From d09ea69e13e8fc6a500ea4c007ab7cb0518cf5db Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Tue, 4 Apr 2023 21:25:56 +0100 Subject: [PATCH 001/102] [ci skip] docs: update upm stable in README --- X10D.Unity/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/X10D.Unity/README.md b/X10D.Unity/README.md index f0e6d4c..2e4e1f6 100644 --- a/X10D.Unity/README.md +++ b/X10D.Unity/README.md @@ -26,7 +26,7 @@ To install X10D in Unity, follow the steps blow: The [upm](https://github.com/oliverbooth/X10D/tree/upm) branch contains the latest nightly - that is the bleeding edge version of X10D. If you'd like to remain on a stable release, specify a commit hash after the `#` instead of `upm`. -The latest current stable is 3.1.0, which is commit [9f3b09661b09e83690318370eea808e70dd4a72c](https://github.com/oliverbooth/X10D/commit/9f3b09661b09e83690318370eea808e70dd4a72c). +The latest current stable is 3.2.0, which is commit [55898d9e70228380b2d039c55e36d89cfe8a0fa2](https://github.com/oliverbooth/X10D/commit/55898d9e70228380b2d039c55e36d89cfe8a0fa2). Keep in mind that referencing a specific commit rather than the `upm` branch will prevent the auto-updater in Unity from detecting new versions. ## Contributing From 47f3a138aaa3840843e032ff28aa700c22fd7fe0 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Wed, 5 Apr 2023 15:06:02 +0100 Subject: [PATCH 002/102] feat: add Unpack for IBinaryInteger This introduces an experiment, to add support for generic math in X10D. So far, build and tests remain passing - this is a good sign. There is potential here. This API is subject to change and may be removed without warning. --- .../Collections/BinaryIntegerExtensions.cs | 89 +++++++++++++++++++ X10D/src/Collections/ByteExtensions.cs | 6 +- X10D/src/Collections/Int16Extensions.cs | 6 +- X10D/src/Collections/Int32Extensions.cs | 6 +- X10D/src/Collections/Int64Extensions.cs | 4 +- 5 files changed, 107 insertions(+), 4 deletions(-) create mode 100644 X10D/src/Collections/BinaryIntegerExtensions.cs diff --git a/X10D/src/Collections/BinaryIntegerExtensions.cs b/X10D/src/Collections/BinaryIntegerExtensions.cs new file mode 100644 index 0000000..2f3a44c --- /dev/null +++ b/X10D/src/Collections/BinaryIntegerExtensions.cs @@ -0,0 +1,89 @@ +#if NET7_0_OR_GREATER +using System.Diagnostics.Contracts; +using System.Numerics; +using System.Runtime.CompilerServices; +using System.Runtime.Intrinsics.X86; +using X10D.CompilerServices; + +namespace X10D.Collections; + +/// +/// Collection-related extension methods for . +/// +public static class BinaryIntegerExtensions +{ + /// + /// Unpacks this integer into a boolean list, treating it as a bit field. + /// + /// The value to unpack. + /// An array of with a length equal to the size of . + [Pure] + [MethodImpl(CompilerResources.MethodImplOptions)] + public static bool[] Unpack(this TInteger value) + where TInteger : unmanaged, IBinaryInteger + { + unsafe + { + var buffer = new bool[sizeof(TInteger) * 8]; + value.Unpack(buffer); + return buffer; + } + } + + /// + /// Unpacks this integer into a boolean list, treating it as a bit field. + /// + /// The value to unpack. + /// When this method returns, contains the unpacked booleans from . + /// is not large enough to contain the result. + [MethodImpl(CompilerResources.MethodImplOptions)] + public static void Unpack(this TInteger value, Span destination) + where TInteger : unmanaged, IBinaryInteger + { + unsafe + { + if (destination.Length < sizeof(TInteger) * 8) + { + throw new ArgumentException(ExceptionMessages.DestinationSpanLengthTooShort, nameof(destination)); + } + } + + switch (value) + { + case byte valueByte when Sse3.IsSupported: + valueByte.UnpackInternal_Ssse3(destination); + break; + + case int valueInt32 when Avx2.IsSupported: + valueInt32.UnpackInternal_Ssse3(destination); + break; + + case int valueInt32 when Sse3.IsSupported: + valueInt32.UnpackInternal_Ssse3(destination); + break; + + case short valueInt16 when Sse3.IsSupported: + valueInt16.UnpackInternal_Ssse3(destination); + break; + + default: + UnpackInternal_Fallback(value, destination); + break; + } + } + + [MethodImpl(CompilerResources.MethodImplOptions)] + internal static void UnpackInternal_Fallback(this TInteger value, Span destination) + where TInteger : unmanaged, IBinaryInteger + { + unsafe + { + int bitCount = sizeof(TInteger) * 8; + for (var index = 0; index < bitCount; index++) + { + destination[index] = (value & (TInteger.One << index)) != TInteger.Zero; + } + } + } +} +#endif diff --git a/X10D/src/Collections/ByteExtensions.cs b/X10D/src/Collections/ByteExtensions.cs index 427afed..5590368 100644 --- a/X10D/src/Collections/ByteExtensions.cs +++ b/X10D/src/Collections/ByteExtensions.cs @@ -1,5 +1,7 @@ -using System.Diagnostics.CodeAnalysis; +#if !NET7_0_OR_GREATER +using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; +#endif using System.Runtime.CompilerServices; using X10D.CompilerServices; @@ -17,6 +19,7 @@ public static class ByteExtensions { private const int Size = sizeof(byte) * 8; +#if !NET7_0_OR_GREATER /// /// Unpacks this 8-bit unsigned integer into a boolean list, treating it as a bit field. /// @@ -56,6 +59,7 @@ public static class ByteExtensions UnpackInternal_Fallback(value, destination); } +#endif [MethodImpl(CompilerResources.MethodImplOptions)] internal static void UnpackInternal_Fallback(this byte value, Span destination) diff --git a/X10D/src/Collections/Int16Extensions.cs b/X10D/src/Collections/Int16Extensions.cs index c53c0fb..c5f8373 100644 --- a/X10D/src/Collections/Int16Extensions.cs +++ b/X10D/src/Collections/Int16Extensions.cs @@ -1,5 +1,7 @@ -using System.Diagnostics.CodeAnalysis; +#if !NET7_0_OR_GREATER +using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; +#endif using System.Runtime.CompilerServices; using X10D.CompilerServices; @@ -17,6 +19,7 @@ public static class Int16Extensions { private const int Size = sizeof(short) * 8; +#if !NET7_0_OR_GREATER /// /// Unpacks this 16-bit signed integer into a boolean list, treating it as a bit field. /// @@ -56,6 +59,7 @@ public static class Int16Extensions UnpackInternal_Fallback(value, destination); } +#endif [MethodImpl(CompilerResources.MethodImplOptions)] internal static void UnpackInternal_Fallback(this short value, Span destination) diff --git a/X10D/src/Collections/Int32Extensions.cs b/X10D/src/Collections/Int32Extensions.cs index 7e2ebaf..60455cd 100644 --- a/X10D/src/Collections/Int32Extensions.cs +++ b/X10D/src/Collections/Int32Extensions.cs @@ -1,5 +1,7 @@ -using System.Diagnostics.CodeAnalysis; +#if !NET7_0_OR_GREATER +using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; +#endif using System.Runtime.CompilerServices; using X10D.CompilerServices; @@ -17,6 +19,7 @@ public static class Int32Extensions { private const int Size = sizeof(int) * 8; +#if !NET7_0_OR_GREATER /// /// Unpacks this 32-bit signed integer into a boolean list, treating it as a bit field. /// @@ -62,6 +65,7 @@ public static class Int32Extensions UnpackInternal_Fallback(value, destination); } +#endif [MethodImpl(CompilerResources.MethodImplOptions)] internal static void UnpackInternal_Fallback(this int value, Span destination) diff --git a/X10D/src/Collections/Int64Extensions.cs b/X10D/src/Collections/Int64Extensions.cs index 5b31a1d..b6fd7ad 100644 --- a/X10D/src/Collections/Int64Extensions.cs +++ b/X10D/src/Collections/Int64Extensions.cs @@ -1,4 +1,5 @@ -using System.Diagnostics.Contracts; +#if !NET7_0_OR_GREATER +using System.Diagnostics.Contracts; namespace X10D.Collections; @@ -41,3 +42,4 @@ public static class Int64Extensions } } } +#endif From b819e6a41830a76b467b6ff45e6870b2fd5a74ee Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Wed, 5 Apr 2023 15:13:21 +0100 Subject: [PATCH 003/102] refactor: revert 47f3a138aaa3840843e032ff28aa700c22fd7fe0 Generic math features will be built in a feature branch to avoid merge conflicts with develop. --- .../Collections/BinaryIntegerExtensions.cs | 89 ------------------- X10D/src/Collections/ByteExtensions.cs | 6 +- X10D/src/Collections/Int16Extensions.cs | 6 +- X10D/src/Collections/Int32Extensions.cs | 6 +- X10D/src/Collections/Int64Extensions.cs | 4 +- 5 files changed, 4 insertions(+), 107 deletions(-) delete mode 100644 X10D/src/Collections/BinaryIntegerExtensions.cs diff --git a/X10D/src/Collections/BinaryIntegerExtensions.cs b/X10D/src/Collections/BinaryIntegerExtensions.cs deleted file mode 100644 index 2f3a44c..0000000 --- a/X10D/src/Collections/BinaryIntegerExtensions.cs +++ /dev/null @@ -1,89 +0,0 @@ -#if NET7_0_OR_GREATER -using System.Diagnostics.Contracts; -using System.Numerics; -using System.Runtime.CompilerServices; -using System.Runtime.Intrinsics.X86; -using X10D.CompilerServices; - -namespace X10D.Collections; - -/// -/// Collection-related extension methods for . -/// -public static class BinaryIntegerExtensions -{ - /// - /// Unpacks this integer into a boolean list, treating it as a bit field. - /// - /// The value to unpack. - /// An array of with a length equal to the size of . - [Pure] - [MethodImpl(CompilerResources.MethodImplOptions)] - public static bool[] Unpack(this TInteger value) - where TInteger : unmanaged, IBinaryInteger - { - unsafe - { - var buffer = new bool[sizeof(TInteger) * 8]; - value.Unpack(buffer); - return buffer; - } - } - - /// - /// Unpacks this integer into a boolean list, treating it as a bit field. - /// - /// The value to unpack. - /// When this method returns, contains the unpacked booleans from . - /// is not large enough to contain the result. - [MethodImpl(CompilerResources.MethodImplOptions)] - public static void Unpack(this TInteger value, Span destination) - where TInteger : unmanaged, IBinaryInteger - { - unsafe - { - if (destination.Length < sizeof(TInteger) * 8) - { - throw new ArgumentException(ExceptionMessages.DestinationSpanLengthTooShort, nameof(destination)); - } - } - - switch (value) - { - case byte valueByte when Sse3.IsSupported: - valueByte.UnpackInternal_Ssse3(destination); - break; - - case int valueInt32 when Avx2.IsSupported: - valueInt32.UnpackInternal_Ssse3(destination); - break; - - case int valueInt32 when Sse3.IsSupported: - valueInt32.UnpackInternal_Ssse3(destination); - break; - - case short valueInt16 when Sse3.IsSupported: - valueInt16.UnpackInternal_Ssse3(destination); - break; - - default: - UnpackInternal_Fallback(value, destination); - break; - } - } - - [MethodImpl(CompilerResources.MethodImplOptions)] - internal static void UnpackInternal_Fallback(this TInteger value, Span destination) - where TInteger : unmanaged, IBinaryInteger - { - unsafe - { - int bitCount = sizeof(TInteger) * 8; - for (var index = 0; index < bitCount; index++) - { - destination[index] = (value & (TInteger.One << index)) != TInteger.Zero; - } - } - } -} -#endif diff --git a/X10D/src/Collections/ByteExtensions.cs b/X10D/src/Collections/ByteExtensions.cs index 5590368..427afed 100644 --- a/X10D/src/Collections/ByteExtensions.cs +++ b/X10D/src/Collections/ByteExtensions.cs @@ -1,7 +1,5 @@ -#if !NET7_0_OR_GREATER -using System.Diagnostics.CodeAnalysis; +using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; -#endif using System.Runtime.CompilerServices; using X10D.CompilerServices; @@ -19,7 +17,6 @@ public static class ByteExtensions { private const int Size = sizeof(byte) * 8; -#if !NET7_0_OR_GREATER /// /// Unpacks this 8-bit unsigned integer into a boolean list, treating it as a bit field. /// @@ -59,7 +56,6 @@ public static class ByteExtensions UnpackInternal_Fallback(value, destination); } -#endif [MethodImpl(CompilerResources.MethodImplOptions)] internal static void UnpackInternal_Fallback(this byte value, Span destination) diff --git a/X10D/src/Collections/Int16Extensions.cs b/X10D/src/Collections/Int16Extensions.cs index c5f8373..c53c0fb 100644 --- a/X10D/src/Collections/Int16Extensions.cs +++ b/X10D/src/Collections/Int16Extensions.cs @@ -1,7 +1,5 @@ -#if !NET7_0_OR_GREATER -using System.Diagnostics.CodeAnalysis; +using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; -#endif using System.Runtime.CompilerServices; using X10D.CompilerServices; @@ -19,7 +17,6 @@ public static class Int16Extensions { private const int Size = sizeof(short) * 8; -#if !NET7_0_OR_GREATER /// /// Unpacks this 16-bit signed integer into a boolean list, treating it as a bit field. /// @@ -59,7 +56,6 @@ public static class Int16Extensions UnpackInternal_Fallback(value, destination); } -#endif [MethodImpl(CompilerResources.MethodImplOptions)] internal static void UnpackInternal_Fallback(this short value, Span destination) diff --git a/X10D/src/Collections/Int32Extensions.cs b/X10D/src/Collections/Int32Extensions.cs index 60455cd..7e2ebaf 100644 --- a/X10D/src/Collections/Int32Extensions.cs +++ b/X10D/src/Collections/Int32Extensions.cs @@ -1,7 +1,5 @@ -#if !NET7_0_OR_GREATER -using System.Diagnostics.CodeAnalysis; +using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; -#endif using System.Runtime.CompilerServices; using X10D.CompilerServices; @@ -19,7 +17,6 @@ public static class Int32Extensions { private const int Size = sizeof(int) * 8; -#if !NET7_0_OR_GREATER /// /// Unpacks this 32-bit signed integer into a boolean list, treating it as a bit field. /// @@ -65,7 +62,6 @@ public static class Int32Extensions UnpackInternal_Fallback(value, destination); } -#endif [MethodImpl(CompilerResources.MethodImplOptions)] internal static void UnpackInternal_Fallback(this int value, Span destination) diff --git a/X10D/src/Collections/Int64Extensions.cs b/X10D/src/Collections/Int64Extensions.cs index b6fd7ad..5b31a1d 100644 --- a/X10D/src/Collections/Int64Extensions.cs +++ b/X10D/src/Collections/Int64Extensions.cs @@ -1,5 +1,4 @@ -#if !NET7_0_OR_GREATER -using System.Diagnostics.Contracts; +using System.Diagnostics.Contracts; namespace X10D.Collections; @@ -42,4 +41,3 @@ public static class Int64Extensions } } } -#endif From e84eef60e6d3f566714b64a4ebcfcb3f93e55867 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Wed, 5 Apr 2023 17:37:26 +0100 Subject: [PATCH 004/102] chore: suppress tfm support build warnings --- X10D.Tests/X10D.Tests.csproj | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/X10D.Tests/X10D.Tests.csproj b/X10D.Tests/X10D.Tests.csproj index 41d2e68..9853d23 100644 --- a/X10D.Tests/X10D.Tests.csproj +++ b/X10D.Tests/X10D.Tests.csproj @@ -10,6 +10,10 @@ true + + true + + From 5d2313fa208ca0670467fe90a0e4710cc0606e99 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Wed, 5 Apr 2023 19:18:06 +0100 Subject: [PATCH 005/102] test: replace playmode tests with NUnit tests (#76) Using yield break; in a coroutine which does not need to be one, that's a paddlin'. --- .../Assets/Tests/Drawing/Color32Tests.cs | 62 ++++++------------ .../Assets/Tests/Drawing/ColorTests.cs | 64 ++++++------------- .../Assets/Tests/Drawing/PointFTests.cs | 8 +-- .../Assets/Tests/Drawing/PointTests.cs | 14 ++-- .../Assets/Tests/Drawing/RandomTests.cs | 58 +++++++---------- .../Assets/Tests/Drawing/RectIntTests.cs | 16 ++--- .../Assets/Tests/Drawing/RectTests.cs | 10 +-- .../Assets/Tests/Drawing/RectangleFTests.cs | 10 +-- .../Assets/Tests/Drawing/RectangleTests.cs | 16 ++--- .../Assets/Tests/Drawing/SizeFTests.cs | 8 +-- .../Assets/Tests/Drawing/SizeTests.cs | 14 ++-- .../Assets/Tests/Numerics/QuaternionTests.cs | 16 ++--- .../Assets/Tests/Numerics/RandomTests.cs | 48 ++++++-------- .../Assets/Tests/Numerics/Vector2IntTests.cs | 34 ++++------ .../Assets/Tests/Numerics/Vector2Tests.cs | 58 ++++++----------- .../Assets/Tests/Numerics/Vector3IntTests.cs | 28 +++----- .../Assets/Tests/Numerics/Vector3Tests.cs | 52 +++++---------- .../Assets/Tests/Numerics/Vector4Tests.cs | 58 ++++++----------- .../Assets/Tests/SingletonTests.cs | 20 +++--- .../Assets/Tests/YieldInstructionTests.cs | 2 +- 20 files changed, 202 insertions(+), 394 deletions(-) diff --git a/X10D.Unity.Tests/Assets/Tests/Drawing/Color32Tests.cs b/X10D.Unity.Tests/Assets/Tests/Drawing/Color32Tests.cs index 3667c4a..b1c7b37 100644 --- a/X10D.Unity.Tests/Assets/Tests/Drawing/Color32Tests.cs +++ b/X10D.Unity.Tests/Assets/Tests/Drawing/Color32Tests.cs @@ -1,8 +1,6 @@ using System; -using System.Collections; using NUnit.Framework; using UnityEngine; -using UnityEngine.TestTools; using X10D.Unity.Drawing; namespace X10D.Unity.Tests.Drawing @@ -18,8 +16,8 @@ namespace X10D.Unity.Tests.Drawing private static readonly Color32 Magenta = new(255, 0, 255, 255); private static readonly Color32 Yellow = new(255, 255, 0, 255); - [UnityTest] - public IEnumerator Deconstruct_ShouldDeconstruct_ToCorrectValues() + [Test] + public void Deconstruct_ShouldDeconstruct_ToCorrectValues() { byte a, r, g, b; @@ -33,12 +31,10 @@ namespace X10D.Unity.Tests.Drawing Assert.AreEqual(255, r); Assert.AreEqual(255, g); Assert.AreEqual(0, b); - - yield break; } - [UnityTest] - public IEnumerator GetClosestConsoleColor_ShouldReturnClosestColor_GivenValidColor() + [Test] + public void GetClosestConsoleColor_ShouldReturnClosestColor_GivenValidColor() { // I know it's just casting... but aim for 100% coverage babyyyy @@ -53,12 +49,10 @@ namespace X10D.Unity.Tests.Drawing Assert.AreEqual(ConsoleColor.Gray, ((Color32)Color.gray).GetClosestConsoleColor()); Assert.AreEqual(ConsoleColor.Gray, ((Color32)Color.grey).GetClosestConsoleColor()); Assert.AreEqual(ConsoleColor.Black, ((Color32)Color.clear).GetClosestConsoleColor()); - - yield break; } - [UnityTest] - public IEnumerator Inverted_ShouldReturnInvertedColor() + [Test] + public void Inverted_ShouldReturnInvertedColor() { Assert.AreEqual(White, Black.Inverted()); Assert.AreEqual(Black, White.Inverted()); @@ -68,78 +62,62 @@ namespace X10D.Unity.Tests.Drawing Assert.AreEqual(Magenta, Green.Inverted()); Assert.AreEqual(Yellow, Blue.Inverted()); Assert.AreEqual(Blue, Yellow.Inverted()); - - yield break; } - [UnityTest] - public IEnumerator Inverted_ShouldIgnoreAlpha() + [Test] + public void Inverted_ShouldIgnoreAlpha() { var expected = new Color32(0, 0, 0, 255); var actual = new Color32(255, 255, 255, 255).Inverted(); Assert.AreEqual(expected, actual); - - yield break; } - [UnityTest] - public IEnumerator ToSystemDrawingColor_ShouldReturnEquivalentColor() + [Test] + public void ToSystemDrawingColor_ShouldReturnEquivalentColor() { System.Drawing.Color expected = System.Drawing.Color.FromArgb(255, 255, 255); System.Drawing.Color actual = White.ToSystemDrawingColor(); Assert.AreEqual(expected, actual); - - yield break; } - [UnityTest] - public IEnumerator ToUnityColor32_ShouldReturnEquivalentColor() + [Test] + public void ToUnityColor32_ShouldReturnEquivalentColor() { Color32 expected = White; Color32 actual = System.Drawing.Color.FromArgb(255, 255, 255).ToUnityColor32(); Assert.AreEqual(expected, actual); - - yield break; } - [UnityTest] - public IEnumerator WithA0_ShouldReturnSameColor_GivenWhite() + [Test] + public void WithA0_ShouldReturnSameColor_GivenWhite() { var transparent = new Color32(255, 255, 255, 0); Assert.AreEqual(transparent, White.WithA(0)); Assert.AreEqual(transparent, transparent.WithA(0)); - - yield break; } - [UnityTest] - public IEnumerator WithB0_ShouldReturnYellow_GivenWhite() + [Test] + public void WithB0_ShouldReturnYellow_GivenWhite() { Assert.AreEqual(Yellow, White.WithB(0)); Assert.AreEqual(Yellow, Yellow.WithB(0)); - - yield break; } - [UnityTest] - public IEnumerator WithG0_ShouldReturnMagenta_GivenWhite() + [Test] + public void WithG0_ShouldReturnMagenta_GivenWhite() { Assert.AreEqual(Magenta, White.WithG(0)); Assert.AreEqual(Magenta, Magenta.WithG(0)); - - yield break; } - [UnityTest] - public IEnumerator WithR0_ShouldReturnCyan_GivenWhite() + [Test] + public void WithR0_ShouldReturnCyan_GivenWhite() { Assert.AreEqual(Cyan, White.WithR(0)); Assert.AreEqual(Cyan, Cyan.WithR(0)); - - yield break; } } } diff --git a/X10D.Unity.Tests/Assets/Tests/Drawing/ColorTests.cs b/X10D.Unity.Tests/Assets/Tests/Drawing/ColorTests.cs index 78031d4..9cdd4ee 100644 --- a/X10D.Unity.Tests/Assets/Tests/Drawing/ColorTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/Drawing/ColorTests.cs @@ -1,10 +1,6 @@ using System; -using System.Collections; -using System.Linq; -using System.Reflection; using NUnit.Framework; using UnityEngine; -using UnityEngine.TestTools; using X10D.Unity.Drawing; namespace X10D.Unity.Tests.Drawing @@ -20,8 +16,8 @@ namespace X10D.Unity.Tests.Drawing private static readonly Color Magenta = new(1, 0, 1); private static readonly Color Yellow = new(1, 1, 0); - [UnityTest] - public IEnumerator Deconstruct_ShouldDeconstruct_ToCorrectValues() + [Test] + public void Deconstruct_ShouldDeconstruct_ToCorrectValues() { float a, r, g, b; @@ -35,12 +31,10 @@ namespace X10D.Unity.Tests.Drawing Assert.AreEqual(1.0f, r); Assert.AreEqual(1.0f, g); Assert.AreEqual(0.0f, b); - - yield break; } - [UnityTest] - public IEnumerator GetClosestConsoleColor_ShouldReturnClosestColor_GivenValidColor() + [Test] + public void GetClosestConsoleColor_ShouldReturnClosestColor_GivenValidColor() { Assert.AreEqual(ConsoleColor.Red, Color.red.GetClosestConsoleColor()); Assert.AreEqual(ConsoleColor.Green, Color.green.GetClosestConsoleColor()); @@ -53,12 +47,10 @@ namespace X10D.Unity.Tests.Drawing Assert.AreEqual(ConsoleColor.Gray, Color.gray.GetClosestConsoleColor()); Assert.AreEqual(ConsoleColor.Gray, Color.grey.GetClosestConsoleColor()); Assert.AreEqual(ConsoleColor.Black, Color.clear.GetClosestConsoleColor()); - - yield break; } - [UnityTest] - public IEnumerator Inverted_ShouldReturnInvertedColor() + [Test] + public void Inverted_ShouldReturnInvertedColor() { Assert.AreEqual(White, Black.Inverted()); Assert.AreEqual(Black, White.Inverted()); @@ -68,78 +60,62 @@ namespace X10D.Unity.Tests.Drawing Assert.AreEqual(Magenta, Green.Inverted()); Assert.AreEqual(Yellow, Blue.Inverted()); Assert.AreEqual(Blue, Yellow.Inverted()); - - yield break; } - [UnityTest] - public IEnumerator Inverted_ShouldIgnoreAlpha() + [Test] + public void Inverted_ShouldIgnoreAlpha() { var expected = new Color(0, 0, 0, 1); var actual = new Color(1, 1, 1, 1).Inverted(); Assert.AreEqual(expected, actual); - - yield break; } - [UnityTest] - public IEnumerator ToSystemDrawingColor_ShouldReturnEquivalentColor() + [Test] + public void ToSystemDrawingColor_ShouldReturnEquivalentColor() { System.Drawing.Color expected = System.Drawing.Color.FromArgb(255, 255, 255); System.Drawing.Color actual = White.ToSystemDrawingColor(); Assert.AreEqual(expected, actual); - - yield break; } - [UnityTest] - public IEnumerator ToUnityColor_ShouldReturnEquivalentColor() + [Test] + public void ToUnityColor_ShouldReturnEquivalentColor() { Color expected = White; Color actual = System.Drawing.Color.FromArgb(255, 255, 255).ToUnityColor(); Assert.AreEqual(expected, actual); - - yield break; } - [UnityTest] - public IEnumerator WithA0_ShouldReturnSameColor_GivenWhite() + [Test] + public void WithA0_ShouldReturnSameColor_GivenWhite() { var transparent = new Color(1, 1, 1, 0); Assert.AreEqual(transparent, White.WithA(0)); Assert.AreEqual(transparent, transparent.WithA(0)); - - yield break; } - [UnityTest] - public IEnumerator WithB0_ShouldReturnYellow_GivenWhite() + [Test] + public void WithB0_ShouldReturnYellow_GivenWhite() { Assert.AreEqual(Yellow, White.WithB(0)); Assert.AreEqual(Yellow, Yellow.WithB(0)); - - yield break; } - [UnityTest] - public IEnumerator WithG0_ShouldReturnMagenta_GivenWhite() + [Test] + public void WithG0_ShouldReturnMagenta_GivenWhite() { Assert.AreEqual(Magenta, White.WithG(0)); Assert.AreEqual(Magenta, Magenta.WithG(0)); - - yield break; } - [UnityTest] - public IEnumerator WithR0_ShouldReturnCyan_GivenWhite() + [Test] + public void WithR0_ShouldReturnCyan_GivenWhite() { Assert.AreEqual(Cyan, White.WithR(0)); Assert.AreEqual(Cyan, Cyan.WithR(0)); - - yield break; } } } diff --git a/X10D.Unity.Tests/Assets/Tests/Drawing/PointFTests.cs b/X10D.Unity.Tests/Assets/Tests/Drawing/PointFTests.cs index 83d70ea..bf949a3 100644 --- a/X10D.Unity.Tests/Assets/Tests/Drawing/PointFTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/Drawing/PointFTests.cs @@ -1,8 +1,6 @@ using System; -using System.Collections; using System.Drawing; using NUnit.Framework; -using UnityEngine.TestTools; using X10D.Core; using X10D.Unity.Drawing; @@ -10,8 +8,8 @@ namespace X10D.Unity.Tests.Drawing { public class PointFTests { - [UnityTest] - public IEnumerator ToUnityVector2_ShouldReturnVector_WithEquivalentMembers() + [Test] + public void ToUnityVector2_ShouldReturnVector_WithEquivalentMembers() { var random = new Random(); var point = new PointF(random.NextSingle(), random.NextSingle()); @@ -19,8 +17,6 @@ namespace X10D.Unity.Tests.Drawing Assert.AreEqual(point.X, vector.x, 1e-6f); Assert.AreEqual(point.Y, vector.y, 1e-6f); - - yield break; } } } diff --git a/X10D.Unity.Tests/Assets/Tests/Drawing/PointTests.cs b/X10D.Unity.Tests/Assets/Tests/Drawing/PointTests.cs index 36b8554..6db859c 100644 --- a/X10D.Unity.Tests/Assets/Tests/Drawing/PointTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/Drawing/PointTests.cs @@ -1,16 +1,14 @@ using System; -using System.Collections; using System.Drawing; using NUnit.Framework; -using UnityEngine.TestTools; using X10D.Unity.Drawing; namespace X10D.Unity.Tests.Drawing { public class PointTests { - [UnityTest] - public IEnumerator ToUnityVector2_ShouldReturnVector_WithEquivalentMembers() + [Test] + public void ToUnityVector2_ShouldReturnVector_WithEquivalentMembers() { var random = new Random(); var point = new Point(random.Next(), random.Next()); @@ -18,12 +16,10 @@ namespace X10D.Unity.Tests.Drawing Assert.AreEqual(point.X, vector.x); Assert.AreEqual(point.Y, vector.y); - - yield break; } - [UnityTest] - public IEnumerator ToUnityVector2Int_ShouldReturnVector_WithEquivalentMembers() + [Test] + public void ToUnityVector2Int_ShouldReturnVector_WithEquivalentMembers() { var random = new Random(); var point = new Point(random.Next(), random.Next()); @@ -31,8 +27,6 @@ namespace X10D.Unity.Tests.Drawing Assert.AreEqual(point.X, vector.x); Assert.AreEqual(point.Y, vector.y); - - yield break; } } } diff --git a/X10D.Unity.Tests/Assets/Tests/Drawing/RandomTests.cs b/X10D.Unity.Tests/Assets/Tests/Drawing/RandomTests.cs index 33c69e9..3bb5543 100644 --- a/X10D.Unity.Tests/Assets/Tests/Drawing/RandomTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/Drawing/RandomTests.cs @@ -1,10 +1,8 @@ #nullable enable using System; -using System.Collections; using NUnit.Framework; using UnityEngine; -using UnityEngine.TestTools; using X10D.Unity.Drawing; using Random = System.Random; @@ -12,8 +10,8 @@ namespace X10D.Unity.Tests.Drawing { public class RandomTests { - [UnityTest] - public IEnumerator NextColorArgb_ShouldReturn331515e5_GivenSeed1234() + [Test] + public void NextColorArgb_ShouldReturn331515e5_GivenSeed1234() { var random = new Random(1234); var color = random.NextColorArgb(); @@ -21,35 +19,31 @@ namespace X10D.Unity.Tests.Drawing Assert.AreEqual(0.391597569f, color.g, 1e-6f); Assert.AreEqual(0.675019085f, color.b, 1e-6f); Assert.AreEqual(0.234300315f, color.a, 1e-6f); - yield break; } - [UnityTest] - public IEnumerator NextColorArgb_ShouldThrow_GivenNull() + [Test] + public void NextColorArgb_ShouldThrow_GivenNull() { - Random? random = null; - Assert.Throws(() => random!.NextColorArgb()); - yield break; + Random random = null!; + Assert.Throws(() => random.NextColorArgb()); } - [UnityTest] - public IEnumerator NextColor32Argb_ShouldReturn331515e5_GivenSeed1234() + [Test] + public void NextColor32Argb_ShouldReturn331515e5_GivenSeed1234() { var random = new Random(1234); Assert.AreEqual(new Color32(21, 21, 229, 51), random.NextColor32Argb()); - yield break; } - [UnityTest] - public IEnumerator NextColor32Argb_ShouldThrow_GivenNull() + [Test] + public void NextColor32Argb_ShouldThrow_GivenNull() { - Random? random = null; - Assert.Throws(() => random!.NextColor32Argb()); - yield break; + Random random = null!; + Assert.Throws(() => random.NextColor32Argb()); } - [UnityTest] - public IEnumerator NextColorRgb_ShouldReturn1515e5_GivenSeed1234() + [Test] + public void NextColorRgb_ShouldReturn1515e5_GivenSeed1234() { var random = new Random(1234); var color = random.NextColorRgb(); @@ -57,31 +51,27 @@ namespace X10D.Unity.Tests.Drawing Assert.AreEqual(0.373868465f, color.g, 1e-6f); Assert.AreEqual(0.391597569f, color.b, 1e-6f); Assert.AreEqual(1, color.a, 1e-6f); - yield break; } - [UnityTest] - public IEnumerator NextColorRgb_ShouldThrow_GivenNull() + [Test] + public void NextColorRgb_ShouldThrow_GivenNull() { - Random? random = null; - Assert.Throws(() => random!.NextColorRgb()); - yield break; + Random random = null!; + Assert.Throws(() => random.NextColorRgb()); } - [UnityTest] - public IEnumerator NextColor32Rgb_ShouldReturn1515e5_GivenSeed1234() + [Test] + public void NextColor32Rgb_ShouldReturn1515e5_GivenSeed1234() { var random = new Random(1234); Assert.AreEqual(new Color32(21, 21, 229, 255), random.NextColor32Rgb()); - yield break; } - [UnityTest] - public IEnumerator NextColor32Rgb_ShouldThrow_GivenNull() + [Test] + public void NextColor32Rgb_ShouldThrow_GivenNull() { - Random? random = null; - Assert.Throws(() => random!.NextColor32Rgb()); - yield break; + Random random = null!; + Assert.Throws(() => random.NextColor32Rgb()); } } } diff --git a/X10D.Unity.Tests/Assets/Tests/Drawing/RectIntTests.cs b/X10D.Unity.Tests/Assets/Tests/Drawing/RectIntTests.cs index 3bf96b6..cd8a576 100644 --- a/X10D.Unity.Tests/Assets/Tests/Drawing/RectIntTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/Drawing/RectIntTests.cs @@ -1,7 +1,5 @@ -using System.Collections; -using NUnit.Framework; +using NUnit.Framework; using UnityEngine; -using UnityEngine.TestTools; using X10D.Unity.Drawing; using Random = System.Random; @@ -9,8 +7,8 @@ namespace X10D.Unity.Tests.Drawing { public class RectIntTests { - [UnityTest] - public IEnumerator ToSystemRectangle_ShouldReturnRectangleF_WithEquivalentMembers() + [Test] + public void ToSystemRectangle_ShouldReturnRectangleF_WithEquivalentMembers() { var random = new Random(); var rect = new RectInt(random.Next(), random.Next(), random.Next(), random.Next()); @@ -20,12 +18,10 @@ namespace X10D.Unity.Tests.Drawing Assert.AreEqual(rect.y, rectangle.Y); Assert.AreEqual(rect.width, rectangle.Width); Assert.AreEqual(rect.height, rectangle.Height); - - yield break; } - [UnityTest] - public IEnumerator ToSystemRectangleF_ShouldReturnRectangleF_WithEquivalentMembers() + [Test] + public void ToSystemRectangleF_ShouldReturnRectangleF_WithEquivalentMembers() { var random = new Random(); var rect = new RectInt(random.Next(), random.Next(), random.Next(), random.Next()); @@ -35,8 +31,6 @@ namespace X10D.Unity.Tests.Drawing Assert.AreEqual(rect.y, rectangle.Y); Assert.AreEqual(rect.width, rectangle.Width); Assert.AreEqual(rect.height, rectangle.Height); - - yield break; } } } diff --git a/X10D.Unity.Tests/Assets/Tests/Drawing/RectTests.cs b/X10D.Unity.Tests/Assets/Tests/Drawing/RectTests.cs index eb5a94d..52ce153 100644 --- a/X10D.Unity.Tests/Assets/Tests/Drawing/RectTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/Drawing/RectTests.cs @@ -1,7 +1,5 @@ -using System.Collections; -using NUnit.Framework; +using NUnit.Framework; using UnityEngine; -using UnityEngine.TestTools; using X10D.Core; using X10D.Unity.Drawing; using Random = System.Random; @@ -10,8 +8,8 @@ namespace X10D.Unity.Tests.Drawing { public class RectTests { - [UnityTest] - public IEnumerator ToSystemRectangleF_ShouldReturnRectangleF_WithEquivalentMembers() + [Test] + public void ToSystemRectangleF_ShouldReturnRectangleF_WithEquivalentMembers() { var random = new Random(); var rect = new Rect(random.NextSingle(), random.NextSingle(), random.NextSingle(), random.NextSingle()); @@ -21,8 +19,6 @@ namespace X10D.Unity.Tests.Drawing Assert.AreEqual(rect.y, rectangle.Y, 1e-6f); Assert.AreEqual(rect.width, rectangle.Width, 1e-6f); Assert.AreEqual(rect.height, rectangle.Height, 1e-6f); - - yield break; } } } diff --git a/X10D.Unity.Tests/Assets/Tests/Drawing/RectangleFTests.cs b/X10D.Unity.Tests/Assets/Tests/Drawing/RectangleFTests.cs index 32676c4..0a99c36 100644 --- a/X10D.Unity.Tests/Assets/Tests/Drawing/RectangleFTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/Drawing/RectangleFTests.cs @@ -1,7 +1,5 @@ -using System.Collections; -using System.Drawing; +using System.Drawing; using NUnit.Framework; -using UnityEngine.TestTools; using X10D.Core; using X10D.Unity.Drawing; using Random = System.Random; @@ -10,8 +8,8 @@ namespace X10D.Unity.Tests.Drawing { public class RectangleFTests { - [UnityTest] - public IEnumerator ToUnityRect_ShouldReturnRect_WithEquivalentMembers() + [Test] + public void ToUnityRect_ShouldReturnRect_WithEquivalentMembers() { var random = new Random(); var rectangle = new RectangleF(random.NextSingle(), random.NextSingle(), random.NextSingle(), random.NextSingle()); @@ -21,8 +19,6 @@ namespace X10D.Unity.Tests.Drawing Assert.AreEqual(rectangle.Y, rect.y, 1e-6f); Assert.AreEqual(rectangle.Width, rect.width, 1e-6f); Assert.AreEqual(rectangle.Height, rect.height, 1e-6f); - - yield break; } } } diff --git a/X10D.Unity.Tests/Assets/Tests/Drawing/RectangleTests.cs b/X10D.Unity.Tests/Assets/Tests/Drawing/RectangleTests.cs index 632e5d6..ef7744f 100644 --- a/X10D.Unity.Tests/Assets/Tests/Drawing/RectangleTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/Drawing/RectangleTests.cs @@ -1,7 +1,5 @@ -using System.Collections; -using System.Drawing; +using System.Drawing; using NUnit.Framework; -using UnityEngine.TestTools; using X10D.Unity.Drawing; using Random = System.Random; @@ -9,8 +7,8 @@ namespace X10D.Unity.Tests.Drawing { public class RectangleTests { - [UnityTest] - public IEnumerator ToUnityRect_ShouldReturnRect_WithEquivalentMembers() + [Test] + public void ToUnityRect_ShouldReturnRect_WithEquivalentMembers() { var random = new Random(); var rectangle = new Rectangle(random.Next(), random.Next(), random.Next(), random.Next()); @@ -20,12 +18,10 @@ namespace X10D.Unity.Tests.Drawing Assert.AreEqual(rectangle.Y, rect.y); Assert.AreEqual(rectangle.Width, rect.width); Assert.AreEqual(rectangle.Height, rect.height); - - yield break; } - [UnityTest] - public IEnumerator ToUnityRectInt_ShouldReturnRect_WithEquivalentMembers() + [Test] + public void ToUnityRectInt_ShouldReturnRect_WithEquivalentMembers() { var random = new Random(); var rectangle = new Rectangle(random.Next(), random.Next(), random.Next(), random.Next()); @@ -35,8 +31,6 @@ namespace X10D.Unity.Tests.Drawing Assert.AreEqual(rectangle.Y, rect.y); Assert.AreEqual(rectangle.Width, rect.width); Assert.AreEqual(rectangle.Height, rect.height); - - yield break; } } } diff --git a/X10D.Unity.Tests/Assets/Tests/Drawing/SizeFTests.cs b/X10D.Unity.Tests/Assets/Tests/Drawing/SizeFTests.cs index e677867..2eb711f 100644 --- a/X10D.Unity.Tests/Assets/Tests/Drawing/SizeFTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/Drawing/SizeFTests.cs @@ -1,8 +1,6 @@ using System; -using System.Collections; using System.Drawing; using NUnit.Framework; -using UnityEngine.TestTools; using X10D.Core; using X10D.Unity.Drawing; @@ -10,8 +8,8 @@ namespace X10D.Unity.Tests.Drawing { public class SizeFTests { - [UnityTest] - public IEnumerator ToUnityVector2_ShouldReturnVector_WithEquivalentMembers() + [Test] + public void ToUnityVector2_ShouldReturnVector_WithEquivalentMembers() { var random = new Random(); var size = new SizeF(random.NextSingle(), random.NextSingle()); @@ -19,8 +17,6 @@ namespace X10D.Unity.Tests.Drawing Assert.AreEqual(size.Width, vector.x, 1e-6f); Assert.AreEqual(size.Height, vector.y, 1e-6f); - - yield break; } } } diff --git a/X10D.Unity.Tests/Assets/Tests/Drawing/SizeTests.cs b/X10D.Unity.Tests/Assets/Tests/Drawing/SizeTests.cs index 0832375..23bc8ec 100644 --- a/X10D.Unity.Tests/Assets/Tests/Drawing/SizeTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/Drawing/SizeTests.cs @@ -1,16 +1,14 @@ using System; -using System.Collections; using System.Drawing; using NUnit.Framework; -using UnityEngine.TestTools; using X10D.Unity.Drawing; namespace X10D.Unity.Tests.Drawing { public class SizeTests { - [UnityTest] - public IEnumerator ToUnityVector2_ShouldReturnVector_WithEquivalentMembers() + [Test] + public void ToUnityVector2_ShouldReturnVector_WithEquivalentMembers() { var random = new Random(); var size = new Size(random.Next(), random.Next()); @@ -18,12 +16,10 @@ namespace X10D.Unity.Tests.Drawing Assert.AreEqual(size.Width, vector.x); Assert.AreEqual(size.Height, vector.y); - - yield break; } - [UnityTest] - public IEnumerator ToUnityVector2Int_ShouldReturnVector_WithEquivalentMembers() + [Test] + public void ToUnityVector2Int_ShouldReturnVector_WithEquivalentMembers() { var random = new Random(); var size = new Size(random.Next(), random.Next()); @@ -31,8 +27,6 @@ namespace X10D.Unity.Tests.Drawing Assert.AreEqual(size.Width, vector.x); Assert.AreEqual(size.Height, vector.y); - - yield break; } } } diff --git a/X10D.Unity.Tests/Assets/Tests/Numerics/QuaternionTests.cs b/X10D.Unity.Tests/Assets/Tests/Numerics/QuaternionTests.cs index a486a75..ebd0698 100644 --- a/X10D.Unity.Tests/Assets/Tests/Numerics/QuaternionTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/Numerics/QuaternionTests.cs @@ -1,7 +1,5 @@ -using System.Collections; -using NUnit.Framework; +using NUnit.Framework; using UnityEngine; -using UnityEngine.TestTools; using X10D.Core; using X10D.Unity.Numerics; using Random = System.Random; @@ -10,8 +8,8 @@ namespace X10D.Unity.Tests.Numerics { public class QuaternionTests { - [UnityTest] - public IEnumerator ToSystemQuaternion_ShouldReturnQuaternion_WithEqualComponents() + [Test] + public void ToSystemQuaternion_ShouldReturnQuaternion_WithEqualComponents() { var random = new Random(); float x = random.NextSingle(); @@ -26,12 +24,10 @@ namespace X10D.Unity.Tests.Numerics Assert.AreEqual(quaternion.y, systemQuaternion.Y, 1e-6f); Assert.AreEqual(quaternion.z, systemQuaternion.Z, 1e-6f); Assert.AreEqual(quaternion.w, systemQuaternion.W, 1e-6f); - - yield break; } - [UnityTest] - public IEnumerator ToUnityQuaternion_ShouldReturnQuaternion_WithEqualComponents() + [Test] + public void ToUnityQuaternion_ShouldReturnQuaternion_WithEqualComponents() { var random = new Random(); float x = random.NextSingle(); @@ -46,8 +42,6 @@ namespace X10D.Unity.Tests.Numerics Assert.AreEqual(quaternion.Y, unityQuaternion.y, 1e-6f); Assert.AreEqual(quaternion.Z, unityQuaternion.z, 1e-6f); Assert.AreEqual(quaternion.W, unityQuaternion.w, 1e-6f); - - yield break; } } } diff --git a/X10D.Unity.Tests/Assets/Tests/Numerics/RandomTests.cs b/X10D.Unity.Tests/Assets/Tests/Numerics/RandomTests.cs index 4d768c2..5c24bc8 100644 --- a/X10D.Unity.Tests/Assets/Tests/Numerics/RandomTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/Numerics/RandomTests.cs @@ -1,63 +1,55 @@ #nullable enable using System; -using System.Collections; using NUnit.Framework; -using UnityEngine.TestTools; using X10D.Unity.Numerics; namespace X10D.Unity.Tests.Numerics { public class RandomTests { - [UnityTest] - public IEnumerator NextUnitVector2_ShouldReturnVector_WithMagnitude1() + [Test] + public void NextUnitVector2_ShouldReturnVector_WithMagnitude1() { var random = new Random(); var vector = random.NextUnitVector2(); Assert.AreEqual(1, vector.magnitude, 1e-6); - yield break; } - [UnityTest] - public IEnumerator NextUnitVector2_ShouldThrow_GivenNullRandom() + [Test] + public void NextUnitVector2_ShouldThrow_GivenNullRandom() { - Random? random = null; - Assert.Throws(() => random!.NextUnitVector2()); - yield break; + Random random = null!; + Assert.Throws(() => random.NextUnitVector2()); } - [UnityTest] - public IEnumerator NextUnitVector3_ShouldReturnVector_WithMagnitude1() + [Test] + public void NextUnitVector3_ShouldReturnVector_WithMagnitude1() { var random = new Random(); var vector = random.NextUnitVector3(); Assert.AreEqual(1, vector.magnitude, 1e-6); - yield break; } - [UnityTest] - public IEnumerator NextUnitVector3_ShouldThrow_GivenNullRandom() + [Test] + public void NextUnitVector3_ShouldThrow_GivenNullRandom() { - Random? random = null; - Assert.Throws(() => random!.NextUnitVector3()); - yield break; + Random random = null!; + Assert.Throws(() => random.NextUnitVector3()); } - [UnityTest] - public IEnumerator NextRotation_ShouldThrow_GivenNullRandom() + [Test] + public void NextRotation_ShouldThrow_GivenNullRandom() { - Random random = null; - Assert.Throws(() => random!.NextRotation()); - yield break; + Random random = null!; + Assert.Throws(() => random.NextRotation()); } - [UnityTest] - public IEnumerator NextRotationUniform_ShouldThrow_GivenNullRandom() + [Test] + public void NextRotationUniform_ShouldThrow_GivenNullRandom() { - Random? random = null; - Assert.Throws(() => random!.NextRotationUniform()); - yield break; + Random random = null!; + Assert.Throws(() => random.NextRotationUniform()); } } } diff --git a/X10D.Unity.Tests/Assets/Tests/Numerics/Vector2IntTests.cs b/X10D.Unity.Tests/Assets/Tests/Numerics/Vector2IntTests.cs index eb1b217..a4e2fbd 100644 --- a/X10D.Unity.Tests/Assets/Tests/Numerics/Vector2IntTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/Numerics/Vector2IntTests.cs @@ -1,7 +1,5 @@ -using System.Collections; -using NUnit.Framework; +using NUnit.Framework; using UnityEngine; -using UnityEngine.TestTools; using X10D.Unity.Numerics; using Random = System.Random; @@ -9,20 +7,18 @@ namespace X10D.Unity.Tests.Numerics { public class Vector2IntTests { - [UnityTest] - public IEnumerator Deconstruct_ShouldReturnCorrectValues() + [Test] + public void Deconstruct_ShouldReturnCorrectValues() { var vector = new Vector2Int(1, 2); (int x, int y) = vector; Assert.AreEqual(1, x); Assert.AreEqual(2, y); - - yield break; } - [UnityTest] - public IEnumerator ToSystemPoint_ShouldReturnPoint_WithEquivalentMembers() + [Test] + public void ToSystemPoint_ShouldReturnPoint_WithEquivalentMembers() { var random = new Random(); int x = random.Next(); @@ -33,12 +29,10 @@ namespace X10D.Unity.Tests.Numerics Assert.AreEqual(vector.x, point.X); Assert.AreEqual(vector.y, point.Y); - - yield break; } - [UnityTest] - public IEnumerator ToSystemSize_ShouldReturnSize_WithEquivalentMembers() + [Test] + public void ToSystemSize_ShouldReturnSize_WithEquivalentMembers() { var random = new Random(); int x = random.Next(); @@ -49,12 +43,10 @@ namespace X10D.Unity.Tests.Numerics Assert.AreEqual(vector.x, point.Width); Assert.AreEqual(vector.y, point.Height); - - yield break; } - [UnityTest] - public IEnumerator WithX_ShouldReturnVectorWithNewX_GivenVector() + [Test] + public void WithX_ShouldReturnVectorWithNewX_GivenVector() { Assert.AreEqual(Vector2Int.up, Vector2Int.one.WithX(0)); Assert.AreEqual(Vector2Int.zero, Vector2Int.zero.WithX(0)); @@ -65,12 +57,10 @@ namespace X10D.Unity.Tests.Numerics Assert.AreEqual(Vector2Int.right, Vector2Int.zero.WithX(1)); Assert.AreEqual(Vector2Int.right, Vector2Int.right.WithX(1)); Assert.AreEqual(Vector2Int.one, Vector2Int.up.WithX(1)); - - yield break; } - [UnityTest] - public IEnumerator WithY_ShouldReturnVectorWithNewY_GivenVector() + [Test] + public void WithY_ShouldReturnVectorWithNewY_GivenVector() { Assert.AreEqual(Vector2Int.right, Vector2Int.one.WithY(0)); Assert.AreEqual(Vector2Int.zero, Vector2Int.zero.WithY(0)); @@ -81,8 +71,6 @@ namespace X10D.Unity.Tests.Numerics Assert.AreEqual(Vector2Int.up, Vector2Int.zero.WithY(1)); Assert.AreEqual(Vector2Int.one, Vector2Int.right.WithY(1)); Assert.AreEqual(Vector2Int.up, Vector2Int.up.WithY(1)); - - yield break; } } } diff --git a/X10D.Unity.Tests/Assets/Tests/Numerics/Vector2Tests.cs b/X10D.Unity.Tests/Assets/Tests/Numerics/Vector2Tests.cs index 3be36d0..fd499c4 100644 --- a/X10D.Unity.Tests/Assets/Tests/Numerics/Vector2Tests.cs +++ b/X10D.Unity.Tests/Assets/Tests/Numerics/Vector2Tests.cs @@ -1,7 +1,5 @@ -using System.Collections; -using NUnit.Framework; +using NUnit.Framework; using UnityEngine; -using UnityEngine.TestTools; using X10D.Core; using X10D.Unity.Numerics; using Random = System.Random; @@ -10,44 +8,38 @@ namespace X10D.Unity.Tests.Numerics { public class Vector2Tests { - [UnityTest] - public IEnumerator Deconstruct_ShouldReturnCorrectValues() + [Test] + public void Deconstruct_ShouldReturnCorrectValues() { var vector = new Vector2(1, 2); (float x, float y) = vector; Assert.AreEqual(1, x); Assert.AreEqual(2, y); - - yield break; } - [UnityTest] - public IEnumerator Round_ShouldRoundToNearestInteger_GivenNoParameters() + [Test] + public void Round_ShouldRoundToNearestInteger_GivenNoParameters() { var vector = new Vector2(1.5f, 2.6f); var rounded = vector.Round(); Assert.AreEqual(2, rounded.x); Assert.AreEqual(3, rounded.y); - - yield break; } - [UnityTest] - public IEnumerator Round_ShouldRoundToNearest10_GivenPrecision10() + [Test] + public void Round_ShouldRoundToNearest10_GivenPrecision10() { var vector = new Vector2(1.5f, 25.2f); var rounded = vector.Round(10); Assert.AreEqual(0, rounded.x); Assert.AreEqual(30, rounded.y); - - yield break; } - [UnityTest] - public IEnumerator ToSystemPointF_ShouldReturnPoint_WithEquivalentMembers() + [Test] + public void ToSystemPointF_ShouldReturnPoint_WithEquivalentMembers() { var random = new Random(); float x = random.NextSingle(); @@ -58,12 +50,10 @@ namespace X10D.Unity.Tests.Numerics Assert.AreEqual(vector.x, point.X, 1e-6f); Assert.AreEqual(vector.y, point.Y, 1e-6f); - - yield break; } - [UnityTest] - public IEnumerator ToSystemSizeF_ShouldReturnSize_WithEquivalentMembers() + [Test] + public void ToSystemSizeF_ShouldReturnSize_WithEquivalentMembers() { var random = new Random(); float x = random.NextSingle(); @@ -74,12 +64,10 @@ namespace X10D.Unity.Tests.Numerics Assert.AreEqual(vector.x, point.Width, 1e-6f); Assert.AreEqual(vector.y, point.Height, 1e-6f); - - yield break; } - [UnityTest] - public IEnumerator ToSystemVector_ShouldReturnVector_WithEqualComponents() + [Test] + public void ToSystemVector_ShouldReturnVector_WithEqualComponents() { var random = new Random(); float x = random.NextSingle(); @@ -91,12 +79,10 @@ namespace X10D.Unity.Tests.Numerics Assert.AreEqual(vector.magnitude, systemVector.Length(), 1e-6f); Assert.AreEqual(vector.x, systemVector.X, 1e-6f); Assert.AreEqual(vector.y, systemVector.Y, 1e-6f); - - yield break; } - [UnityTest] - public IEnumerator ToUnityVector_ShouldReturnVector_WithEqualComponents() + [Test] + public void ToUnityVector_ShouldReturnVector_WithEqualComponents() { var random = new Random(); float x = random.NextSingle(); @@ -108,12 +94,10 @@ namespace X10D.Unity.Tests.Numerics Assert.AreEqual(vector.Length(), unityVector.magnitude, 1e-6f); Assert.AreEqual(vector.X, unityVector.x, 1e-6f); Assert.AreEqual(vector.Y, unityVector.y, 1e-6f); - - yield break; } - [UnityTest] - public IEnumerator WithX_ShouldReturnVectorWithNewX_GivenVector() + [Test] + public void WithX_ShouldReturnVectorWithNewX_GivenVector() { Assert.AreEqual(Vector2.up, Vector2.one.WithX(0)); Assert.AreEqual(Vector2.zero, Vector2.zero.WithX(0)); @@ -124,12 +108,10 @@ namespace X10D.Unity.Tests.Numerics Assert.AreEqual(Vector2.right, Vector2.zero.WithX(1)); Assert.AreEqual(Vector2.right, Vector2.right.WithX(1)); Assert.AreEqual(Vector2.one, Vector2.up.WithX(1)); - - yield break; } - [UnityTest] - public IEnumerator WithY_ShouldReturnVectorWithNewY_GivenVector() + [Test] + public void WithY_ShouldReturnVectorWithNewY_GivenVector() { Assert.AreEqual(Vector2.right, Vector2.one.WithY(0)); Assert.AreEqual(Vector2.zero, Vector2.zero.WithY(0)); @@ -140,8 +122,6 @@ namespace X10D.Unity.Tests.Numerics Assert.AreEqual(Vector2.up, Vector2.zero.WithY(1)); Assert.AreEqual(Vector2.one, Vector2.right.WithY(1)); Assert.AreEqual(Vector2.up, Vector2.up.WithY(1)); - - yield break; } } } diff --git a/X10D.Unity.Tests/Assets/Tests/Numerics/Vector3IntTests.cs b/X10D.Unity.Tests/Assets/Tests/Numerics/Vector3IntTests.cs index 21bf438..59b028e 100644 --- a/X10D.Unity.Tests/Assets/Tests/Numerics/Vector3IntTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/Numerics/Vector3IntTests.cs @@ -1,15 +1,13 @@ -using System.Collections; -using NUnit.Framework; +using NUnit.Framework; using UnityEngine; -using UnityEngine.TestTools; using X10D.Unity.Numerics; namespace X10D.Unity.Tests.Numerics { public class Vector3IntTests { - [UnityTest] - public IEnumerator Deconstruct_ShouldReturnCorrectValues() + [Test] + public void Deconstruct_ShouldReturnCorrectValues() { var vector = new Vector3Int(1, 2, 3); (float x, float y, float z) = vector; @@ -17,12 +15,10 @@ namespace X10D.Unity.Tests.Numerics Assert.AreEqual(1, x); Assert.AreEqual(2, y); Assert.AreEqual(3, z); - - yield break; } - [UnityTest] - public IEnumerator WithX_ShouldReturnVectorWithNewX_GivenVector() + [Test] + public void WithX_ShouldReturnVectorWithNewX_GivenVector() { Assert.AreEqual(new Vector3Int(0, 1, 1), Vector3Int.one.WithX(0)); Assert.AreEqual(Vector3Int.zero, Vector3Int.zero.WithX(0)); @@ -35,12 +31,10 @@ namespace X10D.Unity.Tests.Numerics Assert.AreEqual(Vector3Int.right, Vector3Int.right.WithX(1)); Assert.AreEqual(new Vector3Int(1, 1, 0), Vector3Int.up.WithX(1)); Assert.AreEqual(new Vector3Int(1, 0, 1), Vector3Int.forward.WithX(1)); - - yield break; } - [UnityTest] - public IEnumerator WithY_ShouldReturnVectorWithNewY_GivenVector() + [Test] + public void WithY_ShouldReturnVectorWithNewY_GivenVector() { Assert.AreEqual(new Vector3Int(1, 0, 1), Vector3Int.one.WithY(0)); Assert.AreEqual(Vector3Int.zero, Vector3Int.zero.WithY(0)); @@ -53,12 +47,10 @@ namespace X10D.Unity.Tests.Numerics Assert.AreEqual(new Vector3Int(1, 1, 0), Vector3Int.right.WithY(1)); Assert.AreEqual(Vector3Int.up, Vector3Int.up.WithY(1)); Assert.AreEqual(new Vector3Int(0, 1, 1), Vector3Int.forward.WithY(1)); - - yield break; } - [UnityTest] - public IEnumerator WithZ_ShouldReturnVectorWithNewZ_GivenVector() + [Test] + public void WithZ_ShouldReturnVectorWithNewZ_GivenVector() { Assert.AreEqual(new Vector3Int(1, 1, 0), Vector3Int.one.WithZ(0)); Assert.AreEqual(Vector3Int.zero, Vector3Int.zero.WithZ(0)); @@ -71,8 +63,6 @@ namespace X10D.Unity.Tests.Numerics Assert.AreEqual(new Vector3Int(1, 0, 1), Vector3Int.right.WithZ(1)); Assert.AreEqual(new Vector3Int(0, 1, 1), Vector3Int.up.WithZ(1)); Assert.AreEqual(Vector3Int.forward, Vector3Int.forward.WithZ(1)); - - yield break; } } } diff --git a/X10D.Unity.Tests/Assets/Tests/Numerics/Vector3Tests.cs b/X10D.Unity.Tests/Assets/Tests/Numerics/Vector3Tests.cs index 08ebed9..4df9a07 100644 --- a/X10D.Unity.Tests/Assets/Tests/Numerics/Vector3Tests.cs +++ b/X10D.Unity.Tests/Assets/Tests/Numerics/Vector3Tests.cs @@ -1,7 +1,5 @@ -using System.Collections; -using NUnit.Framework; +using NUnit.Framework; using UnityEngine; -using UnityEngine.TestTools; using X10D.Core; using X10D.Unity.Numerics; using Random = System.Random; @@ -10,8 +8,8 @@ namespace X10D.Unity.Tests.Numerics { public class Vector3Tests { - [UnityTest] - public IEnumerator Deconstruct_ShouldReturnCorrectValues() + [Test] + public void Deconstruct_ShouldReturnCorrectValues() { var vector = new Vector3(1, 2, 3); (float x, float y, float z) = vector; @@ -19,12 +17,10 @@ namespace X10D.Unity.Tests.Numerics Assert.AreEqual(1, x); Assert.AreEqual(2, y); Assert.AreEqual(3, z); - - yield break; } - [UnityTest] - public IEnumerator Round_ShouldRoundToNearestInteger_GivenNoParameters() + [Test] + public void Round_ShouldRoundToNearestInteger_GivenNoParameters() { var vector = new Vector3(1.5f, 2.6f, -5.2f); var rounded = vector.Round(); @@ -32,12 +28,10 @@ namespace X10D.Unity.Tests.Numerics Assert.AreEqual(2, rounded.x); Assert.AreEqual(3, rounded.y); Assert.AreEqual(-5, rounded.z); - - yield break; } - [UnityTest] - public IEnumerator Round_ShouldRoundToNearest10_GivenPrecision10() + [Test] + public void Round_ShouldRoundToNearest10_GivenPrecision10() { var vector = new Vector3(1.5f, 25.2f, -12.5f); var rounded = vector.Round(10); @@ -45,12 +39,10 @@ namespace X10D.Unity.Tests.Numerics Assert.AreEqual(0, rounded.x); Assert.AreEqual(30, rounded.y); Assert.AreEqual(-10, rounded.z); - - yield break; } - [UnityTest] - public IEnumerator ToSystemVector_ShouldReturnVector_WithEqualComponents() + [Test] + public void ToSystemVector_ShouldReturnVector_WithEqualComponents() { var random = new Random(); float x = random.NextSingle(); @@ -64,12 +56,10 @@ namespace X10D.Unity.Tests.Numerics Assert.AreEqual(vector.x, systemVector.X, 1e-6f); Assert.AreEqual(vector.y, systemVector.Y, 1e-6f); Assert.AreEqual(vector.z, systemVector.Z, 1e-6f); - - yield break; } - [UnityTest] - public IEnumerator ToUnityVector_ShouldReturnVector_WithEqualComponents() + [Test] + public void ToUnityVector_ShouldReturnVector_WithEqualComponents() { var random = new Random(); float x = random.NextSingle(); @@ -83,12 +73,10 @@ namespace X10D.Unity.Tests.Numerics Assert.AreEqual(vector.X, unityVector.x, 1e-6f); Assert.AreEqual(vector.Y, unityVector.y, 1e-6f); Assert.AreEqual(vector.Z, unityVector.z, 1e-6f); - - yield break; } - [UnityTest] - public IEnumerator WithX_ShouldReturnVectorWithNewX_GivenVector() + [Test] + public void WithX_ShouldReturnVectorWithNewX_GivenVector() { Assert.AreEqual(new Vector3(0, 1, 1), Vector3.one.WithX(0)); Assert.AreEqual(Vector3.zero, Vector3.zero.WithX(0)); @@ -101,12 +89,10 @@ namespace X10D.Unity.Tests.Numerics Assert.AreEqual(Vector3.right, Vector3.right.WithX(1)); Assert.AreEqual(new Vector3(1, 1, 0), Vector3.up.WithX(1)); Assert.AreEqual(new Vector3(1, 0, 1), Vector3.forward.WithX(1)); - - yield break; } - [UnityTest] - public IEnumerator WithY_ShouldReturnVectorWithNewY_GivenVector() + [Test] + public void WithY_ShouldReturnVectorWithNewY_GivenVector() { Assert.AreEqual(new Vector3(1, 0, 1), Vector3.one.WithY(0)); Assert.AreEqual(Vector3.zero, Vector3.zero.WithY(0)); @@ -119,12 +105,10 @@ namespace X10D.Unity.Tests.Numerics Assert.AreEqual(new Vector3(1, 1, 0), Vector3.right.WithY(1)); Assert.AreEqual(Vector3.up, Vector3.up.WithY(1)); Assert.AreEqual(new Vector3(0, 1, 1), Vector3.forward.WithY(1)); - - yield break; } - [UnityTest] - public IEnumerator WithZ_ShouldReturnVectorWithNewZ_GivenVector() + [Test] + public void WithZ_ShouldReturnVectorWithNewZ_GivenVector() { Assert.AreEqual(new Vector3(1, 1, 0), Vector3.one.WithZ(0)); Assert.AreEqual(Vector3.zero, Vector3.zero.WithZ(0)); @@ -137,8 +121,6 @@ namespace X10D.Unity.Tests.Numerics Assert.AreEqual(new Vector3(1, 0, 1), Vector3.right.WithZ(1)); Assert.AreEqual(new Vector3(0, 1, 1), Vector3.up.WithZ(1)); Assert.AreEqual(Vector3.forward, Vector3.forward.WithZ(1)); - - yield break; } } } diff --git a/X10D.Unity.Tests/Assets/Tests/Numerics/Vector4Tests.cs b/X10D.Unity.Tests/Assets/Tests/Numerics/Vector4Tests.cs index b943406..249394a 100644 --- a/X10D.Unity.Tests/Assets/Tests/Numerics/Vector4Tests.cs +++ b/X10D.Unity.Tests/Assets/Tests/Numerics/Vector4Tests.cs @@ -1,7 +1,5 @@ -using System.Collections; -using NUnit.Framework; +using NUnit.Framework; using UnityEngine; -using UnityEngine.TestTools; using X10D.Core; using X10D.Unity.Numerics; using Random = System.Random; @@ -10,8 +8,8 @@ namespace X10D.Unity.Tests.Numerics { public class Vector4Tests { - [UnityTest] - public IEnumerator Deconstruct_ShouldReturnCorrectValues() + [Test] + public void Deconstruct_ShouldReturnCorrectValues() { var vector = new Vector4(1, 2, 3, 4); (float x, float y, float z, float w) = vector; @@ -20,12 +18,10 @@ namespace X10D.Unity.Tests.Numerics Assert.AreEqual(2, y); Assert.AreEqual(3, z); Assert.AreEqual(4, w); - - yield break; } - [UnityTest] - public IEnumerator Round_ShouldRoundToNearestInteger_GivenNoParameters() + [Test] + public void Round_ShouldRoundToNearestInteger_GivenNoParameters() { var vector = new Vector4(1.5f, 2.6f, -5.2f, 0.3f); var rounded = vector.Round(); @@ -34,12 +30,10 @@ namespace X10D.Unity.Tests.Numerics Assert.AreEqual(3, rounded.y); Assert.AreEqual(-5, rounded.z); Assert.AreEqual(0, rounded.w); - - yield break; } - [UnityTest] - public IEnumerator Round_ShouldRoundToNearest10_GivenPrecision10() + [Test] + public void Round_ShouldRoundToNearest10_GivenPrecision10() { var vector = new Vector4(1.5f, 25.2f, -12.5f, 101.2f); var rounded = vector.Round(10); @@ -48,12 +42,10 @@ namespace X10D.Unity.Tests.Numerics Assert.AreEqual(30, rounded.y); Assert.AreEqual(-10, rounded.z); Assert.AreEqual(100, rounded.w); - - yield break; } - [UnityTest] - public IEnumerator ToSystemVector_ShouldReturnVector_WithEqualComponents() + [Test] + public void ToSystemVector_ShouldReturnVector_WithEqualComponents() { var random = new Random(); float x = random.NextSingle(); @@ -69,12 +61,10 @@ namespace X10D.Unity.Tests.Numerics Assert.AreEqual(vector.y, systemVector.Y, 1e-6f); Assert.AreEqual(vector.z, systemVector.Z, 1e-6f); Assert.AreEqual(vector.w, systemVector.W, 1e-6f); - - yield break; } - [UnityTest] - public IEnumerator ToUnityVector_ShouldReturnVector_WithEqualComponents() + [Test] + public void ToUnityVector_ShouldReturnVector_WithEqualComponents() { var random = new Random(); float x = random.NextSingle(); @@ -90,12 +80,10 @@ namespace X10D.Unity.Tests.Numerics Assert.AreEqual(vector.Y, unityVector.y, 1e-6f); Assert.AreEqual(vector.Z, unityVector.z, 1e-6f); Assert.AreEqual(vector.W, unityVector.w, 1e-6f); - - yield break; } - [UnityTest] - public IEnumerator WithW_ShouldReturnVectorWithNewW_GivenVector() + [Test] + public void WithW_ShouldReturnVectorWithNewW_GivenVector() { Assert.AreEqual(new Vector4(1, 1, 1, 0), Vector4.one.WithW(0)); Assert.AreEqual(Vector4.zero, Vector4.zero.WithW(0)); @@ -110,12 +98,10 @@ namespace X10D.Unity.Tests.Numerics Assert.AreEqual(new Vector4(1, 0, 0, 1), new Vector4(1, 0, 0, 0).WithW(1)); Assert.AreEqual(new Vector4(0, 1, 0, 1), new Vector4(0, 1, 0, 0).WithW(1)); Assert.AreEqual(new Vector4(0, 0, 1, 1), new Vector4(0, 0, 1, 0).WithW(1)); - - yield break; } - [UnityTest] - public IEnumerator WithX_ShouldReturnVectorWithNewX_GivenVector() + [Test] + public void WithX_ShouldReturnVectorWithNewX_GivenVector() { Assert.AreEqual(new Vector4(0, 1, 1, 1), Vector4.one.WithX(0)); Assert.AreEqual(Vector4.zero, Vector4.zero.WithX(0)); @@ -130,12 +116,10 @@ namespace X10D.Unity.Tests.Numerics Assert.AreEqual(new Vector4(1, 0, 0, 0), new Vector4(1, 0, 0, 0).WithX(1)); Assert.AreEqual(new Vector4(1, 1, 0, 0), new Vector4(0, 1, 0, 0).WithX(1)); Assert.AreEqual(new Vector4(1, 0, 1, 0), new Vector4(0, 0, 1, 0).WithX(1)); - - yield break; } - [UnityTest] - public IEnumerator WithY_ShouldReturnVectorWithNewY_GivenVector() + [Test] + public void WithY_ShouldReturnVectorWithNewY_GivenVector() { Assert.AreEqual(new Vector4(1, 0, 1, 1), Vector4.one.WithY(0)); Assert.AreEqual(Vector4.zero, Vector4.zero.WithY(0)); @@ -150,12 +134,10 @@ namespace X10D.Unity.Tests.Numerics Assert.AreEqual(new Vector4(1, 1, 0, 0), new Vector4(1, 0, 0, 0).WithY(1)); Assert.AreEqual(new Vector4(0, 1, 0, 0), new Vector4(0, 1, 0, 0).WithY(1)); Assert.AreEqual(new Vector4(0, 1, 1, 0), new Vector4(0, 0, 1, 0).WithY(1)); - - yield break; } - [UnityTest] - public IEnumerator WithZ_ShouldReturnVectorWithNewZ_GivenVector() + [Test] + public void WithZ_ShouldReturnVectorWithNewZ_GivenVector() { Assert.AreEqual(new Vector4(1, 1, 0, 1), Vector4.one.WithZ(0)); Assert.AreEqual(Vector4.zero, Vector4.zero.WithZ(0)); @@ -170,8 +152,6 @@ namespace X10D.Unity.Tests.Numerics Assert.AreEqual(new Vector4(1, 0, 1, 0), new Vector4(1, 0, 0, 0).WithZ(1)); Assert.AreEqual(new Vector4(0, 1, 1, 0), new Vector4(0, 1, 0, 0).WithZ(1)); Assert.AreEqual(new Vector4(0, 0, 1, 0), new Vector4(0, 0, 1, 0).WithZ(1)); - - yield break; } } } diff --git a/X10D.Unity.Tests/Assets/Tests/SingletonTests.cs b/X10D.Unity.Tests/Assets/Tests/SingletonTests.cs index 9bf7a24..ae7ef31 100644 --- a/X10D.Unity.Tests/Assets/Tests/SingletonTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/SingletonTests.cs @@ -7,33 +7,31 @@ namespace X10D.Unity.Tests { public class SingletonTests { - [UnityTest] - public IEnumerator Singleton_ShouldReturnNewInstance_WhenNoInstanceExists() + [Test] + public void Singleton_ShouldReturnNewInstance_WhenNoInstanceExists() { TestBehaviour instance = Singleton.Instance; - Assert.IsTrue(instance); + Assert.IsNotNull(instance); Assert.IsTrue(instance.Flag); - - yield break; } - [UnityTest] - public IEnumerator Singleton_ShouldReturnSameInstance_WhenAccessedTwice() + [Test] + public void Singleton_ShouldReturnSameInstance_WhenAccessedTwice() { TestBehaviour instance = Singleton.Instance; - Assert.IsTrue(instance); + Assert.IsNotNull(instance); Assert.AreEqual(instance, Singleton.Instance); - - yield break; } [UnityTest] public IEnumerator Singleton_ShouldReturnNewInstance_WhenDestroyed() { TestBehaviour instance = Singleton.Instance; - Assert.IsTrue(instance); + Assert.IsNotNull(instance); Object.Destroy(instance); + yield return null; + Assert.IsFalse(instance); // ReSharper disable once HeuristicUnreachableCode diff --git a/X10D.Unity.Tests/Assets/Tests/YieldInstructionTests.cs b/X10D.Unity.Tests/Assets/Tests/YieldInstructionTests.cs index 14893d0..13cbad6 100644 --- a/X10D.Unity.Tests/Assets/Tests/YieldInstructionTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/YieldInstructionTests.cs @@ -38,7 +38,7 @@ namespace X10D.Unity.Tests { float time = UTime.time; yield return new WaitForTimeSpan(TimeSpan.FromSeconds(2)); - if (System.Math.Abs(UTime.time - (time + 2)) < 1e-2) + if (System.Math.Abs(UTime.time - (time + 2)) < 1e-1) { Assert.Pass($"{time + 2} == {UTime.time}"); } From ab62db2b3762e0f2fe23fb6c938793e3171c843d Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Wed, 5 Apr 2023 22:26:31 +0100 Subject: [PATCH 006/102] chore: switch from MSTest to NUnit (#76) --- X10D.Tests/X10D.Tests.csproj | 12 +- .../src/Collections/ArrayTests.AsReadOnly.cs | 22 +- .../src/Collections/ArrayTests.Clear.cs | 38 +- X10D.Tests/src/Collections/ArrayTests.cs | 4 +- X10D.Tests/src/Collections/BoolListTests.cs | 42 +- X10D.Tests/src/Collections/ByteTests.cs | 112 +-- .../CollectionTests.ClearAndDisposeAll.cs | 16 +- ...CollectionTests.ClearAndDisposeAllAsync.cs | 20 +- X10D.Tests/src/Collections/CollectionTests.cs | 4 +- X10D.Tests/src/Collections/DictionaryTests.cs | 253 ++++--- .../Collections/EnumerableTests.DisposeAll.cs | 14 +- .../EnumerableTests.DisposeAllAsync.cs | 16 +- X10D.Tests/src/Collections/EnumerableTests.cs | 144 ++-- X10D.Tests/src/Collections/Int16Tests.cs | 156 +++-- X10D.Tests/src/Collections/Int32Tests.cs | 187 ++--- X10D.Tests/src/Collections/Int64Tests.cs | 79 ++- X10D.Tests/src/Collections/ListTests.cs | 188 ++--- X10D.Tests/src/Collections/SpanTest.cs | 156 ++--- X10D.Tests/src/Core/CoreTests.cs | 84 +-- X10D.Tests/src/Core/EnumTests.cs | 80 ++- X10D.Tests/src/Core/IntrinsicTests.cs | 68 +- X10D.Tests/src/Core/NullableTests.cs | 22 +- X10D.Tests/src/Core/RandomTests.cs | 168 ++--- X10D.Tests/src/Core/SpanTest.cs | 232 +++--- X10D.Tests/src/Drawing/CircleFTests.cs | 134 ++-- X10D.Tests/src/Drawing/CircleTests.cs | 106 +-- X10D.Tests/src/Drawing/ColorTests.cs | 421 +++++------ X10D.Tests/src/Drawing/CuboidTests.cs | 59 +- X10D.Tests/src/Drawing/EllipseFTests.cs | 123 ++-- X10D.Tests/src/Drawing/EllipseTests.cs | 89 ++- X10D.Tests/src/Drawing/Line3DTests.cs | 132 ++-- X10D.Tests/src/Drawing/LineFTests.cs | 116 +-- X10D.Tests/src/Drawing/LineTests.cs | 88 +-- X10D.Tests/src/Drawing/PointFTests.cs | 53 +- X10D.Tests/src/Drawing/PointTests.cs | 53 +- X10D.Tests/src/Drawing/PolygonFTests.cs | 163 +++-- X10D.Tests/src/Drawing/PolygonTests.cs | 130 ++-- X10D.Tests/src/Drawing/PolyhedronTests.cs | 193 ++--- X10D.Tests/src/Drawing/RandomTests.cs | 24 +- X10D.Tests/src/Drawing/SizeTests.cs | 31 +- X10D.Tests/src/Drawing/SphereTests.cs | 94 ++- .../src/Hosting/ServiceCollectionTests.cs | 34 +- X10D.Tests/src/IO/BooleanTests.cs | 14 +- X10D.Tests/src/IO/ByteTests.cs | 14 +- X10D.Tests/src/IO/DirectoryInfoTests.cs | 40 +- X10D.Tests/src/IO/DoubleTests.cs | 22 +- X10D.Tests/src/IO/FileInfoTests.cs | 32 +- X10D.Tests/src/IO/Int16Tests.cs | 22 +- X10D.Tests/src/IO/Int32Tests.cs | 22 +- X10D.Tests/src/IO/Int64Tests.cs | 22 +- X10D.Tests/src/IO/ListOfByteTests.cs | 102 +-- X10D.Tests/src/IO/SByteTests.cs | 14 +- X10D.Tests/src/IO/SingleTests.cs | 22 +- X10D.Tests/src/IO/StreamTests.ReadDecimal.cs | 40 +- X10D.Tests/src/IO/StreamTests.ReadDouble.cs | 34 +- X10D.Tests/src/IO/StreamTests.ReadInt16.cs | 34 +- X10D.Tests/src/IO/StreamTests.ReadInt32.cs | 34 +- X10D.Tests/src/IO/StreamTests.ReadInt64.cs | 34 +- X10D.Tests/src/IO/StreamTests.ReadSingle.cs | 34 +- X10D.Tests/src/IO/StreamTests.ReadUInt16.cs | 34 +- X10D.Tests/src/IO/StreamTests.ReadUInt32.cs | 34 +- X10D.Tests/src/IO/StreamTests.ReadUInt64.cs | 34 +- X10D.Tests/src/IO/StreamTests.WriteDecimal.cs | 32 +- X10D.Tests/src/IO/StreamTests.WriteDouble.cs | 32 +- X10D.Tests/src/IO/StreamTests.WriteInt16.cs | 32 +- X10D.Tests/src/IO/StreamTests.WriteInt32.cs | 32 +- X10D.Tests/src/IO/StreamTests.WriteInt64.cs | 32 +- X10D.Tests/src/IO/StreamTests.WriteSingle.cs | 32 +- X10D.Tests/src/IO/StreamTests.WriteUInt16.cs | 32 +- X10D.Tests/src/IO/StreamTests.WriteUInt32.cs | 32 +- X10D.Tests/src/IO/StreamTests.WriteUInt64.cs | 32 +- X10D.Tests/src/IO/StreamTests.cs | 38 +- X10D.Tests/src/IO/TextReaderTests.cs | 24 +- X10D.Tests/src/IO/UInt16Tests.cs | 22 +- X10D.Tests/src/IO/UInt32Tests.cs | 22 +- X10D.Tests/src/IO/UInt64Tests.cs | 22 +- X10D.Tests/src/Linq/ByteTests.cs | 58 +- X10D.Tests/src/Linq/DecimalTests.cs | 64 +- X10D.Tests/src/Linq/DoubleTests.cs | 64 +- X10D.Tests/src/Linq/EnumerableTests.cs | 164 +++-- X10D.Tests/src/Linq/Int16Tests.cs | 69 +- X10D.Tests/src/Linq/Int32Tests.cs | 68 +- X10D.Tests/src/Linq/Int64Tests.cs | 64 +- X10D.Tests/src/Linq/ReadOnlySpanTests.cs | 50 +- X10D.Tests/src/Linq/SByteTests.cs | 34 +- X10D.Tests/src/Linq/SingleTests.cs | 58 +- X10D.Tests/src/Linq/SpanTests.cs | 50 +- X10D.Tests/src/Linq/UInt16Tests.cs | 46 +- X10D.Tests/src/Linq/UInt32Tests.cs | 58 +- X10D.Tests/src/Linq/UInt64Tests.cs | 58 +- X10D.Tests/src/Math/BigIntegerTests.Wrap.cs | 36 +- X10D.Tests/src/Math/BigIntegerTests.cs | 131 ++-- X10D.Tests/src/Math/ByteTests.Wrap.cs | 36 +- X10D.Tests/src/Math/ByteTests.cs | 94 +-- X10D.Tests/src/Math/ComparableTests.cs | 128 ++-- X10D.Tests/src/Math/DecimalTests.Wrap.cs | 36 +- X10D.Tests/src/Math/DecimalTests.cs | 171 +++-- X10D.Tests/src/Math/DoubleTests.Wrap.cs | 36 +- X10D.Tests/src/Math/DoubleTests.cs | 274 ++++---- X10D.Tests/src/Math/Int16Tests.Wrap.cs | 36 +- X10D.Tests/src/Math/Int16Tests.cs | 114 +-- X10D.Tests/src/Math/Int32Tests.Wrap.cs | 36 +- X10D.Tests/src/Math/Int32Tests.cs | 120 ++-- X10D.Tests/src/Math/Int64Tests.Wrap.cs | 36 +- X10D.Tests/src/Math/Int64Tests.cs | 124 ++-- X10D.Tests/src/Math/IsPrimeTests.cs | 98 +-- X10D.Tests/src/Math/MathUtilityTests.cs | 245 ++++--- X10D.Tests/src/Math/SByteTests.Wrap.cs | 36 +- X10D.Tests/src/Math/SByteTests.cs | 110 +-- X10D.Tests/src/Math/SingleTests.Wrap.cs | 36 +- X10D.Tests/src/Math/SingleTests.cs | 264 +++---- X10D.Tests/src/Math/UInt16Tests.Wrap.cs | 36 +- X10D.Tests/src/Math/UInt16Tests.cs | 98 +-- X10D.Tests/src/Math/UInt32Tests.Wrap.cs | 36 +- X10D.Tests/src/Math/UInt32Tests.cs | 106 +-- X10D.Tests/src/Math/UInt64Tests.Wrap.cs | 36 +- X10D.Tests/src/Math/UInt64Tests.cs | 106 +-- X10D.Tests/src/Net/EndPointTests.cs | 44 +- X10D.Tests/src/Net/IPAddressTests.cs | 30 +- X10D.Tests/src/Net/Int16Tests.cs | 12 +- X10D.Tests/src/Net/Int32Tests.cs | 12 +- X10D.Tests/src/Net/Int64Tests.cs | 12 +- X10D.Tests/src/Numerics/ByteTests.cs | 54 +- X10D.Tests/src/Numerics/Int16Tests.cs | 58 +- X10D.Tests/src/Numerics/Int32Tests.cs | 54 +- X10D.Tests/src/Numerics/Int64Tests.cs | 54 +- X10D.Tests/src/Numerics/QuaternionTests.cs | 30 +- X10D.Tests/src/Numerics/RandomTests.cs | 44 +- X10D.Tests/src/Numerics/SByteTests.cs | 54 +- X10D.Tests/src/Numerics/UInt16Tests.cs | 58 +- X10D.Tests/src/Numerics/UInt32Tests.cs | 54 +- X10D.Tests/src/Numerics/UInt64Tests.cs | 54 +- X10D.Tests/src/Numerics/Vector2Tests.cs | 113 +-- X10D.Tests/src/Numerics/Vector3Tests.cs | 112 +-- X10D.Tests/src/Numerics/Vector4Tests.cs | 159 +++-- X10D.Tests/src/Reflection/MemberInfoTests.cs | 89 +-- X10D.Tests/src/Reflection/TypeTests.cs | 54 +- X10D.Tests/src/Text/CharSpanTests.cs | 52 +- X10D.Tests/src/Text/CharTests.cs | 38 +- X10D.Tests/src/Text/CoreTests.cs | 10 +- X10D.Tests/src/Text/EnumerableTests.cs | 30 +- X10D.Tests/src/Text/RuneTests.cs | 62 +- .../src/Text/StringBuilderReaderTests.cs | 118 ++-- X10D.Tests/src/Text/StringTests.cs | 661 ++++++++++-------- X10D.Tests/src/Time/ByteTests.cs | 87 ++- X10D.Tests/src/Time/CharSpanTests.cs | 12 +- X10D.Tests/src/Time/DateOnlyTests.cs | 141 ++-- X10D.Tests/src/Time/DateTimeOffsetTests.cs | 128 ++-- X10D.Tests/src/Time/DateTimeTests.cs | 140 ++-- X10D.Tests/src/Time/DecimalTests.cs | 46 +- X10D.Tests/src/Time/DoubleTests.cs | 48 +- X10D.Tests/src/Time/HalfTests.cs | 46 +- X10D.Tests/src/Time/Int16Tests.cs | 113 +-- X10D.Tests/src/Time/Int32Tests.cs | 116 +-- X10D.Tests/src/Time/Int64Tests.cs | 116 +-- X10D.Tests/src/Time/SByteTests.cs | 106 +-- X10D.Tests/src/Time/SingleTests.cs | 46 +- X10D.Tests/src/Time/StringTests.cs | 16 +- X10D.Tests/src/Time/TimeSpanParserTests.cs | 67 +- X10D.Tests/src/Time/TimeSpanTests.cs | 22 +- X10D.Tests/src/Time/UInt16Tests.cs | 89 ++- X10D.Tests/src/Time/UInt32Tests.cs | 89 ++- X10D.Tests/src/Time/UInt64Tests.cs | 89 ++- 163 files changed, 6604 insertions(+), 5769 deletions(-) diff --git a/X10D.Tests/X10D.Tests.csproj b/X10D.Tests/X10D.Tests.csproj index 9853d23..d763c8c 100644 --- a/X10D.Tests/X10D.Tests.csproj +++ b/X10D.Tests/X10D.Tests.csproj @@ -15,15 +15,13 @@ - + - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - + + + + diff --git a/X10D.Tests/src/Collections/ArrayTests.AsReadOnly.cs b/X10D.Tests/src/Collections/ArrayTests.AsReadOnly.cs index ed46847..d576b26 100644 --- a/X10D.Tests/src/Collections/ArrayTests.AsReadOnly.cs +++ b/X10D.Tests/src/Collections/ArrayTests.AsReadOnly.cs @@ -1,42 +1,42 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Collections; namespace X10D.Tests.Collections; public partial class ArrayTests { - [TestClass] + [TestFixture] public class AsReadOnlyTests { - [TestMethod] + [Test] public void AsReadOnly_ShouldReturnReadOnlyCollection_WhenArrayIsNotNull() { int[] array = {1, 2, 3}; IReadOnlyCollection result = array.AsReadOnly(); - Assert.IsInstanceOfType(result, typeof(IReadOnlyCollection)); + Assert.That(result, Is.InstanceOf>()); } - [TestMethod] + [Test] public void AsReadOnly_ShouldThrowArgumentNullException_WhenArrayIsNull() { - int[]? array = null; - Assert.ThrowsException(() => array!.AsReadOnly()); + int[] array = null!; + Assert.Throws(() => _ = array.AsReadOnly()); } - [TestMethod] + [Test] public void AsReadOnly_ShouldReturnCorrectCount_WhenArrayIsNotEmpty() { int[] array = {1, 2, 3}; IReadOnlyCollection result = array.AsReadOnly(); - Assert.AreEqual(array.Length, result.Count); + Assert.That(result, Has.Count.EqualTo(array.Length)); } - [TestMethod] + [Test] public void AsReadOnly_ShouldReturnEmptyCollection_WhenArrayIsEmpty() { int[] array = Array.Empty(); IReadOnlyCollection result = array.AsReadOnly(); - Assert.AreEqual(0, result.Count); + Assert.That(result, Is.Empty); } } } diff --git a/X10D.Tests/src/Collections/ArrayTests.Clear.cs b/X10D.Tests/src/Collections/ArrayTests.Clear.cs index 34c36bb..4679b83 100644 --- a/X10D.Tests/src/Collections/ArrayTests.Clear.cs +++ b/X10D.Tests/src/Collections/ArrayTests.Clear.cs @@ -1,63 +1,63 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Collections; namespace X10D.Tests.Collections; public partial class ArrayTests { - [TestClass] + [TestFixture] public class ClearTests { - [TestMethod] + [Test] public void Clear_ShouldClearTheArray() { var array = new int?[] {1, 2, 3, null, 4}; array.Clear(); - Assert.IsTrue(array.All(x => x == null)); + Assert.That(array.All(x => x == null)); } - [TestMethod] + [Test] public void Clear_ShouldDoNothing_WhenArrayIsEmpty() { int[] array = Array.Empty(); array.Clear(); } - [TestMethod] + [Test] public void Clear_WithRange_ShouldClearTheSpecifiedRangeOfTheArray() { var array = new int?[] {1, 2, 3, null, 4}; array.Clear(1..4); - Assert.AreEqual(5, array.Length); - Assert.AreEqual(1, array[0]); - Assert.AreEqual(4, array[4]); - Assert.IsTrue(array[1..4].All(x => x == null)); + Assert.That(array.Length, Is.EqualTo(5)); + Assert.That(array[0], Is.EqualTo(1)); + Assert.That(array[4], Is.EqualTo(4)); + Assert.That(array[1..4].All(x => x == null)); } - [TestMethod] + [Test] public void Clear_WithIndexAndLength_ShouldClearTheSpecifiedRangeOfTheArray() { var array = new int?[] {1, 2, 3, null, 4}; array.Clear(1, 3); - Assert.AreEqual(5, array.Length); - Assert.AreEqual(1, array[0]); - Assert.AreEqual(4, array[4]); - Assert.IsTrue(array[1..4].All(x => x == null)); + Assert.That(array.Length, Is.EqualTo(5)); + Assert.That(array[0], Is.EqualTo(1)); + Assert.That(array[4], Is.EqualTo(4)); + Assert.That(array[1..4].All(x => x == null)); } - [TestMethod] + [Test] public void Clear_ShouldThrowArgumentNullException_WhenArrayIsNull() { int[] array = null!; - Assert.ThrowsException(() => array.Clear()); - Assert.ThrowsException(() => array.Clear(0, 1)); - Assert.ThrowsException(() => array.Clear(..1)); + Assert.Throws(() => array.Clear()); + Assert.Throws(() => array.Clear(0, 1)); + Assert.Throws(() => array.Clear(..1)); } } } diff --git a/X10D.Tests/src/Collections/ArrayTests.cs b/X10D.Tests/src/Collections/ArrayTests.cs index cdeb996..90e5cd2 100644 --- a/X10D.Tests/src/Collections/ArrayTests.cs +++ b/X10D.Tests/src/Collections/ArrayTests.cs @@ -1,8 +1,8 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; namespace X10D.Tests.Collections; -[TestClass] +[TestFixture] public partial class ArrayTests { } diff --git a/X10D.Tests/src/Collections/BoolListTests.cs b/X10D.Tests/src/Collections/BoolListTests.cs index 0cd5259..a2ad121 100644 --- a/X10D.Tests/src/Collections/BoolListTests.cs +++ b/X10D.Tests/src/Collections/BoolListTests.cs @@ -1,56 +1,56 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Collections; namespace X10D.Tests.Collections; -[TestClass] +[TestFixture] public class BoolListTests { - [TestMethod] + [Test] public void PackByte_Should_Pack_Correctly() { var array = new[] {true, false, true, false, true, false, true, false}; - Assert.AreEqual(85, array.PackByte()); // 01010101 + Assert.That(array.PackByte(), Is.EqualTo(85)); // 01010101 } - [TestMethod] + [Test] public void Pack16Bit_Should_Pack_Correctly() { var array = new[] {true, false, true, false, true, false, true, false, true, true, false, true}; - Assert.AreEqual(2901, array.PackInt16()); // 101101010101 + Assert.That(array.PackInt16(), Is.EqualTo(2901)); // 101101010101 } - [TestMethod] + [Test] public void Pack32Bit_Should_Pack_Correctly() { var array = new[] {true, false, true, false, true, false, true, false, true, true, false, true}; - Assert.AreEqual(2901, array.PackInt32()); // 101101010101 + Assert.That(array.PackInt32(), Is.EqualTo(2901)); // 101101010101 } - [TestMethod] + [Test] public void Pack64Bit_Should_Pack_Correctly() { var array = new[] {true, false, true, false, true, false, true, false, true, true, false, true}; - Assert.AreEqual(2901, array.PackInt64()); // 101101010101 + Assert.That(array.PackInt64(), Is.EqualTo(2901)); // 101101010101 } - [TestMethod] + [Test] public void Pack_ShouldThrow_GivenLargeArray() { bool[] array = Enumerable.Repeat(false, 65).ToArray(); - Assert.ThrowsException(() => array.PackByte()); - Assert.ThrowsException(() => array.PackInt16()); - Assert.ThrowsException(() => array.PackInt32()); - Assert.ThrowsException(() => array.PackInt64()); + Assert.Throws(() => _ = array.PackByte()); + Assert.Throws(() => _ = array.PackInt16()); + Assert.Throws(() => _ = array.PackInt32()); + Assert.Throws(() => _ = array.PackInt64()); } - [TestMethod] + [Test] public void Pack_ShouldThrow_GivenNull() { - bool[]? array = null; - Assert.ThrowsException(() => array!.PackByte()); - Assert.ThrowsException(() => array!.PackInt16()); - Assert.ThrowsException(() => array!.PackInt32()); - Assert.ThrowsException(() => array!.PackInt64()); + bool[] array = null!; + Assert.Throws(() => _ = array.PackByte()); + Assert.Throws(() => _ = array.PackInt16()); + Assert.Throws(() => _ = array.PackInt32()); + Assert.Throws(() => _ = array.PackInt64()); } } diff --git a/X10D.Tests/src/Collections/ByteTests.cs b/X10D.Tests/src/Collections/ByteTests.cs index 6030065..d73ab14 100644 --- a/X10D.Tests/src/Collections/ByteTests.cs +++ b/X10D.Tests/src/Collections/ByteTests.cs @@ -1,67 +1,74 @@ using System.Runtime.Intrinsics.X86; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Collections; namespace X10D.Tests.Collections; -[TestClass] +[TestFixture] public class ByteTests { - [TestMethod] + [Test] public void Unpack_ShouldUnpackToArrayCorrectly() { const byte value = 0b11010100; bool[] bits = value.Unpack(); - Assert.AreEqual(8, bits.Length); - - Assert.IsFalse(bits[0]); - Assert.IsFalse(bits[1]); - Assert.IsTrue(bits[2]); - Assert.IsFalse(bits[3]); - Assert.IsTrue(bits[4]); - Assert.IsFalse(bits[5]); - Assert.IsTrue(bits[6]); - Assert.IsTrue(bits[7]); + Assert.That(bits, Has.Length.EqualTo(8)); + Assert.Multiple(() => + { + Assert.That(bits[0], Is.False); + Assert.That(bits[1], Is.False); + Assert.That(bits[2], Is.True); + Assert.That(bits[3], Is.False); + Assert.That(bits[4], Is.True); + Assert.That(bits[5], Is.False); + Assert.That(bits[6], Is.True); + Assert.That(bits[7], Is.True); + }); } - [TestMethod] + [Test] public void Unpack_ShouldUnpackToSpanCorrectly() { const byte value = 0b11010100; - Span bits = stackalloc bool[8]; - value.Unpack(bits); + Assert.Multiple(() => + { + Span bits = stackalloc bool[8]; + value.Unpack(bits); - Assert.IsFalse(bits[0]); - Assert.IsFalse(bits[1]); - Assert.IsTrue(bits[2]); - Assert.IsFalse(bits[3]); - Assert.IsTrue(bits[4]); - Assert.IsFalse(bits[5]); - Assert.IsTrue(bits[6]); - Assert.IsTrue(bits[7]); + Assert.That(bits[0], Is.False); + Assert.That(bits[1], Is.False); + Assert.That(bits[2], Is.True); + Assert.That(bits[3], Is.False); + Assert.That(bits[4], Is.True); + Assert.That(bits[5], Is.False); + Assert.That(bits[6], Is.True); + Assert.That(bits[7], Is.True); + }); } #if NET5_0_OR_GREATER - - [TestMethod] + [Test] public void UnpackInternal_Fallback_ShouldUnpackToSpanCorrectly() { const byte value = 0b11010100; - Span bits = stackalloc bool[8]; - value.UnpackInternal_Fallback(bits); + Assert.Multiple(() => + { + Span bits = stackalloc bool[8]; + value.Unpack(bits); - Assert.IsFalse(bits[0]); - Assert.IsFalse(bits[1]); - Assert.IsTrue(bits[2]); - Assert.IsFalse(bits[3]); - Assert.IsTrue(bits[4]); - Assert.IsFalse(bits[5]); - Assert.IsTrue(bits[6]); - Assert.IsTrue(bits[7]); + Assert.That(bits[0], Is.False); + Assert.That(bits[1], Is.False); + Assert.That(bits[2], Is.True); + Assert.That(bits[3], Is.False); + Assert.That(bits[4], Is.True); + Assert.That(bits[5], Is.False); + Assert.That(bits[6], Is.True); + Assert.That(bits[7], Is.True); + }); } - [TestMethod] + [Test] public void UnpackInternal_Ssse3_ShouldUnpackToSpanCorrectly() { if (!Sse3.IsSupported) @@ -70,31 +77,34 @@ public class ByteTests } const byte value = 0b11010100; - Span bits = stackalloc bool[8]; - value.UnpackInternal_Ssse3(bits); + Assert.Multiple(() => + { + Span bits = stackalloc bool[8]; + value.Unpack(bits); - Assert.IsFalse(bits[0]); - Assert.IsFalse(bits[1]); - Assert.IsTrue(bits[2]); - Assert.IsFalse(bits[3]); - Assert.IsTrue(bits[4]); - Assert.IsFalse(bits[5]); - Assert.IsTrue(bits[6]); - Assert.IsTrue(bits[7]); + Assert.That(bits[0], Is.False); + Assert.That(bits[1], Is.False); + Assert.That(bits[2], Is.True); + Assert.That(bits[3], Is.False); + Assert.That(bits[4], Is.True); + Assert.That(bits[5], Is.False); + Assert.That(bits[6], Is.True); + Assert.That(bits[7], Is.True); + }); } #endif - [TestMethod] + [Test] public void Unpack_ShouldRepackEqually() { const byte value = 0b11010100; - Assert.AreEqual(value, value.Unpack().PackByte()); + Assert.That(value.Unpack().PackByte(), Is.EqualTo(value)); } - [TestMethod] + [Test] public void Unpack_ShouldThrow_GivenTooSmallSpan() { - Assert.ThrowsException(() => + Assert.Throws(() => { const byte value = 0b11010100; Span bits = stackalloc bool[0]; diff --git a/X10D.Tests/src/Collections/CollectionTests.ClearAndDisposeAll.cs b/X10D.Tests/src/Collections/CollectionTests.ClearAndDisposeAll.cs index a0bed51..ebce1e4 100644 --- a/X10D.Tests/src/Collections/CollectionTests.ClearAndDisposeAll.cs +++ b/X10D.Tests/src/Collections/CollectionTests.ClearAndDisposeAll.cs @@ -1,16 +1,16 @@ using System.Collections.ObjectModel; -using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; +using NUnit.Framework; using X10D.Collections; namespace X10D.Tests.Collections; public partial class CollectionTests { - [TestClass] + [TestFixture] public class ClearAndDisposeAllTests { - [TestMethod] + [Test] public void ClearAndDisposeAll_ShouldClearAndDisposeAllItems_WhenCalledWithValidList() { var mock1 = new Mock(); @@ -23,23 +23,23 @@ public partial class CollectionTests mock1.Verify(i => i.Dispose(), Times.Once); mock2.Verify(i => i.Dispose(), Times.Once); mock3.Verify(i => i.Dispose(), Times.Once); - Assert.AreEqual(0, list.Count); + Assert.That(list, Is.Empty); } - [TestMethod] + [Test] public void ClearAndDisposeAll_ShouldThrowArgumentNullException_WhenCalledWithNullList() { List? list = null; - Assert.ThrowsException(() => list!.ClearAndDisposeAll()); + Assert.Throws(() => list!.ClearAndDisposeAll()); } - [TestMethod] + [Test] public void ClearAndDisposeAll_ShouldThrowInvalidOperationException_WhenCalledWithReadOnlyList() { var mock = new Mock(); var list = new ReadOnlyCollection(new List {mock.Object}); - Assert.ThrowsException(() => list.ClearAndDisposeAll()); + Assert.Throws(() => list.ClearAndDisposeAll()); } } } diff --git a/X10D.Tests/src/Collections/CollectionTests.ClearAndDisposeAllAsync.cs b/X10D.Tests/src/Collections/CollectionTests.ClearAndDisposeAllAsync.cs index 1301763..560eac7 100644 --- a/X10D.Tests/src/Collections/CollectionTests.ClearAndDisposeAllAsync.cs +++ b/X10D.Tests/src/Collections/CollectionTests.ClearAndDisposeAllAsync.cs @@ -1,16 +1,16 @@ using System.Collections.ObjectModel; -using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; +using NUnit.Framework; using X10D.Collections; namespace X10D.Tests.Collections; public partial class CollectionTests { - [TestClass] + [TestFixture] public class ClearAndDisposeAllAsyncTests { - [TestMethod] + [Test] public async Task ClearAndDisposeAllAsync_ShouldClearAndDisposeAllItems_WhenCalledWithValidList() { var mock1 = new Mock(); @@ -23,23 +23,23 @@ public partial class CollectionTests mock1.Verify(i => i.DisposeAsync(), Times.Once); mock2.Verify(i => i.DisposeAsync(), Times.Once); mock3.Verify(i => i.DisposeAsync(), Times.Once); - Assert.AreEqual(0, list.Count); + Assert.That(list, Is.Empty); } - [TestMethod] - public async Task ClearAndDisposeAllAsync_ShouldThrowArgumentNullException_WhenCalledWithNullList() + [Test] + public void ClearAndDisposeAllAsync_ShouldThrowArgumentNullException_WhenCalledWithNullList() { List? list = null; - await Assert.ThrowsExceptionAsync(list!.ClearAndDisposeAllAsync).ConfigureAwait(false); + Assert.ThrowsAsync(list!.ClearAndDisposeAllAsync); } - [TestMethod] - public async Task ClearAndDisposeAllAsync_ShouldThrowInvalidOperationException_WhenCalledWithReadOnlyList() + [Test] + public void ClearAndDisposeAllAsync_ShouldThrowInvalidOperationException_WhenCalledWithReadOnlyList() { var mock = new Mock(); var list = new ReadOnlyCollection(new List {mock.Object}); - await Assert.ThrowsExceptionAsync(list.ClearAndDisposeAllAsync).ConfigureAwait(false); + Assert.ThrowsAsync(list.ClearAndDisposeAllAsync); } } } diff --git a/X10D.Tests/src/Collections/CollectionTests.cs b/X10D.Tests/src/Collections/CollectionTests.cs index 9642b16..ba825f6 100644 --- a/X10D.Tests/src/Collections/CollectionTests.cs +++ b/X10D.Tests/src/Collections/CollectionTests.cs @@ -1,8 +1,8 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; namespace X10D.Tests.Collections; -[TestClass] +[TestFixture] public partial class CollectionTests { } diff --git a/X10D.Tests/src/Collections/DictionaryTests.cs b/X10D.Tests/src/Collections/DictionaryTests.cs index 907b1f9..1882dad 100644 --- a/X10D.Tests/src/Collections/DictionaryTests.cs +++ b/X10D.Tests/src/Collections/DictionaryTests.cs @@ -1,176 +1,231 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Collections; namespace X10D.Tests.Collections; -[TestClass] +[TestFixture] public class DictionaryTests { - [TestMethod] + [Test] public void AddOrUpdate_ShouldAddNewKey_IfNotExists_GivenConcreteDictionary() { var dictionary = new Dictionary(); - Assert.IsFalse(dictionary.ContainsKey(1)); + Assert.That(dictionary.ContainsKey(1), Is.False); dictionary.AddOrUpdate(1, "one", (_, _) => string.Empty); - Assert.IsTrue(dictionary.ContainsKey(1)); - Assert.AreEqual("one", dictionary[1]); + Assert.Multiple(() => + { + Assert.That(dictionary.ContainsKey(1)); + Assert.That(dictionary[1], Is.EqualTo("one")); + }); dictionary.Clear(); - Assert.IsFalse(dictionary.ContainsKey(1)); + Assert.That(dictionary.ContainsKey(1), Is.False); dictionary.AddOrUpdate(1, _ => "one", (_, _) => string.Empty); - Assert.IsTrue(dictionary.ContainsKey(1)); - Assert.AreEqual("one", dictionary[1]); + Assert.Multiple(() => + { + Assert.That(dictionary.ContainsKey(1)); + Assert.That(dictionary[1], Is.EqualTo("one")); + }); dictionary.Clear(); - Assert.IsFalse(dictionary.ContainsKey(1)); + Assert.That(dictionary, Is.Empty); + Assert.That(dictionary.ContainsKey(1), Is.False); dictionary.AddOrUpdate(1, (_, _) => "one", (_, _, _) => string.Empty, 0); - Assert.IsTrue(dictionary.ContainsKey(1)); - Assert.AreEqual("one", dictionary[1]); + Assert.Multiple(() => + { + Assert.That(dictionary.ContainsKey(1), Is.True); + Assert.That(dictionary[1], Is.EqualTo("one")); + }); } - [TestMethod] + [Test] public void AddOrUpdate_ShouldAddNewKey_IfNotExists_GivenIDictionary() { IDictionary dictionary = new Dictionary(); - Assert.IsFalse(dictionary.ContainsKey(1)); + Assert.That(dictionary.ContainsKey(1), Is.False); dictionary.AddOrUpdate(1, "one", (_, _) => string.Empty); - Assert.IsTrue(dictionary.ContainsKey(1)); - Assert.AreEqual("one", dictionary[1]); + Assert.Multiple(() => + { + Assert.That(dictionary.ContainsKey(1), Is.True); + Assert.That(dictionary[1], Is.EqualTo("one")); + }); dictionary.Clear(); - Assert.IsFalse(dictionary.ContainsKey(1)); + Assert.That(dictionary.ContainsKey(1), Is.False); dictionary.AddOrUpdate(1, _ => "one", (_, _) => string.Empty); - Assert.IsTrue(dictionary.ContainsKey(1)); - Assert.AreEqual("one", dictionary[1]); + Assert.Multiple(() => + { + Assert.That(dictionary.ContainsKey(1), Is.True); + Assert.That(dictionary[1], Is.EqualTo("one")); + }); dictionary.Clear(); - Assert.IsFalse(dictionary.ContainsKey(1)); + Assert.That(dictionary, Is.Empty); + Assert.That(dictionary.ContainsKey(1), Is.False); dictionary.AddOrUpdate(1, (_, _) => "one", (_, _, _) => string.Empty, 0); - Assert.IsTrue(dictionary.ContainsKey(1)); - Assert.AreEqual("one", dictionary[1]); + Assert.Multiple(() => + { + Assert.That(dictionary.ContainsKey(1), Is.True); + Assert.That(dictionary[1], Is.EqualTo("one")); + }); } - [TestMethod] + [Test] public void AddOrUpdate_ShouldUpdateKey_IfExists_GivenConcreteDirection() { var dictionary = new Dictionary {[1] = "one"}; - Assert.IsTrue(dictionary.ContainsKey(1)); - Assert.AreEqual("one", dictionary[1]); + Assert.Multiple(() => + { + Assert.That(dictionary.ContainsKey(1)); + Assert.That(dictionary[1], Is.EqualTo("one")); + }); dictionary.AddOrUpdate(1, string.Empty, (_, _) => "two"); - Assert.IsTrue(dictionary.ContainsKey(1)); - Assert.AreEqual("two", dictionary[1]); + Assert.Multiple(() => + { + Assert.That(dictionary.ContainsKey(1)); + Assert.That(dictionary[1], Is.EqualTo("two")); + }); dictionary.Clear(); - Assert.IsFalse(dictionary.ContainsKey(1)); + Assert.That(dictionary, Is.Empty); + Assert.That(dictionary.ContainsKey(1), Is.False); + dictionary[1] = "one"; - dictionary.AddOrUpdate(1, _ => string.Empty, (_, _) => "two"); - Assert.IsTrue(dictionary.ContainsKey(1)); - Assert.AreEqual("two", dictionary[1]); + + Assert.Multiple(() => + { + Assert.That(dictionary.ContainsKey(1)); + Assert.That(dictionary[1], Is.EqualTo("two")); + }); dictionary.Clear(); - Assert.IsFalse(dictionary.ContainsKey(1)); + Assert.That(dictionary, Is.Empty); + Assert.That(dictionary.ContainsKey(1), Is.False); dictionary[1] = "one"; dictionary.AddOrUpdate(1, (_, _) => string.Empty, (_, _, _) => "two", 0); - Assert.IsTrue(dictionary.ContainsKey(1)); - Assert.AreEqual("two", dictionary[1]); + Assert.Multiple(() => + { + Assert.That(dictionary.ContainsKey(1)); + Assert.That(dictionary[1], Is.EqualTo("two")); + }); } - [TestMethod] + [Test] public void AddOrUpdate_ShouldUpdateKey_IfExists_GivenIDictionary() { IDictionary dictionary = new Dictionary {[1] = "one"}; - Assert.IsTrue(dictionary.ContainsKey(1)); - Assert.AreEqual("one", dictionary[1]); + Assert.Multiple(() => + { + Assert.That(dictionary.ContainsKey(1)); + Assert.That(dictionary[1], Is.EqualTo("one")); + }); dictionary.AddOrUpdate(1, string.Empty, (_, _) => "two"); - Assert.IsTrue(dictionary.ContainsKey(1)); - Assert.AreEqual("two", dictionary[1]); + Assert.Multiple(() => + { + Assert.That(dictionary.ContainsKey(1)); + Assert.That(dictionary[1], Is.EqualTo("two")); + }); dictionary.Clear(); - Assert.IsFalse(dictionary.ContainsKey(1)); - dictionary[1] = "one"; + Assert.Multiple(() => + { + Assert.That(dictionary, Is.Empty); + Assert.That(dictionary.ContainsKey(1), Is.False); + }); + dictionary[1] = "one"; dictionary.AddOrUpdate(1, _ => string.Empty, (_, _) => "two"); - Assert.IsTrue(dictionary.ContainsKey(1)); - Assert.AreEqual("two", dictionary[1]); + Assert.Multiple(() => + { + Assert.That(dictionary.ContainsKey(1)); + Assert.That(dictionary[1], Is.EqualTo("two")); + }); dictionary.Clear(); - Assert.IsFalse(dictionary.ContainsKey(1)); - dictionary[1] = "one"; + Assert.Multiple(() => + { + Assert.That(dictionary, Is.Empty); + Assert.That(dictionary.ContainsKey(1), Is.False); + dictionary[1] = "one"; + }); dictionary.AddOrUpdate(1, (_, _) => string.Empty, (_, _, _) => "two", 0); - Assert.IsTrue(dictionary.ContainsKey(1)); - Assert.AreEqual("two", dictionary[1]); + Assert.Multiple(() => + { + Assert.That(dictionary.ContainsKey(1)); + Assert.That(dictionary[1], Is.EqualTo("two")); + }); } - [TestMethod] + [Test] public void AddOrUpdate_ShouldThrow_GivenNullDictionary_GivenConcreteDictionary() { Dictionary? dictionary = null; - Assert.ThrowsException(() => dictionary!.AddOrUpdate(1, string.Empty, (_, _) => string.Empty)); - Assert.ThrowsException(() => + Assert.Throws(() => dictionary!.AddOrUpdate(1, string.Empty, (_, _) => string.Empty)); + Assert.Throws(() => dictionary!.AddOrUpdate(1, _ => string.Empty, (_, _) => string.Empty)); - Assert.ThrowsException(() => + Assert.Throws(() => dictionary!.AddOrUpdate(1, (_, _) => string.Empty, (_, _, _) => string.Empty, 0)); } - [TestMethod] + [Test] public void AddOrUpdate_ShouldThrow_GivenNullDictionary_GivenIDictionary() { IDictionary? dictionary = null; - Assert.ThrowsException(() => dictionary!.AddOrUpdate(1, string.Empty, (_, _) => string.Empty)); - Assert.ThrowsException(() => + Assert.Throws(() => dictionary!.AddOrUpdate(1, string.Empty, (_, _) => string.Empty)); + Assert.Throws(() => dictionary!.AddOrUpdate(1, _ => string.Empty, (_, _) => string.Empty)); - Assert.ThrowsException(() => + Assert.Throws(() => dictionary!.AddOrUpdate(1, (_, _) => string.Empty, (_, _, _) => string.Empty, 0)); } - [TestMethod] + [Test] public void AddOrUpdate_ShouldThrow_GivenNullUpdateValueFactory_GivenConcreteDictionary() { var dictionary = new Dictionary(); - Assert.ThrowsException(() => dictionary.AddOrUpdate(1, string.Empty, null!)); - Assert.ThrowsException(() => dictionary.AddOrUpdate(1, _ => string.Empty, null!)); - Assert.ThrowsException(() => dictionary.AddOrUpdate(1, (_, _) => string.Empty, null!, 0)); + Assert.Throws(() => dictionary.AddOrUpdate(1, string.Empty, null!)); + Assert.Throws(() => dictionary.AddOrUpdate(1, _ => string.Empty, null!)); + Assert.Throws(() => dictionary.AddOrUpdate(1, (_, _) => string.Empty, null!, 0)); } - [TestMethod] + [Test] public void AddOrUpdate_ShouldThrow_GivenNullUpdateValueFactory_GivenIDictionary() { IDictionary dictionary = new Dictionary(); - Assert.ThrowsException(() => dictionary.AddOrUpdate(1, string.Empty, null!)); - Assert.ThrowsException(() => dictionary.AddOrUpdate(1, _ => string.Empty, null!)); - Assert.ThrowsException(() => dictionary.AddOrUpdate(1, (_, _) => string.Empty, null!, 0)); + Assert.Throws(() => dictionary.AddOrUpdate(1, string.Empty, null!)); + Assert.Throws(() => dictionary.AddOrUpdate(1, _ => string.Empty, null!)); + Assert.Throws(() => dictionary.AddOrUpdate(1, (_, _) => string.Empty, null!, 0)); } - [TestMethod] + [Test] public void AddOrUpdate_ShouldThrow_GivenNullAddValueFactory_GivenConcreteDictionary() { var dictionary = new Dictionary(); Func? addValueFactory = null; - Assert.ThrowsException(() => dictionary.AddOrUpdate(1, addValueFactory!, (_, _) => "one")); - Assert.ThrowsException(() => dictionary.AddOrUpdate(1, null!, (_, _, _) => "one", 0)); + Assert.Throws(() => dictionary.AddOrUpdate(1, addValueFactory!, (_, _) => "one")); + Assert.Throws(() => dictionary.AddOrUpdate(1, null!, (_, _, _) => "one", 0)); } - [TestMethod] + [Test] public void AddOrUpdate_ShouldThrow_GivenNullAddValueFactory_GivenIDictionary() { IDictionary dictionary = new Dictionary(); Func? addValueFactory = null; - Assert.ThrowsException(() => dictionary.AddOrUpdate(1, addValueFactory!, (_, _) => "one")); - Assert.ThrowsException(() => dictionary.AddOrUpdate(1, null!, (_, _, _) => "one", 0)); + Assert.Throws(() => dictionary.AddOrUpdate(1, addValueFactory!, (_, _) => "one")); + Assert.Throws(() => dictionary.AddOrUpdate(1, null!, (_, _, _) => "one", 0)); } - [TestMethod] + [Test] public void ToConnectionString_ShouldReturnConnectionString() { var dictionary = new Dictionary @@ -179,10 +234,10 @@ public class DictionaryTests }; string connectionString = dictionary.ToConnectionString(); - Assert.AreEqual("Data Source=localhost;Initial Catalog=test;Integrated Security=True;Foobar=", connectionString); + Assert.That(connectionString, Is.EqualTo("Data Source=localhost;Initial Catalog=test;Integrated Security=True;Foobar=")); } - [TestMethod] + [Test] public void ToConnectionString_ShouldReturnTransformedValueConnectionString() { var dictionary = new Dictionary @@ -191,10 +246,10 @@ public class DictionaryTests }; string connectionString = dictionary.ToConnectionString(v => v?.ToUpperInvariant()); - Assert.AreEqual("Data Source=LOCALHOST;Initial Catalog=TEST;Integrated Security=TRUE;Foobar=", connectionString); + Assert.That(connectionString, Is.EqualTo("Data Source=LOCALHOST;Initial Catalog=TEST;Integrated Security=TRUE;Foobar=")); } - [TestMethod] + [Test] public void ToConnectionString_ShouldReturnTransformedKeyValueConnectionString() { var dictionary = new Dictionary @@ -203,69 +258,69 @@ public class DictionaryTests }; string connectionString = dictionary.ToConnectionString(k => k.ToUpper(), v => v?.ToUpperInvariant()); - Assert.AreEqual("DATA SOURCE=LOCALHOST;INITIAL CATALOG=TEST;INTEGRATED SECURITY=TRUE;FOOBAR=", connectionString); + Assert.That(connectionString, Is.EqualTo("DATA SOURCE=LOCALHOST;INITIAL CATALOG=TEST;INTEGRATED SECURITY=TRUE;FOOBAR=")); } - [TestMethod] + [Test] public void ToConnectionString_ShouldThrow_GivenNullSource() { - Dictionary? dictionary = null; - Assert.ThrowsException(() => dictionary!.ToConnectionString()); - Assert.ThrowsException(() => dictionary!.ToConnectionString(null!)); - Assert.ThrowsException(() => dictionary!.ToConnectionString(null!, null!)); + Dictionary dictionary = null!; + Assert.Throws(() => _ = dictionary.ToConnectionString()); + Assert.Throws(() => _ = dictionary.ToConnectionString(null!)); + Assert.Throws(() => _ = dictionary.ToConnectionString(null!, null!)); } - [TestMethod] + [Test] public void ToConnectionString_ShouldThrow_GivenNullSelector() { var dictionary = new Dictionary(); - Assert.ThrowsException(() => dictionary.ToConnectionString(null!)); - Assert.ThrowsException(() => dictionary.ToConnectionString(null!, _ => _)); - Assert.ThrowsException(() => dictionary.ToConnectionString(_ => _, null!)); + Assert.Throws(() => _ = dictionary.ToConnectionString(null!)); + Assert.Throws(() => _ = dictionary.ToConnectionString(null!, _ => _)); + Assert.Throws(() => _ = dictionary.ToConnectionString(_ => _, null!)); } - [TestMethod] + [Test] public void ToGetParameters_ShouldReturnParameters() { var dictionary = new Dictionary {["id"] = "1", ["user"] = "hello world", ["foo"] = "bar"}; string queryString = dictionary.ToGetParameters(); - Assert.AreEqual("id=1&user=hello+world&foo=bar", queryString); + Assert.That(queryString, Is.EqualTo("id=1&user=hello+world&foo=bar")); } - [TestMethod] + [Test] public void ToGetParameters_ShouldReturnTransformedValueParameters() { var dictionary = new Dictionary {["id"] = "1", ["user"] = "hello world", ["foo"] = null}; string queryString = dictionary.ToGetParameters(v => v?.ToUpper()); - Assert.AreEqual("id=1&user=HELLO+WORLD&foo=", queryString); + Assert.That(queryString, Is.EqualTo("id=1&user=HELLO+WORLD&foo=")); } - [TestMethod] + [Test] public void ToGetParameters_ShouldReturnTransformedKeyValueParameters() { var dictionary = new Dictionary {["id"] = "1", ["user"] = "hello world", ["foo"] = null}; string queryString = dictionary.ToGetParameters(k => k.ToUpper(), v => v?.ToUpper()); - Assert.AreEqual("ID=1&USER=HELLO+WORLD&FOO=", queryString); + Assert.That(queryString, Is.EqualTo("ID=1&USER=HELLO+WORLD&FOO=")); } - [TestMethod] + [Test] public void ToGetParameters_ShouldThrow_GivenNullSource() { - Dictionary? dictionary = null; - Assert.ThrowsException(() => dictionary!.ToGetParameters()); - Assert.ThrowsException(() => dictionary!.ToGetParameters(null!)); - Assert.ThrowsException(() => dictionary!.ToGetParameters(null!, null!)); + Dictionary dictionary = null!; + Assert.Throws(() => _ = dictionary.ToGetParameters()); + Assert.Throws(() => _ = dictionary.ToGetParameters(null!)); + Assert.Throws(() => _ = dictionary.ToGetParameters(null!, null!)); } - [TestMethod] + [Test] public void ToGetParameters_ShouldThrow_GivenNullSelector() { var dictionary = new Dictionary(); - Assert.ThrowsException(() => dictionary.ToGetParameters(null!)); - Assert.ThrowsException(() => dictionary.ToGetParameters(null!, _ => _)); - Assert.ThrowsException(() => dictionary.ToGetParameters(_ => _, null!)); + Assert.Throws(() => _ = dictionary.ToGetParameters(null!)); + Assert.Throws(() => _ = dictionary.ToGetParameters(null!, _ => _)); + Assert.Throws(() => _ = dictionary.ToGetParameters(_ => _, null!)); } } diff --git a/X10D.Tests/src/Collections/EnumerableTests.DisposeAll.cs b/X10D.Tests/src/Collections/EnumerableTests.DisposeAll.cs index f616b62..d5a4b8e 100644 --- a/X10D.Tests/src/Collections/EnumerableTests.DisposeAll.cs +++ b/X10D.Tests/src/Collections/EnumerableTests.DisposeAll.cs @@ -1,15 +1,15 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; +using Moq; +using NUnit.Framework; using X10D.Collections; namespace X10D.Tests.Collections; public partial class EnumerableTests { - [TestClass] + [TestFixture] public class DisposeAllTests { - [TestMethod] + [Test] public void DisposeAll_ShouldDisposeAllItems_WhenCalledWithValidList() { var mock1 = new Mock(); @@ -24,11 +24,11 @@ public partial class EnumerableTests mock3.Verify(i => i.Dispose(), Times.Once); } - [TestMethod] + [Test] public void DisposeAll_ShouldThrowArgumentNullException_WhenCalledWithNullList() { - List? list = null; - Assert.ThrowsException(() => list!.DisposeAll()); + List list = null!; + Assert.Throws(() => list.DisposeAll()); } } } diff --git a/X10D.Tests/src/Collections/EnumerableTests.DisposeAllAsync.cs b/X10D.Tests/src/Collections/EnumerableTests.DisposeAllAsync.cs index d683940..867006e 100644 --- a/X10D.Tests/src/Collections/EnumerableTests.DisposeAllAsync.cs +++ b/X10D.Tests/src/Collections/EnumerableTests.DisposeAllAsync.cs @@ -1,15 +1,15 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; +using Moq; +using NUnit.Framework; using X10D.Collections; namespace X10D.Tests.Collections; public partial class EnumerableTests { - [TestClass] + [TestFixture] public class DisposeAllAsyncTests { - [TestMethod] + [Test] public async Task DisposeAllAsync_ShouldDisposeAllItems_WhenCalledWithValidList() { var mock1 = new Mock(); @@ -24,11 +24,11 @@ public partial class EnumerableTests mock3.Verify(i => i.DisposeAsync(), Times.Once); } - [TestMethod] - public async Task DisposeAllAsync_ShouldThrowArgumentNullException_WhenCalledWithNullList() + [Test] + public void DisposeAllAsync_ShouldThrowArgumentNullException_WhenCalledWithNullList() { - List? list = null; - await Assert.ThrowsExceptionAsync(() => list!.DisposeAllAsync()).ConfigureAwait(false); + List list = null!; + Assert.ThrowsAsync(() => list.DisposeAllAsync()); } } } diff --git a/X10D.Tests/src/Collections/EnumerableTests.cs b/X10D.Tests/src/Collections/EnumerableTests.cs index e008e87..0fbc23e 100644 --- a/X10D.Tests/src/Collections/EnumerableTests.cs +++ b/X10D.Tests/src/Collections/EnumerableTests.cs @@ -1,33 +1,33 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Collections; using X10D.Core; namespace X10D.Tests.Collections; -[TestClass] +[TestFixture] public partial class EnumerableTests { - [TestMethod] + [Test] public void CountWhereNot_ShouldReturnCorrectCount_GivenSequence() { var enumerable = new[] {2, 4, 6, 7, 8, 9, 10}; int count = enumerable.CountWhereNot(x => x % 2 == 0); - Assert.AreEqual(2, count); + Assert.That(count, Is.EqualTo(2)); } - [TestMethod] + [Test] public void CountWhereNot_ShouldThrowArgumentNullException_GivenNullSource() { - Assert.ThrowsException(() => ((IEnumerable?)null)!.CountWhereNot(x => x % 2 == 0)); + Assert.Throws(() => ((IEnumerable?)null)!.CountWhereNot(x => x % 2 == 0)); } - [TestMethod] + [Test] public void CountWhereNot_ShouldThrowArgumentNullException_GivenNullPredicate() { - Assert.ThrowsException(() => Enumerable.Empty().CountWhereNot(null!)); + Assert.Throws(() => Enumerable.Empty().CountWhereNot(null!)); } - [TestMethod] + [Test] public void CountWhereNot_ShouldThrowOverflowException_GivenLargeSource() { IEnumerable GetValues() @@ -40,76 +40,76 @@ public partial class EnumerableTests // ReSharper disable once IteratorNeverReturns } - Assert.ThrowsException(() => GetValues().CountWhereNot(x => x % 2 == 0)); + Assert.Throws(() => _ = GetValues().CountWhereNot(x => x % 2 == 0)); } - [TestMethod] + [Test] public void FirstWhereNot_ShouldReturnCorrectElements_GivenSequence() { var enumerable = new[] {2, 4, 6, 7, 8, 9, 10}; int result = enumerable.FirstWhereNot(x => x % 2 == 0); - Assert.AreEqual(7, result); + Assert.That(result, Is.EqualTo(7)); } - [TestMethod] + [Test] public void FirstWhereNot_ShouldThrowArgumentNullException_GivenNullSource() { - Assert.ThrowsException(() => ((IEnumerable?)null)!.FirstWhereNot(x => x % 2 == 0)); + Assert.Throws(() => _ = ((IEnumerable?)null)!.FirstWhereNot(x => x % 2 == 0)); } - [TestMethod] + [Test] public void FirstWhereNot_ShouldThrowArgumentNullException_GivenNullPredicate() { - Assert.ThrowsException(() => Enumerable.Range(0, 1).FirstWhereNot(null!)); + Assert.Throws(() => _ = Enumerable.Range(0, 1).FirstWhereNot(null!)); } - [TestMethod] + [Test] public void FirstWhereNot_ShouldThrowInvalidOperationException_GivenEmptySource() { - Assert.ThrowsException(() => Enumerable.Empty().FirstWhereNot(x => x % 2 == 0)); + Assert.Throws(() => _ = Enumerable.Empty().FirstWhereNot(x => x % 2 == 0)); } - [TestMethod] + [Test] public void FirstWhereNot_ShouldThrowInvalidOperationException_GivenSourceWithNoMatchingElements() { - Assert.ThrowsException(() => 2.AsArrayValue().FirstWhereNot(x => x % 2 == 0)); + Assert.Throws(() => _ = 2.AsArrayValue().FirstWhereNot(x => x % 2 == 0)); } - [TestMethod] + [Test] public void FirstWhereNotOrDefault_ShouldReturnCorrectElements_GivenSequence() { var enumerable = new[] {2, 4, 6, 7, 8, 9, 10}; int result = enumerable.FirstWhereNotOrDefault(x => x % 2 == 0); - Assert.AreEqual(7, result); + Assert.That(result, Is.EqualTo(7)); } - [TestMethod] + [Test] public void FirstWhereNotOrDefault_ShouldThrowArgumentNullException_GivenNullSource() { - Assert.ThrowsException(() => ((IEnumerable?)null)!.FirstWhereNotOrDefault(x => x % 2 == 0)); + Assert.Throws(() => _ = ((IEnumerable?)null)!.FirstWhereNotOrDefault(x => x % 2 == 0)); } - [TestMethod] + [Test] public void FirstWhereNotOrDefault_ShouldThrowArgumentNullException_GivenNullPredicate() { - Assert.ThrowsException(() => Enumerable.Empty().FirstWhereNotOrDefault(null!)); + Assert.Throws(() => _ = Enumerable.Empty().FirstWhereNotOrDefault(null!)); } - [TestMethod] + [Test] public void FirstWhereNotOrDefault_ShouldReturnDefault_GivenEmptySource() { int result = Enumerable.Empty().FirstWhereNotOrDefault(x => x % 2 == 0); - Assert.AreEqual(default, result); + Assert.That(result, Is.Zero); } - [TestMethod] + [Test] public void FirstWhereNotOrDefault_ShouldReturnDefault_GivenSourceWithNoMatchingElements() { int result = 2.AsArrayValue().FirstWhereNotOrDefault(x => x % 2 == 0); - Assert.AreEqual(default, result); + Assert.That(result, Is.Zero); } - [TestMethod] + [Test] public void For_ShouldTransform_GivenTransformationDelegate() { var oneToTen = new[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; @@ -124,21 +124,21 @@ public partial class EnumerableTests CollectionAssert.AreEqual(multipliedByIndex, values.ToArray()); } - [TestMethod] + [Test] public void For_ShouldThrow_GivenNullSource() { IEnumerable? source = null; - Assert.ThrowsException(() => source!.For((_, _) => { })); + Assert.Throws(() => source!.For((_, _) => { })); } - [TestMethod] + [Test] public void For_ShouldThrow_GivenNullAction() { IEnumerable source = ArraySegment.Empty; - Assert.ThrowsException(() => source.For(null!)); + Assert.Throws(() => source.For(null!)); } - [TestMethod] + [Test] public void ForEach_ShouldTransform_GivenTransformationDelegate() { var oneToTen = new[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; @@ -153,93 +153,93 @@ public partial class EnumerableTests CollectionAssert.AreEqual(oneToTenDoubled, values.ToArray()); } - [TestMethod] + [Test] public void ForEach_ShouldThrow_GivenNullSource() { IEnumerable? source = null; - Assert.ThrowsException(() => source!.ForEach(_ => { })); + Assert.Throws(() => source!.ForEach(_ => { })); } - [TestMethod] + [Test] public void ForEach_ShouldThrow_GivenNullAction() { IEnumerable source = ArraySegment.Empty; - Assert.ThrowsException(() => source.ForEach(null!)); + Assert.Throws(() => source.ForEach(null!)); } - [TestMethod] + [Test] public void LastWhereNot_ShouldReturnCorrectElements_GivenSequence() { var enumerable = new[] {2, 4, 6, 7, 8, 9, 10}; int result = enumerable.LastWhereNot(x => x % 2 == 0); - Assert.AreEqual(9, result); + Assert.That(result, Is.EqualTo(9)); } - [TestMethod] + [Test] public void LastWhereNot_ShouldThrowArgumentNullException_GivenNullSource() { - Assert.ThrowsException(() => ((IEnumerable?)null)!.LastWhereNot(x => x % 2 == 0)); + Assert.Throws(() => _ = ((IEnumerable?)null)!.LastWhereNot(x => x % 2 == 0)); } - [TestMethod] + [Test] public void LastWhereNot_ShouldThrowArgumentNullException_GivenNullPredicate() { - Assert.ThrowsException(() => Array.Empty().LastWhereNot(null!)); + Assert.Throws(() => _ = Array.Empty().LastWhereNot(null!)); } - [TestMethod] + [Test] public void LastWhereNot_ShouldThrowInvalidOperationException_GivenEmptySource() { - Assert.ThrowsException(() => Array.Empty().LastWhereNot(x => x % 2 == 0)); + Assert.Throws(() => _ = Array.Empty().LastWhereNot(x => x % 2 == 0)); } - [TestMethod] + [Test] public void LastWhereNot_ShouldThrowInvalidOperationException_GivenSourceWithNoMatchingElements() { - Assert.ThrowsException(() => 2.AsArrayValue().LastWhereNot(x => x % 2 == 0)); + Assert.Throws(() => _ = 2.AsArrayValue().LastWhereNot(x => x % 2 == 0)); } - [TestMethod] + [Test] public void LastWhereNotOrDefault_ShouldReturnCorrectElements_GivenSequence() { var enumerable = new[] {2, 4, 6, 7, 8, 9, 10}; int result = enumerable.LastWhereNotOrDefault(x => x % 2 == 0); - Assert.AreEqual(9, result); + Assert.That(result, Is.EqualTo(9)); } - [TestMethod] + [Test] public void LastWhereNotOrDefault_ShouldThrowArgumentNullException_GivenNullSource() { - Assert.ThrowsException(() => ((IEnumerable?)null)!.LastWhereNotOrDefault(x => x % 2 == 0)); + Assert.Throws(() => _ = ((IEnumerable?)null)!.LastWhereNotOrDefault(x => x % 2 == 0)); } - [TestMethod] + [Test] public void LastWhereNotOrDefault_ShouldThrowArgumentNullException_GivenNullPredicate() { - Assert.ThrowsException(() => Array.Empty().LastWhereNotOrDefault(null!)); + Assert.Throws(() => _ = Array.Empty().LastWhereNotOrDefault(null!)); } - [TestMethod] + [Test] public void LastWhereNotOrDefault_ShouldReturnDefault_GivenEmptySource() { int result = Array.Empty().LastWhereNotOrDefault(x => x % 2 == 0); - Assert.AreEqual(default, result); + Assert.That(result, Is.Zero); } - [TestMethod] + [Test] public void LastWhereNotOrDefault_ShouldReturnDefault_GivenSourceWithNoMatchingElements() { int result = 2.AsArrayValue().LastWhereNotOrDefault(x => x % 2 == 0); - Assert.AreEqual(default, result); + Assert.That(result, Is.Zero); } - [TestMethod] + [Test] public void Shuffled_ShouldThrow_GivenNull() { - Assert.ThrowsException(() => ((List?)null)!.Shuffled()); + Assert.Throws(() => _ = ((List?)null)!.Shuffled()); } - [TestMethod] + [Test] public void Shuffled_ShouldReorder_GivenNotNull() { int[] array = Enumerable.Range(1, 52).ToArray(); // 52! chance of being shuffled to the same order @@ -251,7 +251,7 @@ public partial class EnumerableTests CollectionAssert.AreNotEqual(array, shuffled); } - [TestMethod] + [Test] public void WhereNot_ShouldReturnCorrectElements_GivenSequence() { var enumerable = new[] {2, 4, 6, 7, 8, 9, 10}; @@ -259,19 +259,19 @@ public partial class EnumerableTests CollectionAssert.AreEqual(new[] {7, 9}, result.ToArray()); } - [TestMethod] + [Test] public void WhereNot_ShouldThrowArgumentNullException_GivenNullSource() { - Assert.ThrowsException(() => ((IEnumerable?)null)!.WhereNot(x => x % 2 == 0)); + Assert.Throws(() => _ = ((IEnumerable?)null)!.WhereNot(x => x % 2 == 0)); } - [TestMethod] + [Test] public void WhereNot_ShouldThrowArgumentNullException_GivenNullPredicate() { - Assert.ThrowsException(() => Enumerable.Empty().WhereNot(null!)); + Assert.Throws(() => _ = Enumerable.Empty().WhereNot(null!)); } - [TestMethod] + [Test] public void WhereNotNull_ShouldContainNoNullElements() { object?[] array = Enumerable.Repeat(new object(), 10).ToArray(); @@ -289,14 +289,14 @@ public partial class EnumerableTests actualCount++; } - Assert.AreEqual(expectedCount, actualCount); + Assert.That(actualCount, Is.EqualTo(expectedCount)); } - [TestMethod] + [Test] public void WhereNotNull_ShouldThrowArgumentNullException_GivenNullSource() { IEnumerable source = null!; - Assert.ThrowsException(() => source.WhereNotNull()); + Assert.Throws(() => source.WhereNotNull()); } private class DummyClass diff --git a/X10D.Tests/src/Collections/Int16Tests.cs b/X10D.Tests/src/Collections/Int16Tests.cs index e5df97b..63c2cef 100644 --- a/X10D.Tests/src/Collections/Int16Tests.cs +++ b/X10D.Tests/src/Collections/Int16Tests.cs @@ -1,119 +1,131 @@ using System.Runtime.Intrinsics.X86; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Collections; namespace X10D.Tests.Collections; -[TestClass] +[TestFixture] public class Int16Tests { - [TestMethod] + [Test] public void Unpack_ShouldUnpackToArrayCorrectly() { - const short value = 0b11010100; - bool[] bits = value.Unpack(); - - Assert.AreEqual(16, bits.Length); - - Assert.IsFalse(bits[0]); - Assert.IsFalse(bits[1]); - Assert.IsTrue(bits[2]); - Assert.IsFalse(bits[3]); - Assert.IsTrue(bits[4]); - Assert.IsFalse(bits[5]); - Assert.IsTrue(bits[6]); - Assert.IsTrue(bits[7]); - - for (var index = 8; index < 16; index++) + Assert.Multiple(() => { - Assert.IsFalse(bits[index]); - } + const short value = 0b11010100; + bool[] bits = value.Unpack(); + + Assert.That(bits, Has.Length.EqualTo(16)); + Assert.That(bits[0], Is.False); + Assert.That(bits[1], Is.False); + Assert.That(bits[2], Is.True); + Assert.That(bits[3], Is.False); + Assert.That(bits[4], Is.True); + Assert.That(bits[5], Is.False); + Assert.That(bits[6], Is.True); + Assert.That(bits[7], Is.True); + + for (var index = 8; index < 16; index++) + { + Assert.That(bits[index], Is.False); + } + }); } - [TestMethod] + [Test] public void Unpack_ShouldUnpackToSpanCorrectly() { const short value = 0b11010100; - Span bits = stackalloc bool[16]; - value.Unpack(bits); - - Assert.IsFalse(bits[0]); - Assert.IsFalse(bits[1]); - Assert.IsTrue(bits[2]); - Assert.IsFalse(bits[3]); - Assert.IsTrue(bits[4]); - Assert.IsFalse(bits[5]); - Assert.IsTrue(bits[6]); - Assert.IsTrue(bits[7]); - - for (var index = 8; index < 16; index++) + Assert.Multiple(() => { - Assert.IsFalse(bits[index]); - } + Span bits = stackalloc bool[16]; + value.Unpack(bits); + + Assert.That(bits[0], Is.False); + Assert.That(bits[1], Is.False); + Assert.That(bits[2], Is.True); + Assert.That(bits[3], Is.False); + Assert.That(bits[4], Is.True); + Assert.That(bits[5], Is.False); + Assert.That(bits[6], Is.True); + Assert.That(bits[7], Is.True); + + for (var index = 8; index < 16; index++) + { + Assert.That(bits[index], Is.False); + } + }); } - [TestMethod] + [Test] public void Unpack_ShouldUnpackToSpanCorrectly_GivenFallbackImplementation() { const short value = 0b11010100; - Span bits = stackalloc bool[16]; - value.UnpackInternal_Fallback(bits); - - Assert.IsFalse(bits[0]); - Assert.IsFalse(bits[1]); - Assert.IsTrue(bits[2]); - Assert.IsFalse(bits[3]); - Assert.IsTrue(bits[4]); - Assert.IsFalse(bits[5]); - Assert.IsTrue(bits[6]); - Assert.IsTrue(bits[7]); - - for (var index = 8; index < 16; index++) + Assert.Multiple(() => { - Assert.IsFalse(bits[index]); - } + Span bits = stackalloc bool[16]; + value.UnpackInternal_Fallback(bits); + + Assert.That(bits[0], Is.False); + Assert.That(bits[1], Is.False); + Assert.That(bits[2], Is.True); + Assert.That(bits[3], Is.False); + Assert.That(bits[4], Is.True); + Assert.That(bits[5], Is.False); + Assert.That(bits[6], Is.True); + Assert.That(bits[7], Is.True); + + for (var index = 8; index < 16; index++) + { + Assert.That(bits[index], Is.False); + } + }); } #if NET5_0_OR_GREATER - [TestMethod] + [Test] public void UnpackInternal_Ssse3_ShouldUnpackToSpanCorrectly() { if (!Sse3.IsSupported) { + Assert.Pass(); return; } const short value = 0b11010100; - Span bits = stackalloc bool[16]; - value.UnpackInternal_Ssse3(bits); - - Assert.IsFalse(bits[0]); - Assert.IsFalse(bits[1]); - Assert.IsTrue(bits[2]); - Assert.IsFalse(bits[3]); - Assert.IsTrue(bits[4]); - Assert.IsFalse(bits[5]); - Assert.IsTrue(bits[6]); - Assert.IsTrue(bits[7]); - - for (var index = 8; index < 16; index++) + Assert.Multiple(() => { - Assert.IsFalse(bits[index]); - } + Span bits = stackalloc bool[16]; + value.UnpackInternal_Ssse3(bits); + + Assert.That(bits[0], Is.False); + Assert.That(bits[1], Is.False); + Assert.That(bits[2], Is.True); + Assert.That(bits[3], Is.False); + Assert.That(bits[4], Is.True); + Assert.That(bits[5], Is.False); + Assert.That(bits[6], Is.True); + Assert.That(bits[7], Is.True); + + for (var index = 8; index < 16; index++) + { + Assert.That(bits[index], Is.False); + } + }); } #endif - [TestMethod] + [Test] public void Unpack_ShouldRepackEqually() { const short value = 0b11010100; - Assert.AreEqual(value, value.Unpack().PackInt16()); + Assert.That(value.Unpack().PackInt16(), Is.EqualTo(value)); } - [TestMethod] + [Test] public void Unpack_ShouldThrow_GivenTooSmallSpan() { - Assert.ThrowsException(() => + Assert.Throws(() => { const short value = 0b11010100; Span bits = stackalloc bool[0]; diff --git a/X10D.Tests/src/Collections/Int32Tests.cs b/X10D.Tests/src/Collections/Int32Tests.cs index c48e0a0..9aee1e8 100644 --- a/X10D.Tests/src/Collections/Int32Tests.cs +++ b/X10D.Tests/src/Collections/Int32Tests.cs @@ -1,81 +1,90 @@ using System.Runtime.Intrinsics.X86; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Collections; namespace X10D.Tests.Collections; -[TestClass] +[TestFixture] public class Int32Tests { - [TestMethod] + [Test] public void Unpack_ShouldUnpackToArrayCorrectly() { const int value = 0b11010100; - bool[] bits = value.Unpack(); - Assert.AreEqual(32, bits.Length); - - Assert.IsFalse(bits[0]); - Assert.IsFalse(bits[1]); - Assert.IsTrue(bits[2]); - Assert.IsFalse(bits[3]); - Assert.IsTrue(bits[4]); - Assert.IsFalse(bits[5]); - Assert.IsTrue(bits[6]); - Assert.IsTrue(bits[7]); - - for (var index = 8; index < 32; index++) + Assert.Multiple(() => { - Assert.IsFalse(bits[index]); - } + bool[] bits = value.Unpack(); + Assert.That(bits, Has.Length.EqualTo(32)); + + Assert.That(bits[0], Is.False); + Assert.That(bits[1], Is.False); + Assert.That(bits[2], Is.True); + Assert.That(bits[3], Is.False); + Assert.That(bits[4], Is.True); + Assert.That(bits[5], Is.False); + Assert.That(bits[6], Is.True); + Assert.That(bits[7], Is.True); + + for (var index = 8; index < 32; index++) + { + Assert.That(bits[index], Is.False); + } + }); } - [TestMethod] + [Test] public void Unpack_ShouldUnpackToSpanCorrectly() { const int value = 0b11010100; - Span bits = stackalloc bool[32]; - value.Unpack(bits); - - Assert.IsFalse(bits[0]); - Assert.IsFalse(bits[1]); - Assert.IsTrue(bits[2]); - Assert.IsFalse(bits[3]); - Assert.IsTrue(bits[4]); - Assert.IsFalse(bits[5]); - Assert.IsTrue(bits[6]); - Assert.IsTrue(bits[7]); - - for (var index = 8; index < 32; index++) + Assert.Multiple(() => { - Assert.IsFalse(bits[index]); - } + Span bits = stackalloc bool[32]; + value.Unpack(bits); + + Assert.That(bits[0], Is.False); + Assert.That(bits[1], Is.False); + Assert.That(bits[2], Is.True); + Assert.That(bits[3], Is.False); + Assert.That(bits[4], Is.True); + Assert.That(bits[5], Is.False); + Assert.That(bits[6], Is.True); + Assert.That(bits[7], Is.True); + + for (var index = 8; index < 32; index++) + { + Assert.That(bits[index], Is.False); + } + }); } - [TestMethod] + [Test] public void UnpackInternal_Fallback_ShouldUnpackToSpanCorrectly() { const int value = 0b11010100; - Span bits = stackalloc bool[32]; - value.UnpackInternal_Fallback(bits); - - Assert.IsFalse(bits[0]); - Assert.IsFalse(bits[1]); - Assert.IsTrue(bits[2]); - Assert.IsFalse(bits[3]); - Assert.IsTrue(bits[4]); - Assert.IsFalse(bits[5]); - Assert.IsTrue(bits[6]); - Assert.IsTrue(bits[7]); - - for (var index = 8; index < 32; index++) + Assert.Multiple(() => { - Assert.IsFalse(bits[index]); - } + Span bits = stackalloc bool[32]; + value.UnpackInternal_Fallback(bits); + + Assert.That(bits[0], Is.False); + Assert.That(bits[1], Is.False); + Assert.That(bits[2], Is.True); + Assert.That(bits[3], Is.False); + Assert.That(bits[4], Is.True); + Assert.That(bits[5], Is.False); + Assert.That(bits[6], Is.True); + Assert.That(bits[7], Is.True); + + for (var index = 8; index < 32; index++) + { + Assert.That(bits[index], Is.False); + } + }); } #if NET5_0_OR_GREATER - [TestMethod] + [Test] public void UnpackInternal_Ssse3_ShouldUnpackToSpanCorrectly() { if (!Ssse3.IsSupported) @@ -84,25 +93,28 @@ public class Int32Tests } const int value = 0b11010100; - Span bits = stackalloc bool[32]; - value.UnpackInternal_Ssse3(bits); - - Assert.IsFalse(bits[0]); - Assert.IsFalse(bits[1]); - Assert.IsTrue(bits[2]); - Assert.IsFalse(bits[3]); - Assert.IsTrue(bits[4]); - Assert.IsFalse(bits[5]); - Assert.IsTrue(bits[6]); - Assert.IsTrue(bits[7]); - - for (var index = 8; index < 32; index++) + Assert.Multiple(() => { - Assert.IsFalse(bits[index]); - } + Span bits = stackalloc bool[32]; + value.UnpackInternal_Ssse3(bits); + + Assert.That(bits[0], Is.False); + Assert.That(bits[1], Is.False); + Assert.That(bits[2], Is.True); + Assert.That(bits[3], Is.False); + Assert.That(bits[4], Is.True); + Assert.That(bits[5], Is.False); + Assert.That(bits[6], Is.True); + Assert.That(bits[7], Is.True); + + for (var index = 8; index < 32; index++) + { + Assert.That(bits[index], Is.False); + } + }); } - [TestMethod] + [Test] public void UnpackInternal_Avx2_ShouldUnpackToSpanCorrectly() { if (!Avx2.IsSupported) @@ -111,36 +123,39 @@ public class Int32Tests } const int value = 0b11010100; - Span bits = stackalloc bool[32]; - value.UnpackInternal_Avx2(bits); - - Assert.IsFalse(bits[0]); - Assert.IsFalse(bits[1]); - Assert.IsTrue(bits[2]); - Assert.IsFalse(bits[3]); - Assert.IsTrue(bits[4]); - Assert.IsFalse(bits[5]); - Assert.IsTrue(bits[6]); - Assert.IsTrue(bits[7]); - - for (var index = 8; index < 32; index++) + Assert.Multiple(() => { - Assert.IsFalse(bits[index]); - } + Span bits = stackalloc bool[32]; + value.UnpackInternal_Avx2(bits); + + Assert.That(bits[0], Is.False); + Assert.That(bits[1], Is.False); + Assert.That(bits[2], Is.True); + Assert.That(bits[3], Is.False); + Assert.That(bits[4], Is.True); + Assert.That(bits[5], Is.False); + Assert.That(bits[6], Is.True); + Assert.That(bits[7], Is.True); + + for (var index = 8; index < 32; index++) + { + Assert.That(bits[index], Is.False); + } + }); } #endif - [TestMethod] + [Test] public void Unpack_ShouldRepackEqually() { const int value = 0b11010100; - Assert.AreEqual(value, value.Unpack().PackInt32()); + Assert.That(value.Unpack().PackInt32(), Is.EqualTo(value)); } - [TestMethod] + [Test] public void Unpack_ShouldThrow_GivenTooSmallSpan() { - Assert.ThrowsException(() => + Assert.Throws(() => { const int value = 0b11010100; Span bits = stackalloc bool[0]; diff --git a/X10D.Tests/src/Collections/Int64Tests.cs b/X10D.Tests/src/Collections/Int64Tests.cs index 2622863..02b89df 100644 --- a/X10D.Tests/src/Collections/Int64Tests.cs +++ b/X10D.Tests/src/Collections/Int64Tests.cs @@ -1,68 +1,73 @@ using System.Diagnostics; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Collections; namespace X10D.Tests.Collections; -[TestClass] +[TestFixture] public class Int64Tests { - [TestMethod] + [Test] public void UnpackBits_ShouldUnpackToArrayCorrectly() { bool[] bits = 0b11010100L.Unpack(); - Assert.AreEqual(64, bits.Length); + Assert.That(bits, Has.Length.EqualTo(64)); Trace.WriteLine(Convert.ToString(0b11010100L, 2)); Trace.WriteLine(string.Join("", bits.Select(b => b ? "1" : "0"))); - - Assert.IsFalse(bits[0]); - Assert.IsFalse(bits[1]); - Assert.IsTrue(bits[2]); - Assert.IsFalse(bits[3]); - Assert.IsTrue(bits[4]); - Assert.IsFalse(bits[5]); - Assert.IsTrue(bits[6]); - Assert.IsTrue(bits[7]); - - for (var index = 8; index < 64; index++) + Assert.Multiple(() => { - Assert.IsFalse(bits[index], index.ToString()); - } + Assert.That(bits[0], Is.False); + Assert.That(bits[1], Is.False); + Assert.That(bits[2], Is.True); + Assert.That(bits[3], Is.False); + Assert.That(bits[4], Is.True); + Assert.That(bits[5], Is.False); + Assert.That(bits[6], Is.True); + Assert.That(bits[7], Is.True); + + for (var index = 8; index < 64; index++) + { + Assert.That(bits[index], Is.False, index.ToString()); + } + }); } - [TestMethod] + [Test] public void UnpackBits_ShouldUnpackToSpanCorrectly() { - Span bits = stackalloc bool[64]; - 0b11010100L.Unpack(bits); - - Assert.IsFalse(bits[0]); - Assert.IsFalse(bits[1]); - Assert.IsTrue(bits[2]); - Assert.IsFalse(bits[3]); - Assert.IsTrue(bits[4]); - Assert.IsFalse(bits[5]); - Assert.IsTrue(bits[6]); - Assert.IsTrue(bits[7]); - - for (var index = 8; index < 64; index++) + Assert.Multiple(() => { - Assert.IsFalse(bits[index], index.ToString()); - } + Span bits = stackalloc bool[64]; + 0b11010100L.Unpack(bits); + + Assert.That(bits[0], Is.False); + Assert.That(bits[1], Is.False); + Assert.That(bits[2], Is.True); + Assert.That(bits[3], Is.False); + Assert.That(bits[4], Is.True); + Assert.That(bits[5], Is.False); + Assert.That(bits[6], Is.True); + Assert.That(bits[7], Is.True); + + for (var index = 8; index < 64; index++) + { + Assert.That(bits[index], Is.False, index.ToString()); + } + }); } - [TestMethod] + [Test] public void UnpackBits_ShouldRepackEqually() { - Assert.AreEqual(0b11010100L, 0b11010100L.Unpack().PackInt64()); + Assert.That(0b11010100L.Unpack().PackInt64(), Is.EqualTo(0b11010100L)); } - [TestMethod] + [Test] public void UnpackBits_ShouldThrow_GivenTooSmallSpan() { - Assert.ThrowsException(() => + Assert.Throws(() => { Span bits = stackalloc bool[0]; 0b11010100L.Unpack(bits); diff --git a/X10D.Tests/src/Collections/ListTests.cs b/X10D.Tests/src/Collections/ListTests.cs index 06c079a..095444f 100644 --- a/X10D.Tests/src/Collections/ListTests.cs +++ b/X10D.Tests/src/Collections/ListTests.cs @@ -1,16 +1,16 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Collections; namespace X10D.Tests.Collections; -[TestClass] +[TestFixture] public class ListTests { [CLSCompliant(false)] - [TestMethod] - [DataRow(1)] - [DataRow(1, 2, 3)] - [DataRow(1, 2, 3, 4, 5)] + [Test] + [TestCase(1)] + [TestCase(1, 2, 3)] + [TestCase(1, 2, 3, 4, 5)] public void Fill_ShouldGiveHomogenousList_GivenValue(params int[] args) { int[] all42 = Enumerable.Repeat(42, args.Length).ToArray(); @@ -27,154 +27,169 @@ public class ListTests } [CLSCompliant(false)] - [TestMethod] - [DataRow(1)] - [DataRow(1, 2, 3)] - [DataRow(1, 2, 3, 4, 5)] + [Test] + [TestCase(1)] + [TestCase(1, 2, 3)] + [TestCase(1, 2, 3, 4, 5)] public void SlicedFill_ShouldLeaveFirstElement_GivenStartIndex1(params int[] args) { int first = args[0]; args.Fill(1, 1, args.Length - 1); int[] comparison = Enumerable.Repeat(1, args.Length - 1).ToArray(); - Assert.AreEqual(first, args[0]); + Assert.That(args[0], Is.EqualTo(first)); CollectionAssert.AreEqual(comparison, args[1..]); } - [TestMethod] + [Test] public void Fill_ShouldThrow_GivenExceededCount() { int[] array = Array.Empty(); var list = new List(); - Assert.ThrowsException(() => array.Fill(0, 0, 1)); - Assert.ThrowsException(() => list.Fill(0, 0, 1)); + Assert.Throws(() => array.Fill(0, 0, 1)); + Assert.Throws(() => list.Fill(0, 0, 1)); } - [TestMethod] + [Test] public void Fill_ShouldThrow_GivenNegativeCount() { int[] array = Array.Empty(); var list = new List(); - Assert.ThrowsException(() => array.Fill(0, 0, -1)); - Assert.ThrowsException(() => list.Fill(0, 0, -1)); + Assert.Throws(() => array.Fill(0, 0, -1)); + Assert.Throws(() => list.Fill(0, 0, -1)); } - [TestMethod] + [Test] public void Fill_ShouldThrow_GivenNegativeStartIndex() { int[] array = Array.Empty(); var list = new List(); - Assert.ThrowsException(() => array.Fill(0, -1, 0)); - Assert.ThrowsException(() => list.Fill(0, -1, 0)); + Assert.Throws(() => array.Fill(0, -1, 0)); + Assert.Throws(() => list.Fill(0, -1, 0)); } - [TestMethod] + [Test] public void Fill_ShouldThrow_GivenNull() { int[]? array = null; List? list = null; - Assert.ThrowsException(() => array!.Fill(0)); - Assert.ThrowsException(() => list!.Fill(0)); - Assert.ThrowsException(() => array!.Fill(0, 0, 0)); - Assert.ThrowsException(() => list!.Fill(0, 0, 0)); + Assert.Throws(() => array!.Fill(0)); + Assert.Throws(() => list!.Fill(0)); + Assert.Throws(() => array!.Fill(0, 0, 0)); + Assert.Throws(() => list!.Fill(0, 0, 0)); } - [TestMethod] + [Test] public void IndexOf_ShouldReturnCorrectValue_FromStartOfList() { int[] array = {0, 1, 2, 3, 4}; - Assert.AreEqual(2, array.IndexOf(2)); - Assert.AreEqual(2, array.IndexOf(2, 0)); - Assert.AreEqual(2, array.IndexOf(2, 0, 5)); + Assert.Multiple(() => + { + Assert.That(array.IndexOf(2), Is.EqualTo(2)); + Assert.That(array.IndexOf(2, 0), Is.EqualTo(2)); + Assert.That(array.IndexOf(2, 0, 5), Is.EqualTo(2)); + }); } - [TestMethod] + [Test] public void IndexOf_ShouldReturnCorrectValue_GivenSubRange() { int[] array = {0, 1, 2, 3, 4, 0}; - Assert.AreEqual(0, array.IndexOf(0)); - Assert.AreEqual(0, array.IndexOf(0, 0)); - Assert.AreEqual(0, array.IndexOf(0, 0, 5)); + Assert.Multiple(() => + { + Assert.That(array.IndexOf(0), Is.Zero); + Assert.That(array.IndexOf(0, 0), Is.Zero); + Assert.That(array.IndexOf(0, 0, 5), Is.Zero); - Assert.AreEqual(5, array.IndexOf(0, 1)); - Assert.AreEqual(5, array.IndexOf(0, 1, 5)); + Assert.That(array.IndexOf(0, 1), Is.EqualTo(5)); + Assert.That(array.IndexOf(0, 1, 5), Is.EqualTo(5)); + }); } - [TestMethod] + [Test] public void IndexOf_ShouldReturnNegative1_ForEmptyList() { int[] array = Array.Empty(); - Assert.AreEqual(-1, array.IndexOf(0)); - Assert.AreEqual(-1, array.IndexOf(0, 0)); - Assert.AreEqual(-1, array.IndexOf(0, 0, 0)); + Assert.Multiple(() => + { + Assert.That(array.IndexOf(0), Is.EqualTo(-1)); + Assert.That(array.IndexOf(0, 0), Is.EqualTo(-1)); + Assert.That(array.IndexOf(0, 0, 0), Is.EqualTo(-1)); + }); } - [TestMethod] + [Test] public void IndexOf_ShouldThrowArgumentNullException_GivenNullList() { int[]? array = null; - Assert.ThrowsException(() => array!.IndexOf(0)); - Assert.ThrowsException(() => array!.IndexOf(0, 0)); - Assert.ThrowsException(() => array!.IndexOf(0, 0, 0)); + Assert.Multiple(() => + { + Assert.Throws(() => array!.IndexOf(0)); + Assert.Throws(() => array!.IndexOf(0, 0)); + Assert.Throws(() => array!.IndexOf(0, 0, 0)); + }); } - [TestMethod] + [Test] public void IndexOf_ShouldThrowArgumentOutOfRangeException_GivenNegativeCount() { int[] array = Array.Empty(); - Assert.ThrowsException(() => array.IndexOf(0, 0, -1)); + Assert.Throws(() => array.IndexOf(0, 0, -1)); } - [TestMethod] + [Test] public void IndexOf_ShouldThrowArgumentOutOfRangeException_GivenNegativeStartIndex() { int[] array = Array.Empty(); - Assert.ThrowsException(() => array.IndexOf(0, -1)); - Assert.ThrowsException(() => array.IndexOf(0, -1, 0)); + Assert.Multiple(() => + { + Assert.Throws(() => array.IndexOf(0, -1)); + Assert.Throws(() => array.IndexOf(0, -1, 0)); + }); } - [TestMethod] + [Test] public void IndexOf_ShouldThrowArgumentOutOfRangeException_GivenInvalidStartIndexCountPair() { int[] array = {0, 1, 2}; - Assert.ThrowsException(() => array.IndexOf(0, 2, 4)); + Assert.Throws(() => array.IndexOf(0, 2, 4)); } - [TestMethod] + [Test] public void Random_ShouldReturnContainedObject_GivenNotNull() { var list = new List(Enumerable.Range(1, 52)); // 52! chance of being shuffled to the same order int random = list.Random(); - Assert.IsTrue(list.Contains(random)); + Assert.That(list, Does.Contain(random)); } - [TestMethod] + [Test] public void Random_ShouldThrow_GivenNull() { - Assert.ThrowsException(() => ((List?)null)!.Random()); + Assert.Throws(() => _ = ((List?)null)!.Random()); } - [TestMethod] + [Test] public void RemoveRange_ShouldThrowArgumentNullException_GivenNull() { - Assert.ThrowsException(() => ((List?)null)!.RemoveRange(new Range())); + Assert.Throws(() => ((List?)null)!.RemoveRange(new Range())); } - [TestMethod] + [Test] public void RemoveRange_ShouldThrowArgumentException_GivenEndIndexLessThanStart() { - Assert.ThrowsException(() => new List().RemoveRange(2..0)); + Assert.Throws(() => new List().RemoveRange(2..0)); } - [TestMethod] + [Test] public void RemoveRange_ShouldThrowArgumentOutOfRangeException_GivenEndIndexGreaterThanOrEqualToCount() { - Assert.ThrowsException(() => new List().RemoveRange(..0)); - Assert.ThrowsException(() => new List {1}.RemoveRange(..2)); + Assert.Throws(() => new List().RemoveRange(..0)); + Assert.Throws(() => new List {1}.RemoveRange(..2)); } - [TestMethod] + [Test] public void RemoveRange_ShouldRemoveElements_GivenList() { var list = new List @@ -191,13 +206,14 @@ public class ListTests 10 }; - Assert.AreEqual(10, list.Count); + Assert.That(list, Has.Count.EqualTo(10)); list.RemoveRange(2..5); - Assert.AreEqual(6, list.Count); + + Assert.That(list, Has.Count.EqualTo(6)); CollectionAssert.AreEqual(new[] {1, 2, 7, 8, 9, 10}, list); } - [TestMethod] + [Test] public void Shuffle_ShouldReorder_GivenNotNull() { var list = new List(Enumerable.Range(1, 52)); // 52! chance of being shuffled to the same order @@ -210,27 +226,27 @@ public class ListTests CollectionAssert.AreNotEqual(list, shuffled); } - [TestMethod] + [Test] public void Shuffle_ShouldThrow_GivenNull() { - Assert.ThrowsException(() => ((List?)null)!.Shuffle()); + Assert.Throws(() => ((List?)null)!.Shuffle()); } - [TestMethod] + [Test] public void Slice_ShouldReturnCorrectValue_GivenStartIndex() { int[] array = {0, 1, 2, 3, 4, 5}; CollectionAssert.AreEqual(new[] {2, 3, 4, 5}, array.Slice(2).ToArray()); } - [TestMethod] + [Test] public void Slice_ShouldReturnCorrectValue_GivenStartIndexAndLength() { int[] array = {0, 1, 2, 3, 4, 5}; CollectionAssert.AreEqual(new[] {2, 3, 4}, array.Slice(2, 3).ToArray()); } - [TestMethod] + [Test] public void Slice_ShouldReturnEmptyList_ForEmptyList() { int[] array = Array.Empty(); @@ -238,49 +254,49 @@ public class ListTests CollectionAssert.AreEqual(Array.Empty(), array.Slice(0, 0).ToArray()); } - [TestMethod] + [Test] public void Slice_ShouldThrowArgumentNullException_GivenNullList() { int[]? array = null; - Assert.ThrowsException(() => array!.Slice(0)); - Assert.ThrowsException(() => array!.Slice(0, 0)); + Assert.Throws(() => array!.Slice(0)); + Assert.Throws(() => array!.Slice(0, 0)); } - [TestMethod] + [Test] public void Slice_ShouldThrowArgumentOutOfRangeException_GivenNegativeCount() { int[] array = Array.Empty(); - Assert.ThrowsException(() => array.Slice(0, -1)); + Assert.Throws(() => array.Slice(0, -1)); } - [TestMethod] + [Test] public void Slice_ShouldThrowArgumentOutOfRangeException_GivenNegativeStartIndex() { int[] array = Array.Empty(); - Assert.ThrowsException(() => array.Slice(-1)); - Assert.ThrowsException(() => array.Slice(-1, 0)); + Assert.Throws(() => array.Slice(-1)); + Assert.Throws(() => array.Slice(-1, 0)); } - [TestMethod] + [Test] public void Slice_ShouldThrowArgumentOutOfRangeException_GivenInvalidStartIndexCountPair() { int[] array = {0, 1, 2}; - Assert.ThrowsException(() => array.Slice(2, 4)); + Assert.Throws(() => array.Slice(2, 4)); } - [TestMethod] + [Test] public void Swap_ShouldThrowArgumentNullException_GivenNullSource() { - Assert.ThrowsException(() => ((IList?)null)!.Swap(new List())); + Assert.Throws(() => ((IList?)null)!.Swap(new List())); } - [TestMethod] + [Test] public void Swap_ShouldThrowArgumentNullException_GivenNullTarget() { - Assert.ThrowsException(() => new List().Swap(null!)); + Assert.Throws(() => new List().Swap(null!)); } - [TestMethod] + [Test] public void Swap_ShouldSwapElements_GivenMatchingElementCount() { var first = new List {1, 2, 3}; @@ -297,7 +313,7 @@ public class ListTests CollectionAssert.AreEqual(new[] {4, 5, 6}, second, string.Join(' ', second)); } - [TestMethod] + [Test] public void Swap_ShouldSwapElements_GivenDifferentElementCount() { var first = new List diff --git a/X10D.Tests/src/Collections/SpanTest.cs b/X10D.Tests/src/Collections/SpanTest.cs index 7506ca9..5df5acd 100644 --- a/X10D.Tests/src/Collections/SpanTest.cs +++ b/X10D.Tests/src/Collections/SpanTest.cs @@ -1,52 +1,52 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Collections; namespace X10D.Tests.Collections; -[TestClass] +[TestFixture] public class SpanTest { - [TestMethod] + [Test] public void Count_ShouldReturn0_GivenEmptySpan() { Span span = Span.Empty; int count = span.Count(2); - Assert.AreEqual(0, count); + Assert.That(count, Is.Zero); } - [TestMethod] + [Test] public void Count_ShouldReturn0_GivenEmptyReadOnlySpan() { ReadOnlySpan span = ReadOnlySpan.Empty; int count = span.Count(2); - Assert.AreEqual(0, count); + Assert.That(count, Is.Zero); } - [TestMethod] + [Test] public void Count_ShouldReturn8_GivenSpanWith8MatchingElements() { Span span = stackalloc int[16] {1, 2, 3, 2, 5, 2, 7, 2, 9, 2, 11, 2, 13, 2, 15, 2}; int count = span.Count(2); - Assert.AreEqual(8, count); + Assert.That(count, Is.EqualTo(8)); } - [TestMethod] + [Test] public void Count_ShouldReturn8_GivenReadOnlySpanWith8MatchingElements() { ReadOnlySpan span = stackalloc int[16] {1, 2, 3, 2, 5, 2, 7, 2, 9, 2, 11, 2, 13, 2, 15, 2}; int count = span.Count(2); - Assert.AreEqual(8, count); + Assert.That(count, Is.EqualTo(8)); } - [TestMethod] + [Test] public void Split_OnEmptySpan_ShouldYieldNothing_UsingCharDelimiter_GivenReadOnlySpan() { ReadOnlySpan span = ReadOnlySpan.Empty; @@ -57,10 +57,10 @@ public class SpanTest index++; } - Assert.AreEqual(0, index); + Assert.That(index, Is.Zero); } - [TestMethod] + [Test] public void Split_OnEmptySpan_ShouldYieldNothing_UsingCharDelimiter_GivenSpan() { Span span = Span.Empty; @@ -71,10 +71,10 @@ public class SpanTest index++; } - Assert.AreEqual(0, index); + Assert.That(index, Is.Zero); } - [TestMethod] + [Test] public void Split_OnEmptySpan_ShouldYieldNothing_UsingStringDelimiter_GivenReadOnlySpan() { ReadOnlySpan span = ReadOnlySpan.Empty; @@ -85,10 +85,10 @@ public class SpanTest index++; } - Assert.AreEqual(0, index); + Assert.That(index, Is.Zero); } - [TestMethod] + [Test] public void Split_OnEmptySpan_ShouldYieldNothing_UsingStringDelimiter_GivenSpan() { Span span = Span.Empty; @@ -99,10 +99,10 @@ public class SpanTest index++; } - Assert.AreEqual(0, index); + Assert.That(index, Is.Zero); } - [TestMethod] + [Test] public void Split_OnOneWord_ShouldYieldLength1_UsingCharDelimiter_GivenReadOnlySpan() { ReadOnlySpan span = "Hello ".AsSpan(); @@ -112,16 +112,16 @@ public class SpanTest { if (index == 0) { - Assert.AreEqual("Hello", subSpan.ToString()); + Assert.That(subSpan.ToString(), Is.EqualTo("Hello")); } index++; } - Assert.AreEqual(1, index); + Assert.That(index, Is.EqualTo(1)); } - [TestMethod] + [Test] public void Split_OnOneWord_ShouldYieldLength1_UsingCharDelimiter_GivenSpan() { ReadOnlySpan source = "Hello ".AsSpan(); @@ -133,16 +133,16 @@ public class SpanTest { if (index == 0) { - Assert.AreEqual("Hello", subSpan.ToString()); + Assert.That(subSpan.ToString(), Is.EqualTo("Hello")); } index++; } - Assert.AreEqual(1, index); + Assert.That(index, Is.EqualTo(1)); } - [TestMethod] + [Test] public void Split_OnOneWord_ShouldYieldLength1_UsingStringDelimiter_GivenReadOnlySpan() { ReadOnlySpan span = "Hello ".AsSpan(); @@ -152,16 +152,16 @@ public class SpanTest { if (index == 0) { - Assert.AreEqual("Hello", subSpan.ToString()); + Assert.That(subSpan.ToString(), Is.EqualTo("Hello")); } index++; } - Assert.AreEqual(1, index); + Assert.That(index, Is.EqualTo(1)); } - [TestMethod] + [Test] public void Split_OnOneWord_ShouldYieldLength1_UsingStringDelimiter_GivenSpan() { ReadOnlySpan source = "Hello ".AsSpan(); @@ -173,16 +173,16 @@ public class SpanTest { if (index == 0) { - Assert.AreEqual("Hello", subSpan.ToString()); + Assert.That(subSpan.ToString(), Is.EqualTo("Hello")); } index++; } - Assert.AreEqual(1, index); + Assert.That(index, Is.EqualTo(1)); } - [TestMethod] + [Test] public void Split_OnOneWordWithoutDelimiter_ShouldYieldLength1_UsingCharDelimiter_GivenReadOnlySpan() { ReadOnlySpan span = "Hello".AsSpan(); @@ -192,16 +192,16 @@ public class SpanTest { if (index == 0) { - Assert.AreEqual("Hello", subSpan.ToString()); + Assert.That(subSpan.ToString(), Is.EqualTo("Hello")); } index++; } - Assert.AreEqual(1, index); + Assert.That(index, Is.EqualTo(1)); } - [TestMethod] + [Test] public void Split_OnOneWordWithoutDelimiter_ShouldYieldLength1_UsingCharDelimiter_GivenSpan() { ReadOnlySpan source = "Hello".AsSpan(); @@ -213,16 +213,16 @@ public class SpanTest { if (index == 0) { - Assert.AreEqual("Hello", subSpan.ToString()); + Assert.That(subSpan.ToString(), Is.EqualTo("Hello")); } index++; } - Assert.AreEqual(1, index); + Assert.That(index, Is.EqualTo(1)); } - [TestMethod] + [Test] public void Split_OnOneWordWithoutDelimiter_ShouldYieldLength1_UsingStringDelimiter_GivenReadOnlySpan() { ReadOnlySpan span = "Hello".AsSpan(); @@ -232,16 +232,16 @@ public class SpanTest { if (index == 0) { - Assert.AreEqual("Hello", subSpan.ToString()); + Assert.That(subSpan.ToString(), Is.EqualTo("Hello")); } index++; } - Assert.AreEqual(1, index); + Assert.That(index, Is.EqualTo(1)); } - [TestMethod] + [Test] public void Split_OnOneWordWithoutDelimiter_ShouldYieldLength1_UsingStringDelimiter_GivenSpan() { ReadOnlySpan source = "Hello".AsSpan(); @@ -253,16 +253,16 @@ public class SpanTest { if (index == 0) { - Assert.AreEqual("Hello", subSpan.ToString()); + Assert.That(subSpan.ToString(), Is.EqualTo("Hello")); } index++; } - Assert.AreEqual(1, index); + Assert.That(index, Is.EqualTo(1)); } - [TestMethod] + [Test] public void Split_OnTwoWords_ShouldYieldLength2_UsingCharDelimiter_GivenReadOnlySpan() { ReadOnlySpan span = "Hello World ".AsSpan(); @@ -273,20 +273,20 @@ public class SpanTest switch (index) { case 0: - Assert.AreEqual("Hello", subSpan.ToString()); + Assert.That(subSpan.ToString(), Is.EqualTo("Hello")); break; case 1: - Assert.AreEqual("World", subSpan.ToString()); + Assert.That(subSpan.ToString(), Is.EqualTo("World")); break; } index++; } - Assert.AreEqual(2, index); + Assert.That(index, Is.EqualTo(2)); } - [TestMethod] + [Test] public void Split_OnTwoWords_ShouldYieldLength2_UsingCharDelimiter_GivenSpan() { ReadOnlySpan source = "Hello World ".AsSpan(); @@ -299,20 +299,20 @@ public class SpanTest switch (index) { case 0: - Assert.AreEqual("Hello", subSpan.ToString()); + Assert.That(subSpan.ToString(), Is.EqualTo("Hello")); break; case 1: - Assert.AreEqual("World", subSpan.ToString()); + Assert.That(subSpan.ToString(), Is.EqualTo("World")); break; } index++; } - Assert.AreEqual(2, index); + Assert.That(index, Is.EqualTo(2)); } - [TestMethod] + [Test] public void Split_OnTwoWords_ShouldYieldLength2_UsingStringDelimiter_GivenReadOnlySpan() { ReadOnlySpan span = "Hello World ".AsSpan(); @@ -323,20 +323,20 @@ public class SpanTest switch (index) { case 0: - Assert.AreEqual("Hello", subSpan.ToString()); + Assert.That(subSpan.ToString(), Is.EqualTo("Hello")); break; case 1: - Assert.AreEqual("World", subSpan.ToString()); + Assert.That(subSpan.ToString(), Is.EqualTo("World")); break; } index++; } - Assert.AreEqual(2, index); + Assert.That(index, Is.EqualTo(2)); } - [TestMethod] + [Test] public void Split_OnTwoWords_ShouldYieldLength2_UsingStringDelimiter_GivenSpan() { ReadOnlySpan source = "Hello World ".AsSpan(); @@ -349,20 +349,20 @@ public class SpanTest switch (index) { case 0: - Assert.AreEqual("Hello", subSpan.ToString()); + Assert.That(subSpan.ToString(), Is.EqualTo("Hello")); break; case 1: - Assert.AreEqual("World", subSpan.ToString()); + Assert.That(subSpan.ToString(), Is.EqualTo("World")); break; } index++; } - Assert.AreEqual(2, index); + Assert.That(index, Is.EqualTo(2)); } - [TestMethod] + [Test] public void Split_OnThreeWords_ShouldYieldLength3_UsingCharDelimiter_GivenReadOnlySpan() { ReadOnlySpan span = "Hello, the World ".AsSpan(); @@ -373,23 +373,23 @@ public class SpanTest switch (index) { case 0: - Assert.AreEqual("Hello,", subSpan.ToString()); + Assert.That(subSpan.ToString(), Is.EqualTo("Hello,")); break; case 1: - Assert.AreEqual("the", subSpan.ToString()); + Assert.That(subSpan.ToString(), Is.EqualTo("the")); break; case 2: - Assert.AreEqual("World", subSpan.ToString()); + Assert.That(subSpan.ToString(), Is.EqualTo("World")); break; } index++; } - Assert.AreEqual(3, index); + Assert.That(index, Is.EqualTo(3)); } - [TestMethod] + [Test] public void Split_OnThreeWords_ShouldYieldLength3_UsingCharDelimiter_GivenSpan() { ReadOnlySpan source = "Hello, the World ".AsSpan(); @@ -402,23 +402,23 @@ public class SpanTest switch (index) { case 0: - Assert.AreEqual("Hello,", subSpan.ToString()); + Assert.That(subSpan.ToString(), Is.EqualTo("Hello,")); break; case 1: - Assert.AreEqual("the", subSpan.ToString()); + Assert.That(subSpan.ToString(), Is.EqualTo("the")); break; case 2: - Assert.AreEqual("World", subSpan.ToString()); + Assert.That(subSpan.ToString(), Is.EqualTo("World")); break; } index++; } - Assert.AreEqual(3, index); + Assert.That(index, Is.EqualTo(3)); } - [TestMethod] + [Test] public void Split_OnThreeWords_ShouldYieldLength3_UsingStringDelimiter_GivenReadOnlySpan() { ReadOnlySpan span = "Hello, the World ".AsSpan(); @@ -429,23 +429,23 @@ public class SpanTest switch (index) { case 0: - Assert.AreEqual("Hello,", subSpan.ToString()); + Assert.That(subSpan.ToString(), Is.EqualTo("Hello,")); break; case 1: - Assert.AreEqual("the", subSpan.ToString()); + Assert.That(subSpan.ToString(), Is.EqualTo("the")); break; case 2: - Assert.AreEqual("World", subSpan.ToString()); + Assert.That(subSpan.ToString(), Is.EqualTo("World")); break; } index++; } - Assert.AreEqual(3, index); + Assert.That(index, Is.EqualTo(3)); } - [TestMethod] + [Test] public void Split_OnThreeWords_ShouldYieldLength3_UsingStringDelimiter_GivenSpan() { ReadOnlySpan source = "Hello, the World ".AsSpan(); @@ -458,19 +458,19 @@ public class SpanTest switch (index) { case 0: - Assert.AreEqual("Hello,", subSpan.ToString()); + Assert.That(subSpan.ToString(), Is.EqualTo("Hello,")); break; case 1: - Assert.AreEqual("the", subSpan.ToString()); + Assert.That(subSpan.ToString(), Is.EqualTo("the")); break; case 2: - Assert.AreEqual("World", subSpan.ToString()); + Assert.That(subSpan.ToString(), Is.EqualTo("World")); break; } index++; } - Assert.AreEqual(3, index); + Assert.That(index, Is.EqualTo(3)); } } diff --git a/X10D.Tests/src/Core/CoreTests.cs b/X10D.Tests/src/Core/CoreTests.cs index 57bf03d..41f1436 100644 --- a/X10D.Tests/src/Core/CoreTests.cs +++ b/X10D.Tests/src/Core/CoreTests.cs @@ -1,76 +1,78 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Core; namespace X10D.Tests.Core; -[TestClass] +[TestFixture] public class CoreTests { - [TestMethod] - [DataRow(1)] - [DataRow("f")] - [DataRow(true)] + [Test] + [TestCase(1)] + [TestCase("f")] + [TestCase(true)] public void AsArrayValue_ShouldBeLength1_GivenValue(object o) { - object[] array = o.AsArrayValue()!; - Assert.IsNotNull(array); - Assert.IsTrue(array.Length == 1); + object[] array = o.AsArrayValue(); + Assert.That(array, Is.Not.Null); + Assert.That(array, Has.Length.EqualTo(1)); } - [TestMethod] - [DataRow(1)] - [DataRow("f")] - [DataRow(true)] + [Test] + [TestCase(1)] + [TestCase("f")] + [TestCase(true)] public void AsArrayValue_ShouldContainValue_Given_Value(object o) { - object[] array = o.AsArrayValue()!; - Assert.IsNotNull(array); - Assert.AreEqual(o, array[0]); + object[] array = o.AsArrayValue(); + Assert.That(array, Is.Not.Null); + Assert.That(array[0], Is.EqualTo(o)); } - [TestMethod] - [DataRow(1)] - [DataRow("f")] - [DataRow(true)] + [Test] + [TestCase(1)] + [TestCase("f")] + [TestCase(true)] public void AsEnumerableValue_ShouldBeLength1_GivenValue(object o) { - IEnumerable enumerable = o.AsEnumerableValue()!; - Assert.IsNotNull(enumerable); - Assert.IsTrue(enumerable.Count() == 1); + object[] enumerable = o.AsEnumerableValue().ToArray(); + Assert.That(enumerable, Is.Not.Null); + Assert.That(enumerable, Has.Length.EqualTo(1)); } - [TestMethod] - [DataRow(1)] - [DataRow("f")] - [DataRow(true)] + [Test] + [TestCase(1)] + [TestCase("f")] + [TestCase(true)] public void AsEnumerableValue_ShouldContainValue_Given_Value(object o) { - IEnumerable enumerable = o.AsEnumerableValue()!; - Assert.IsNotNull(enumerable); - Assert.AreEqual(o, enumerable.ElementAt(0)); + object[] enumerable = o.AsEnumerableValue().ToArray(); + Assert.That(enumerable, Is.Not.Null); + Assert.That(enumerable.ElementAt(0), Is.EqualTo(o)); } - [TestMethod] - [DataRow(1)] - [DataRow("f")] - [DataRow(true)] + [Test] + [TestCase(1)] + [TestCase("f")] + [TestCase(true)] public void RepeatValue_ShouldContainRepeatedValue_GivenValue(object o) { IEnumerable enumerable = o.RepeatValue(10); - Assert.IsNotNull(enumerable); + // ReSharper disable once PossibleMultipleEnumeration + Assert.That(enumerable, Is.Not.Null); + // ReSharper disable once PossibleMultipleEnumeration object[] array = enumerable.ToArray(); - Assert.AreEqual(10, array.Length); + Assert.That(array, Has.Length.EqualTo(10)); CollectionAssert.AreEqual(new[] {o, o, o, o, o, o, o, o, o, o}, array); } - [TestMethod] - [DataRow(1)] - [DataRow("f")] - [DataRow(true)] + [Test] + [TestCase(1)] + [TestCase("f")] + [TestCase(true)] public void RepeatValue_ShouldThrow_GivenNegativeCount(object o) { // we must force enumeration via ToArray() to ensure the exception is thrown - Assert.ThrowsException(() => o.RepeatValue(-1).ToArray()); + Assert.Throws(() => _ = o.RepeatValue(-1).ToArray()); } } diff --git a/X10D.Tests/src/Core/EnumTests.cs b/X10D.Tests/src/Core/EnumTests.cs index a96ecc0..4469874 100644 --- a/X10D.Tests/src/Core/EnumTests.cs +++ b/X10D.Tests/src/Core/EnumTests.cs @@ -1,9 +1,9 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Core; namespace X10D.Tests.Core; -[TestClass] +[TestFixture] public class EnumTests { // Microsoft wrongfully decided to have Sunday be 0, Monday be 1, etc. @@ -12,51 +12,63 @@ public class EnumTests // but Microsoft can't fix this without breaking compatibility. // I have feelings... - [TestMethod] + [Test] public void Next() { - Assert.AreEqual(DayOfWeek.Monday, DayOfWeek.Sunday.Next()); - Assert.AreEqual(DayOfWeek.Tuesday, DayOfWeek.Monday.Next()); - Assert.AreEqual(DayOfWeek.Wednesday, DayOfWeek.Tuesday.Next()); - Assert.AreEqual(DayOfWeek.Thursday, DayOfWeek.Wednesday.Next()); - Assert.AreEqual(DayOfWeek.Friday, DayOfWeek.Thursday.Next()); - Assert.AreEqual(DayOfWeek.Saturday, DayOfWeek.Friday.Next()); - Assert.AreEqual(DayOfWeek.Sunday, DayOfWeek.Saturday.Next()); // Saturday is the "last" day. wrap to "first" + Assert.Multiple(() => + { + Assert.That(DayOfWeek.Sunday.Next(), Is.EqualTo(DayOfWeek.Monday)); + Assert.That(DayOfWeek.Monday.Next(), Is.EqualTo(DayOfWeek.Tuesday)); + Assert.That(DayOfWeek.Tuesday.Next(), Is.EqualTo(DayOfWeek.Wednesday)); + Assert.That(DayOfWeek.Wednesday.Next(), Is.EqualTo(DayOfWeek.Thursday)); + Assert.That(DayOfWeek.Thursday.Next(), Is.EqualTo(DayOfWeek.Friday)); + Assert.That(DayOfWeek.Friday.Next(), Is.EqualTo(DayOfWeek.Saturday)); + Assert.That(DayOfWeek.Saturday.Next(), Is.EqualTo(DayOfWeek.Sunday)); // Saturday is the "last" day. wrap to "first" + }); } - [TestMethod] + [Test] public void NextUnchecked() { - Assert.AreEqual(DayOfWeek.Monday, DayOfWeek.Sunday.NextUnchecked()); - Assert.AreEqual(DayOfWeek.Tuesday, DayOfWeek.Monday.NextUnchecked()); - Assert.AreEqual(DayOfWeek.Wednesday, DayOfWeek.Tuesday.NextUnchecked()); - Assert.AreEqual(DayOfWeek.Thursday, DayOfWeek.Wednesday.NextUnchecked()); - Assert.AreEqual(DayOfWeek.Friday, DayOfWeek.Thursday.NextUnchecked()); - Assert.AreEqual(DayOfWeek.Saturday, DayOfWeek.Friday.NextUnchecked()); - Assert.ThrowsException(() => DayOfWeek.Saturday.NextUnchecked()); + Assert.Multiple(() => + { + Assert.That(DayOfWeek.Sunday.NextUnchecked(), Is.EqualTo(DayOfWeek.Monday)); + Assert.That(DayOfWeek.Monday.NextUnchecked(), Is.EqualTo(DayOfWeek.Tuesday)); + Assert.That(DayOfWeek.Tuesday.NextUnchecked(), Is.EqualTo(DayOfWeek.Wednesday)); + Assert.That(DayOfWeek.Wednesday.NextUnchecked(), Is.EqualTo(DayOfWeek.Thursday)); + Assert.That(DayOfWeek.Thursday.NextUnchecked(), Is.EqualTo(DayOfWeek.Friday)); + Assert.That(DayOfWeek.Friday.NextUnchecked(), Is.EqualTo(DayOfWeek.Saturday)); + }); + Assert.Throws(() => _ = DayOfWeek.Saturday.NextUnchecked()); } - [TestMethod] + [Test] public void Previous() { - Assert.AreEqual(DayOfWeek.Saturday, DayOfWeek.Sunday.Previous()); // Sunday is the "first" day. wrap to "last" - Assert.AreEqual(DayOfWeek.Sunday, DayOfWeek.Monday.Previous()); - Assert.AreEqual(DayOfWeek.Monday, DayOfWeek.Tuesday.Previous()); - Assert.AreEqual(DayOfWeek.Tuesday, DayOfWeek.Wednesday.Previous()); - Assert.AreEqual(DayOfWeek.Wednesday, DayOfWeek.Thursday.Previous()); - Assert.AreEqual(DayOfWeek.Thursday, DayOfWeek.Friday.Previous()); - Assert.AreEqual(DayOfWeek.Friday, DayOfWeek.Saturday.Previous()); + Assert.Multiple(() => + { + Assert.That(DayOfWeek.Sunday.Previous(), Is.EqualTo(DayOfWeek.Saturday)); // Sunday is the "first" day. wrap to "last" + Assert.That(DayOfWeek.Monday.Previous(), Is.EqualTo(DayOfWeek.Sunday)); + Assert.That(DayOfWeek.Tuesday.Previous(), Is.EqualTo(DayOfWeek.Monday)); + Assert.That(DayOfWeek.Wednesday.Previous(), Is.EqualTo(DayOfWeek.Tuesday)); + Assert.That(DayOfWeek.Thursday.Previous(), Is.EqualTo(DayOfWeek.Wednesday)); + Assert.That(DayOfWeek.Friday.Previous(), Is.EqualTo(DayOfWeek.Thursday)); + Assert.That(DayOfWeek.Saturday.Previous(), Is.EqualTo(DayOfWeek.Friday)); + }); } - [TestMethod] + [Test] public void PreviousUnchecked() { - Assert.AreEqual(DayOfWeek.Sunday, DayOfWeek.Monday.PreviousUnchecked()); - Assert.AreEqual(DayOfWeek.Monday, DayOfWeek.Tuesday.PreviousUnchecked()); - Assert.AreEqual(DayOfWeek.Tuesday, DayOfWeek.Wednesday.PreviousUnchecked()); - Assert.AreEqual(DayOfWeek.Wednesday, DayOfWeek.Thursday.PreviousUnchecked()); - Assert.AreEqual(DayOfWeek.Thursday, DayOfWeek.Friday.PreviousUnchecked()); - Assert.AreEqual(DayOfWeek.Friday, DayOfWeek.Saturday.PreviousUnchecked()); - Assert.ThrowsException(() => DayOfWeek.Sunday.PreviousUnchecked()); + Assert.Multiple(() => + { + Assert.That(DayOfWeek.Monday.PreviousUnchecked(), Is.EqualTo(DayOfWeek.Sunday)); + Assert.That(DayOfWeek.Tuesday.PreviousUnchecked(), Is.EqualTo(DayOfWeek.Monday)); + Assert.That(DayOfWeek.Wednesday.PreviousUnchecked(), Is.EqualTo(DayOfWeek.Tuesday)); + Assert.That(DayOfWeek.Thursday.PreviousUnchecked(), Is.EqualTo(DayOfWeek.Wednesday)); + Assert.That(DayOfWeek.Friday.PreviousUnchecked(), Is.EqualTo(DayOfWeek.Thursday)); + Assert.That(DayOfWeek.Saturday.PreviousUnchecked(), Is.EqualTo(DayOfWeek.Friday)); + }); + Assert.Throws(() => _ = DayOfWeek.Sunday.PreviousUnchecked()); } } diff --git a/X10D.Tests/src/Core/IntrinsicTests.cs b/X10D.Tests/src/Core/IntrinsicTests.cs index c1ea98f..ecda634 100644 --- a/X10D.Tests/src/Core/IntrinsicTests.cs +++ b/X10D.Tests/src/Core/IntrinsicTests.cs @@ -1,15 +1,15 @@ #if NET6_0_OR_GREATER using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Core; namespace X10D.Tests.Core; -[TestClass] +[TestFixture] public class IntrinsicTests { - [TestMethod] + [Test] public void CorrectBoolean_ShouldReturnExpectedVector64Result_GivenInputVector() { var inputVector = Vector64.Create(0, 1, 2, 0, 3, 0, 0, (byte)4); @@ -17,10 +17,10 @@ public class IntrinsicTests Vector64 result = inputVector.CorrectBoolean(); - Assert.AreEqual(expectedResult, result); + Assert.That(result, Is.EqualTo(expectedResult)); } - [TestMethod] + [Test] public void CorrectBooleanInternal_Fallback_ShouldReturnExpectedVector128Result_GivenInputVector() { var inputVector = Vector128.Create(0, 1, 2, 0, 3, 0, 0, 4, 5, 0, 0, 6, 0, 0, 7, (byte)8); @@ -28,10 +28,10 @@ public class IntrinsicTests Vector128 result = inputVector.CorrectBooleanInternal_Fallback(); - Assert.AreEqual(expectedResult, result); + Assert.That(result, Is.EqualTo(expectedResult)); } - [TestMethod] + [Test] public void CorrectBooleanInternal_Sse2_ShouldReturnExpectedVector128Result_GivenInputVector() { if (!Sse2.IsSupported) @@ -44,10 +44,10 @@ public class IntrinsicTests Vector128 result = inputVector.CorrectBooleanInternal_Sse2(); - Assert.AreEqual(expectedResult, result); + Assert.That(result, Is.EqualTo(expectedResult)); } - [TestMethod] + [Test] public void CorrectBooleanInternal_Avx2_ShouldReturnExpectedVector256Result_GivenInputVector() { if (!Avx2.IsSupported) @@ -62,10 +62,10 @@ public class IntrinsicTests Vector256 result = inputVector.CorrectBooleanInternal_Avx2(); - Assert.AreEqual(expectedResult, result); + Assert.That(result, Is.EqualTo(expectedResult)); } - [TestMethod] + [Test] public void CorrectBooleanInternal_Fallback_ShouldReturnExpectedVector256Result_GivenInputVector() { var inputVector = Vector256.Create(0, 1, 2, 0, 3, 0, 0, 4, 5, 0, 0, 6, 0, 0, 7, 8, 0, 1, 2, 0, 3, 0, 0, 4, 5, 0, 0, 6, 0, @@ -75,10 +75,10 @@ public class IntrinsicTests Vector256 result = inputVector.CorrectBooleanInternal_Fallback(); - Assert.AreEqual(expectedResult, result); + Assert.That(result, Is.EqualTo(expectedResult)); } - [TestMethod] + [Test] public void HorizontalOr_ShouldReturnCombinedVector_GivenInputVector128OfUInt32() { Vector128 left = Vector128.Create(1U, 2U, 3U, 4U); @@ -87,10 +87,10 @@ public class IntrinsicTests Vector128 expected = Vector128.Create(3U, 7U, 7U, 15U); Vector128 actual = IntrinsicUtility.HorizontalOr(left, right); - Assert.AreEqual(expected, actual); + Assert.That(actual, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void HorizontalOrInternal_Sse_ShouldReturnCombinedVector_GivenInputVector128OfInt32() { Vector128 left = Vector128.Create(1, 2, 3, 4); @@ -99,10 +99,10 @@ public class IntrinsicTests Vector128 expected = Vector128.Create(3, 7, 7, 15); Vector128 actual = IntrinsicUtility.HorizontalOr_Sse(left, right); - Assert.AreEqual(expected, actual); + Assert.That(actual, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void HorizontalOrInternal_Fallback_ShouldReturnCombinedVector_GivenInputVector128OfInt32() { Vector128 left = Vector128.Create(1, 2, 3, 4); @@ -111,10 +111,10 @@ public class IntrinsicTests Vector128 expected = Vector128.Create(3, 7, 7, 15); Vector128 actual = IntrinsicUtility.HorizontalOrInternal_Fallback(left, right); - Assert.AreEqual(expected, actual); + Assert.That(actual, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void Multiply_ShouldReturnMultipliedVector_GivenInputVector128OfInt64() { Vector128 left = Vector128.Create(6L, 4L); @@ -123,10 +123,10 @@ public class IntrinsicTests Vector128 expected = Vector128.Create(12L, 12L); Vector128 actual = IntrinsicUtility.Multiply(left, right); - Assert.AreEqual(expected, actual); + Assert.That(actual, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void MultiplyInternal_Sse2_ShouldReturnMultipliedVector_GivenInputVector128OfUInt64() { if (!Sse2.IsSupported) @@ -140,10 +140,10 @@ public class IntrinsicTests Vector128 expected = Vector128.Create(12UL, 12UL); Vector128 actual = IntrinsicUtility.MultiplyInternal_Sse2(left, right); - Assert.AreEqual(expected, actual); + Assert.That(actual, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void MultiplyInternal_Fallback_ShouldReturnMultipliedVector_GivenInputVector128OfUInt64() { Vector128 left = Vector128.Create(6UL, 4UL); @@ -152,10 +152,10 @@ public class IntrinsicTests Vector128 expected = Vector128.Create(12UL, 12UL); Vector128 actual = IntrinsicUtility.MultiplyInternal_Fallback(left, right); - Assert.AreEqual(expected, actual); + Assert.That(actual, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void Multiply_ShouldReturnMultipliedVector_GivenInputVector256OfInt64() { Vector256 left = Vector256.Create(4L, 6L, 8L, 10L); @@ -164,10 +164,10 @@ public class IntrinsicTests Vector256 expected = Vector256.Create(8L, 18L, 32L, 50L); Vector256 actual = IntrinsicUtility.Multiply(left, right); - Assert.AreEqual(expected, actual); + Assert.That(actual, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void MultiplyInternal_Avx2_ShouldReturnMultipliedVector_GivenInputVector256OfUInt64() { if (!Avx2.IsSupported) @@ -181,10 +181,10 @@ public class IntrinsicTests Vector256 expected = Vector256.Create(8UL, 18UL, 32UL, 50UL); Vector256 actual = IntrinsicUtility.MultiplyInternal_Avx2(left, right); - Assert.AreEqual(expected, actual); + Assert.That(actual, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void MultiplyInternal_Fallback_ShouldReturnMultipliedVector_GivenInputVector256OfUInt64() { Vector256 left = Vector256.Create(4UL, 6UL, 8UL, 10UL); @@ -193,10 +193,10 @@ public class IntrinsicTests Vector256 expected = Vector256.Create(8UL, 18UL, 32UL, 50UL); Vector256 actual = IntrinsicUtility.MultiplyInternal_Fallback(left, right); - Assert.AreEqual(expected, actual); + Assert.That(actual, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void ReverseElementsInternal_Fallback_ShouldReturnExpectedVector128Result_GivenInputVector() { var inputVector = Vector128.Create(42UL, 69UL); @@ -204,10 +204,10 @@ public class IntrinsicTests Vector128 result = inputVector.ReverseElementsInternal_Fallback(); - Assert.AreEqual(expectedResult, result); + Assert.That(result, Is.EqualTo(expectedResult)); } - [TestMethod] + [Test] public void ReverseElementsInternal_Sse2_ShouldReturnExpectedVector128Result_GivenInputVector() { if (!Sse2.IsSupported) @@ -220,7 +220,7 @@ public class IntrinsicTests Vector128 result = inputVector.ReverseElementsInternal_Sse2(); - Assert.AreEqual(expectedResult, result); + Assert.That(result, Is.EqualTo(expectedResult)); } } #endif diff --git a/X10D.Tests/src/Core/NullableTests.cs b/X10D.Tests/src/Core/NullableTests.cs index eda6883..4626e9c 100644 --- a/X10D.Tests/src/Core/NullableTests.cs +++ b/X10D.Tests/src/Core/NullableTests.cs @@ -1,24 +1,30 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Core; namespace X10D.Tests.Core; -[TestClass] +[TestFixture] public class NullableTests { - [TestMethod] + [Test] public void TryGetValue_ShouldBeTrue_GivenValue() { int? value = 42; - Assert.IsTrue(value.TryGetValue(out int returnedValue)); - Assert.AreEqual(value, returnedValue); + Assert.Multiple(() => + { + Assert.That(value.TryGetValue(out int returnedValue)); + Assert.That(returnedValue, Is.EqualTo(value.Value)); + }); } - [TestMethod] + [Test] public void TryGetValue_ShouldBeFalse_GivenNull() { int? value = null; - Assert.IsFalse(value.TryGetValue(out int returnedValue)); - Assert.AreEqual(default, returnedValue); + Assert.Multiple(() => + { + Assert.That(value.TryGetValue(out int returnedValue), Is.False); + Assert.That(returnedValue, Is.Zero); + }); } } diff --git a/X10D.Tests/src/Core/RandomTests.cs b/X10D.Tests/src/Core/RandomTests.cs index 9824c01..1e7b7bd 100644 --- a/X10D.Tests/src/Core/RandomTests.cs +++ b/X10D.Tests/src/Core/RandomTests.cs @@ -1,121 +1,121 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Collections; using X10D.Core; namespace X10D.Tests.Core; -[TestClass] +[TestFixture] public class RandomTests { - [TestMethod] + [Test] public void NextBoolean_ShouldBeFalse_GivenSeed1234() { var random = new Random(1234); - Assert.IsFalse(random.NextBoolean()); + Assert.That(random.NextBoolean(), Is.False); } - [TestMethod] + [Test] public void NextBoolean_ShouldThrow_GivenNull() { - Random? random = null; - Assert.ThrowsException(() => random!.NextBoolean()); + Random random = null!; + Assert.Throws(() => random.NextBoolean()); } - [TestMethod] + [Test] public void NextByte_ShouldBe101_GivenSeed1234() { var random = new Random(1234); - Assert.AreEqual(101, random.NextByte()); + Assert.That(random.NextByte(), Is.EqualTo(101)); } - [TestMethod] + [Test] public void NextByte_WithMax10_ShouldBe3_GivenSeed1234() { var random = new Random(1234); - Assert.AreEqual(3, random.NextByte(10)); + Assert.That(random.NextByte(10), Is.EqualTo(3)); } - [TestMethod] + [Test] public void NextByte_WithMin0Max10_ShouldBe3_GivenSeed1234() { var random = new Random(1234); - Assert.AreEqual(3, random.NextByte(0, 10)); + Assert.That(random.NextByte(0, 10), Is.EqualTo(3)); } - [TestMethod] + [Test] public void NextByte_ShouldThrow_GivenNull() { Random? random = null; - Assert.ThrowsException(() => random!.NextByte()); - Assert.ThrowsException(() => random!.NextByte(10)); - Assert.ThrowsException(() => random!.NextByte(0, 10)); + Assert.Throws(() => random!.NextByte()); + Assert.Throws(() => random!.NextByte(10)); + Assert.Throws(() => random!.NextByte(0, 10)); } - [TestMethod] + [Test] public void NextDouble_WithMax10_ShouldBe3point9908097935797695_GivenSeed1234() { var random = new Random(1234); - Assert.AreEqual(3.9908097935797695, random.NextDouble(10)); + Assert.That(random.NextDouble(10), Is.EqualTo(3.9908097935797695)); } - [TestMethod] + [Test] public void NextDouble_WithMin0Max10_ShouldBe3point9908097935797695_GivenSeed1234() { var random = new Random(1234); - Assert.AreEqual(3.9908097935797695, random.NextDouble(0, 10)); + Assert.That(random.NextDouble(0, 10), Is.EqualTo(3.9908097935797695)); } - [TestMethod] + [Test] public void NextDouble_ShouldThrow_GivenNull() { Random? random = null; - Assert.ThrowsException(() => random!.NextDouble(10)); - Assert.ThrowsException(() => random!.NextDouble(0, 10)); + Assert.Throws(() => random!.NextDouble(10)); + Assert.Throws(() => random!.NextDouble(0, 10)); } - [TestMethod] + [Test] public void NextDouble_ShouldThrow_GivenMaxLessThan0() { var random = new Random(1234); - Assert.ThrowsException(() => random.NextDouble(-1)); + Assert.Throws(() => random.NextDouble(-1)); } - [TestMethod] + [Test] public void NextDouble_ShouldThrow_GivenMaxLessThanMin() { var random = new Random(1234); - Assert.ThrowsException(() => random.NextDouble(0, -1)); + Assert.Throws(() => random.NextDouble(0, -1)); } - [TestMethod] + [Test] public void NextEnum_ShouldBeTuesday_GivenSeed1234() { var random = new Random(1234); - Assert.AreEqual(DayOfWeek.Tuesday, random.Next()); + Assert.That(random.Next(), Is.EqualTo(DayOfWeek.Tuesday)); } - [TestMethod] + [Test] public void NextEnum_ShouldThrow_GivenNull() { Random? random = null; - Assert.ThrowsException(() => random!.Next()); + Assert.Throws(() => random!.Next()); } - [TestMethod] + [Test] public void NextFrom_ShouldThrow_GivenNullRandom() { Random? random = null; - Assert.ThrowsException(() => random!.NextFrom("")); + Assert.Throws(() => random!.NextFrom("")); } - [TestMethod] + [Test] public void NextFrom_ShouldThrow_GivenNullSource() { var random = new Random(1234); - Assert.ThrowsException(() => random.NextFrom((string?)null!)); + Assert.Throws(() => random.NextFrom((string?)null!)); } - [TestMethod] + [Test] public void NextFrom_ShouldEnumerate_GivenNonList() { IEnumerable Source() @@ -124,168 +124,168 @@ public class RandomTests } var random = new Random(1234); - Assert.AreEqual(0, random.NextFrom(Source())); + Assert.That(random.NextFrom(Source()), Is.Zero); } - [TestMethod] + [Test] public void NextFromSpan_ShouldThrow_GivenNullRandom() { Random? random = null; - Assert.ThrowsException(() => + Assert.Throws(() => { Span span = stackalloc int[1]; - return random!.NextFrom(span); + _ = random!.NextFrom(span); }); } - [TestMethod] + [Test] public void NextFromReadOnlySpan_ShouldThrow_GivenNullRandom() { Random? random = null; - Assert.ThrowsException(() => + Assert.Throws(() => { Span span = stackalloc int[1]; - return random!.NextFrom(span.AsReadOnly()); + _ = random!.NextFrom(span.AsReadOnly()); }); } - [TestMethod] + [Test] public void NextFromSpan_ShouldReturnOnlyValue_GivenSpanWithLength1() { Span span = stackalloc int[1]; span[0] = 42; var random = new Random(1234); - Assert.AreEqual(42, random.NextFrom(span)); + Assert.That(random.NextFrom(span), Is.EqualTo(42)); } - [TestMethod] + [Test] public void NextFromReadOnlySpan_ShouldReturnOnlyValue_GivenSpanWithLength1() { Span span = stackalloc int[1]; span[0] = 42; var random = new Random(1234); - Assert.AreEqual(42, random.NextFrom(span.AsReadOnly())); + Assert.That(random.NextFrom(span.AsReadOnly()), Is.EqualTo(42)); } - [TestMethod] + [Test] public void NextInt16_ShouldBe13076_GivenSeed1234() { var random = new Random(1234); - Assert.AreEqual(13076, random.NextInt16()); + Assert.That(random.NextInt16(), Is.EqualTo(13076)); } - [TestMethod] + [Test] public void NextInt16_WithMax10_ShouldBe3_GivenSeed1234() { var random = new Random(1234); - Assert.AreEqual(3, random.NextInt16(10)); + Assert.That(random.NextInt16(10), Is.EqualTo(3)); } - [TestMethod] + [Test] public void NextInt16_WithMin0Max10_ShouldBe3_GivenSeed1234() { var random = new Random(1234); - Assert.AreEqual(3, random.NextInt16(0, 10)); + Assert.That(random.NextInt16(0, 10), Is.EqualTo(3)); } - [TestMethod] + [Test] public void NextInt16_ShouldThrow_GivenMaxLessThan0() { var random = new Random(1234); - Assert.ThrowsException(() => random.NextInt16(-1)); + Assert.Throws(() => random.NextInt16(-1)); } - [TestMethod] + [Test] public void NextInt16_ShouldThrow_GivenNull() { Random? random = null; - Assert.ThrowsException(() => random!.NextInt16()); - Assert.ThrowsException(() => random!.NextInt16(10)); - Assert.ThrowsException(() => random!.NextInt16(0, 10)); + Assert.Throws(() => random!.NextInt16()); + Assert.Throws(() => random!.NextInt16(10)); + Assert.Throws(() => random!.NextInt16(0, 10)); } - [TestMethod] + [Test] public void NextSingle_WithMax10_ShouldBe3point99081_GivenSeed1234() { var random = new Random(1234); - Assert.AreEqual(3.99081f, random.NextSingle(10)); + Assert.That(random.NextSingle(10), Is.EqualTo(3.99081f)); } - [TestMethod] + [Test] public void NextSingle_WithMin0Max10_ShouldBe3point99081_GivenSeed1234() { var random = new Random(1234); - Assert.AreEqual(3.99081f, random.NextSingle(0, 10)); + Assert.That(random.NextSingle(0, 10), Is.EqualTo(3.99081f)); } - [TestMethod] + [Test] public void NextSingle_ShouldThrow_GivenNull() { Random? random = null; - Assert.ThrowsException(() => random!.NextSingle(10)); - Assert.ThrowsException(() => random!.NextSingle(0, 10)); + Assert.Throws(() => random!.NextSingle(10)); + Assert.Throws(() => random!.NextSingle(0, 10)); #if !NET6_0_OR_GREATER - Assert.ThrowsException(() => random!.NextSingle()); + Assert.Throws(() => random!.NextSingle()); #endif } - [TestMethod] + [Test] public void NextSingle_ShouldThrow_GivenMaxLessThan0() { var random = new Random(1234); - Assert.ThrowsException(() => random.NextSingle(-1)); + Assert.Throws(() => random.NextSingle(-1)); } - [TestMethod] + [Test] public void NextSingle_ShouldThrow_GivenMaxLessThanMin() { var random = new Random(1234); - Assert.ThrowsException(() => random.NextSingle(0, -1)); + Assert.Throws(() => random.NextSingle(0, -1)); } - [TestMethod] + [Test] public void NextString_ShouldBe_kxiyiyvnqi_GivenSeed1234() { const string alphabet = "abcdefghijklmnopqrstuvwxyz"; var random = new Random(1234); - Assert.AreEqual("kxiyiyvnqi", random.NextString(alphabet.ToCharArray(), 10)); + Assert.That(random.NextString(alphabet.ToCharArray(), 10), Is.EqualTo("kxiyiyvnqi")); } - [TestMethod] + [Test] public void NextString_ShouldBeEmpty_GivenLength0() { var random = new Random(1234); - Assert.AreEqual(string.Empty, random.NextString(ArraySegment.Empty, 0)); + Assert.That(random.NextString(ArraySegment.Empty, 0), Is.EqualTo(string.Empty)); } - [TestMethod] + [Test] public void NextString_ShouldBeLength1_GivenLength1() { var random = new Random(1234); - Assert.AreEqual(1, random.NextString("hello world".ToCharArray(), 1).Length); + Assert.That(random.NextString("hello world".ToCharArray(), 1).Length, Is.EqualTo(1)); } - [TestMethod] + [Test] public void NextString_ShouldThrow_GivenNullRandom() { Random? random = null; - Assert.ThrowsException(() => random!.NextString(ArraySegment.Empty, 0)); + Assert.Throws(() => random!.NextString(ArraySegment.Empty, 0)); } - [TestMethod] + [Test] public void NextString_ShouldThrow_GivenNullSource() { var random = new Random(1234); - Assert.ThrowsException(() => random.NextString(null!, 0)); + Assert.Throws(() => random.NextString(null!, 0)); } - [TestMethod] + [Test] public void NextString_ShouldThrow_GivenNegativeLength() { var random = new Random(1234); - Assert.ThrowsException(() => random.NextString(ArraySegment.Empty, -1)); + Assert.Throws(() => random.NextString(ArraySegment.Empty, -1)); } } diff --git a/X10D.Tests/src/Core/SpanTest.cs b/X10D.Tests/src/Core/SpanTest.cs index e242c12..6ef4f74 100644 --- a/X10D.Tests/src/Core/SpanTest.cs +++ b/X10D.Tests/src/Core/SpanTest.cs @@ -2,191 +2,203 @@ using System.Runtime.Intrinsics.Arm; using System.Runtime.Intrinsics.X86; #endif -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Core; namespace X10D.Tests.Core; -[TestClass] +[TestFixture] public class SpanTest { - [TestMethod] + [Test] public void Contains_ShouldReturnFalse_GivenReadOnlySpanWithNoMatchingElements_UsingByteEnum() { - ReadOnlySpan span = stackalloc EnumByte[1] {EnumByte.B}; - - Assert.IsFalse(span.Contains(EnumByte.A)); - Assert.IsFalse(span.Contains(EnumByte.C)); + Assert.Multiple(() => + { + ReadOnlySpan span = stackalloc EnumByte[1] {EnumByte.B}; + Assert.That(span.Contains(EnumByte.A), Is.False); + Assert.That(span.Contains(EnumByte.C), Is.False); + }); } - [TestMethod] + [Test] public void Contains_ShouldReturnFalse_GivenReadOnlySpanWithNoMatchingElements_UsingInt16Enum() { - ReadOnlySpan span = stackalloc EnumInt16[1] {EnumInt16.B}; - - Assert.IsFalse(span.Contains(EnumInt16.A)); - Assert.IsFalse(span.Contains(EnumInt16.C)); + Assert.Multiple(() => + { + ReadOnlySpan span = stackalloc EnumInt16[1] {EnumInt16.B}; + Assert.That(span.Contains(EnumInt16.A), Is.False); + Assert.That(span.Contains(EnumInt16.C), Is.False); + }); } - [TestMethod] + [Test] public void Contains_ShouldReturnFalse_GivenReadOnlySpanWithNoMatchingElements_UsingInt32Enum() { - ReadOnlySpan span = stackalloc EnumInt32[1] {EnumInt32.B}; - - Assert.IsFalse(span.Contains(EnumInt32.A)); - Assert.IsFalse(span.Contains(EnumInt32.C)); + Assert.Multiple(() => + { + ReadOnlySpan span = stackalloc EnumInt32[1] {EnumInt32.B}; + Assert.That(span.Contains(EnumInt32.A), Is.False); + Assert.That(span.Contains(EnumInt32.C), Is.False); + }); } - [TestMethod] + [Test] public void Contains_ShouldReturnFalse_GivenReadOnlySpanWithNoMatchingElements_UsingInt64Enum() { - ReadOnlySpan span = stackalloc EnumInt64[1] {EnumInt64.B}; + Assert.Multiple(() => + { + ReadOnlySpan span = stackalloc EnumInt64[1] {EnumInt64.B}; - Assert.IsFalse(span.Contains(EnumInt64.A)); - Assert.IsFalse(span.Contains(EnumInt64.C)); + Assert.That(span.Contains(EnumInt64.A), Is.False); + Assert.That(span.Contains(EnumInt64.C), Is.False); + }); } - [TestMethod] + [Test] public void Contains_ShouldReturnTrue_GivenReadOnlySpanWithMatchingElements_UsingByteEnum() { ReadOnlySpan span = stackalloc EnumByte[1] {EnumByte.B}; - Assert.IsTrue(span.Contains(EnumByte.B)); + Assert.That(span.Contains(EnumByte.B)); } - [TestMethod] + [Test] public void Contains_ShouldReturnTrue_GivenReadOnlySpanWithMatchingElements_UsingInt16Enum() { ReadOnlySpan span = stackalloc EnumInt16[1] {EnumInt16.B}; - Assert.IsTrue(span.Contains(EnumInt16.B)); + Assert.That(span.Contains(EnumInt16.B)); } - [TestMethod] + [Test] public void Contains_ShouldReturnTrue_GivenReadOnlySpanWithMatchingElements_UsingInt32Enum() { ReadOnlySpan span = stackalloc EnumInt32[1] {EnumInt32.B}; - Assert.IsTrue(span.Contains(EnumInt32.B)); + Assert.That(span.Contains(EnumInt32.B)); } - [TestMethod] + [Test] public void Contains_ShouldReturnTrue_GivenReadOnlySpanWithMatchingElements_UsingInt64Enum() { ReadOnlySpan span = stackalloc EnumInt64[1] {EnumInt64.B}; - Assert.IsTrue(span.Contains(EnumInt64.B)); + Assert.That(span.Contains(EnumInt64.B)); } - [TestMethod] + [Test] public void Contains_ShouldReturnFalse_GivenSpanWithNoMatchingElements_UsingByteEnum() { - Span span = stackalloc EnumByte[1] {EnumByte.B}; + Assert.Multiple(() => + { + Span span = stackalloc EnumByte[1] {EnumByte.B}; - Assert.IsFalse(span.Contains(EnumByte.A)); - Assert.IsFalse(span.Contains(EnumByte.C)); + Assert.That(span.Contains(EnumByte.A), Is.False); + Assert.That(span.Contains(EnumByte.C), Is.False); + }); } - [TestMethod] + [Test] public void Contains_ShouldReturnFalse_GivenSpanWithNoMatchingElements_UsingInt16Enum() { Span span = stackalloc EnumInt16[1] {EnumInt16.B}; - Assert.IsFalse(span.Contains(EnumInt16.A)); - Assert.IsFalse(span.Contains(EnumInt16.C)); + Assert.That(span.Contains(EnumInt16.A), Is.False); + Assert.That(span.Contains(EnumInt16.C), Is.False); } - [TestMethod] + [Test] public void Contains_ShouldReturnFalse_GivenSpanWithNoMatchingElements_UsingInt32Enum() { Span span = stackalloc EnumInt32[1] {EnumInt32.B}; - Assert.IsFalse(span.Contains(EnumInt32.A)); - Assert.IsFalse(span.Contains(EnumInt32.C)); + Assert.That(span.Contains(EnumInt32.A), Is.False); + Assert.That(span.Contains(EnumInt32.C), Is.False); } - [TestMethod] + [Test] public void Contains_ShouldReturnFalse_GivenSpanWithNoMatchingElements_UsingInt64Enum() { Span span = stackalloc EnumInt64[1] {EnumInt64.B}; - Assert.IsFalse(span.Contains(EnumInt64.A)); - Assert.IsFalse(span.Contains(EnumInt64.C)); + Assert.That(span.Contains(EnumInt64.A), Is.False); + Assert.That(span.Contains(EnumInt64.C), Is.False); } - [TestMethod] + [Test] public void Contains_ShouldReturnTrue_GivenSpanWithMatchingElements_UsingByteEnum() { Span span = stackalloc EnumByte[1] {EnumByte.B}; - Assert.IsTrue(span.Contains(EnumByte.B)); + Assert.That(span.Contains(EnumByte.B)); } - [TestMethod] + [Test] public void Contains_ShouldReturnTrue_GivenSpanWithMatchingElements_UsingInt16Enum() { Span span = stackalloc EnumInt16[1] {EnumInt16.B}; - Assert.IsTrue(span.Contains(EnumInt16.B)); + Assert.That(span.Contains(EnumInt16.B)); } - [TestMethod] + [Test] public void Contains_ShouldReturnTrue_GivenSpanWithMatchingElements_UsingInt32Enum() { Span span = stackalloc EnumInt32[1] {EnumInt32.B}; - Assert.IsTrue(span.Contains(EnumInt32.B)); + Assert.That(span.Contains(EnumInt32.B)); } - [TestMethod] + [Test] public void Contains_ShouldReturnTrue_GivenSpanWithMatchingElements_UsingInt64Enum() { Span span = stackalloc EnumInt64[1] {EnumInt64.B}; - Assert.IsTrue(span.Contains(EnumInt64.B)); + Assert.That(span.Contains(EnumInt64.B)); } - [TestMethod] + [Test] public void PackByte_ShouldThrowArgumentException_GivenSpanLengthGreaterThan8() { - Assert.ThrowsException(() => + Assert.Throws(() => { Span span = stackalloc bool[9]; - return span.PackByte(); + _ = span.PackByte(); }); } - [TestMethod] + [Test] public void PackInt16_ShouldThrowArgumentException_GivenSpanLengthGreaterThan16() { - Assert.ThrowsException(() => + Assert.Throws(() => { Span span = stackalloc bool[17]; - return span.PackInt16(); + _ = span.PackInt16(); }); } - [TestMethod] + [Test] public void PackInt32_ShouldThrowArgumentException_GivenSpanLengthGreaterThan32() { - Assert.ThrowsException(() => + Assert.Throws(() => { Span span = stackalloc bool[33]; - return span.PackInt32(); + _ = span.PackInt32(); }); } - [TestMethod] + [Test] public void PackInt64_ShouldThrowArgumentException_GivenSpanLengthGreaterThan64() { - Assert.ThrowsException(() => + Assert.Throws(() => { Span span = stackalloc bool[65]; - return span.PackInt64(); + _ = span.PackInt64(); }); } - [TestMethod] + [Test] public void PackByteInternal_Fallback_ShouldReturnCorrectByte_GivenReadOnlySpan_Using() { const byte expected = 0b00110011; @@ -194,11 +206,11 @@ public class SpanTest byte actual = span.PackByteInternal_Fallback(); - Assert.AreEqual(expected, actual); + Assert.That(actual, Is.EqualTo(expected)); } #if NET5_0_OR_GREATER - [TestMethod] + [Test] public void PackByteInternal_Sse2_ShouldReturnCorrectByte_GivenReadOnlySpan_Using() { if (!Sse2.IsSupported) @@ -211,10 +223,10 @@ public class SpanTest byte actual = span.PackByteInternal_Sse2(); - Assert.AreEqual(expected, actual); + Assert.That(actual, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void PackByteInternal_AdvSimd_ShouldReturnCorrectByte_GivenReadOnlySpan_Using() { if (!AdvSimd.IsSupported) @@ -227,11 +239,11 @@ public class SpanTest byte actual = span.PackByteInternal_AdvSimd(); - Assert.AreEqual(expected, actual); + Assert.That(actual, Is.EqualTo(expected)); } #endif - [TestMethod] + [Test] public void PackInt16_ShouldReturnSameAsPackByte_WhenSpanHasLength8() { ReadOnlySpan span = stackalloc bool[8] {true, true, false, false, true, true, false, false}; @@ -239,10 +251,10 @@ public class SpanTest short expected = span.PackByte(); short actual = span.PackInt16(); - Assert.AreEqual(expected, actual); + Assert.That(actual, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void PackInt16Internal_Fallback_ShouldReturnCorrectInt16_GivenReadOnlySpan() { const short expected = 0b00101101_11010100; @@ -253,11 +265,11 @@ public class SpanTest short actual = span.PackInt16Internal_Fallback(); - Assert.AreEqual(expected, actual); + Assert.That(actual, Is.EqualTo(expected)); } #if NET5_0_OR_GREATER - [TestMethod] + [Test] public void PackInt16Internal_Sse2_ShouldReturnCorrectInt16_GivenReadOnlySpan_Using() { if (!Sse2.IsSupported) @@ -273,11 +285,11 @@ public class SpanTest short actual = span.PackInt16Internal_Sse2(); - Assert.AreEqual(expected, actual); + Assert.That(actual, Is.EqualTo(expected)); } #endif - [TestMethod] + [Test] public void PackInt32Internal_Fallback_ShouldReturnCorrectInt32_GivenReadOnlySpan() { const int expected = 0b01010101_10101010_01010101_10101010; @@ -289,11 +301,11 @@ public class SpanTest int actual = span.PackInt32Internal_Fallback(); - Assert.AreEqual(expected, actual); + Assert.That(actual, Is.EqualTo(expected)); } #if NET5_0_OR_GREATER - [TestMethod] + [Test] public void PackInt32Internal_Sse2_ShouldReturnCorrectInt32_GivenReadOnlySpan() { if (!Sse2.IsSupported) @@ -310,10 +322,10 @@ public class SpanTest int actual = span.PackInt32Internal_Sse2(); - Assert.AreEqual(expected, actual); + Assert.That(actual, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void PackInt32Internal_Avx2_ShouldReturnCorrectInt32_GivenReadOnlySpan() { if (!Avx2.IsSupported) @@ -330,10 +342,10 @@ public class SpanTest int actual = span.PackInt32Internal_Avx2(); - Assert.AreEqual(expected, actual); + Assert.That(actual, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void PackInt32Internal_AdvSimd_ShouldReturnCorrectInt32_GivenReadOnlySpan() { if (!AdvSimd.IsSupported) @@ -350,11 +362,11 @@ public class SpanTest int actual = span.PackInt32Internal_AdvSimd(); - Assert.AreEqual(expected, actual); + Assert.That(actual, Is.EqualTo(expected)); } #endif - [TestMethod] + [Test] public void PackInt32_ShouldReturnSameAsPackByte_WhenSpanHasLength8_UsingReadOnlySpan() { ReadOnlySpan span = stackalloc bool[8] {true, true, false, false, true, true, false, false}; @@ -362,10 +374,10 @@ public class SpanTest int expected = span.PackByte(); int actual = span.PackInt32(); - Assert.AreEqual(expected, actual); + Assert.That(actual, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void PackInt32_ShouldReturnSameAsPackByte_WhenSpanHasLength8_UsingSpan() { Span span = stackalloc bool[8] {true, true, false, false, true, true, false, false}; @@ -373,10 +385,10 @@ public class SpanTest int expected = span.PackByte(); int actual = span.PackInt32(); - Assert.AreEqual(expected, actual); + Assert.That(actual, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void PackInt32_ShouldReturnSameAsPackInt16_WhenSpanHasLength16_UsingReadOnlySpan() { ReadOnlySpan span = stackalloc bool[16] @@ -387,10 +399,10 @@ public class SpanTest int expected = span.PackInt16(); int actual = span.PackInt32(); - Assert.AreEqual(expected, actual); + Assert.That(actual, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void PackInt32_ShouldReturnSameAsPackInt16_WhenSpanHasLength16_UsingSpan() { Span span = stackalloc bool[16] @@ -401,10 +413,10 @@ public class SpanTest int expected = span.PackInt16(); int actual = span.PackInt32(); - Assert.AreEqual(expected, actual); + Assert.That(actual, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void PackInt64_ShouldReturnCorrectInt64_GivenReadOnlySpan() { const long expected = 0b01010101_11010110_01101001_11010110_00010010_10010111_00101100_10100101; @@ -418,10 +430,10 @@ public class SpanTest long actual = span.PackInt64(); - Assert.AreEqual(expected, actual); + Assert.That(actual, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void PackInt64_ShouldReturnCorrectInt64_GivenSpan() { const long expected = 0b01010101_11010110_01101001_11010110_00010010_10010111_00101100_10100101; @@ -435,10 +447,10 @@ public class SpanTest long actual = span.PackInt64(); - Assert.AreEqual(expected, actual); + Assert.That(actual, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void PackInt64_ShouldReturnSameAsPackByte_WhenSpanHasLength8_UsingReadOnlySpan() { ReadOnlySpan span = stackalloc bool[8] {true, true, false, false, true, true, false, false}; @@ -446,10 +458,10 @@ public class SpanTest long expected = span.PackByte(); long actual = span.PackInt64(); - Assert.AreEqual(expected, actual); + Assert.That(actual, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void PackInt64_ShouldReturnSameAsPackByte_WhenSpanHasLength8_UsingSpan() { Span span = stackalloc bool[8] {true, true, false, false, true, true, false, false}; @@ -457,10 +469,10 @@ public class SpanTest long expected = span.PackByte(); long actual = span.PackInt64(); - Assert.AreEqual(expected, actual); + Assert.That(actual, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void PackInt64_ShouldReturnSameAsPackInt16_WhenSpanHasLength16_UsingReadOnlySpan() { ReadOnlySpan span = stackalloc bool[16] @@ -471,10 +483,10 @@ public class SpanTest long expected = span.PackInt16(); long actual = span.PackInt64(); - Assert.AreEqual(expected, actual); + Assert.That(actual, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void PackInt64_ShouldReturnSameAsPackInt16_WhenSpanHasLength16_UsingSpan() { Span span = stackalloc bool[16] @@ -485,10 +497,10 @@ public class SpanTest long expected = span.PackInt16(); long actual = span.PackInt64(); - Assert.AreEqual(expected, actual); + Assert.That(actual, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void PackInt64_ShouldReturnSameAsPackInt32_WhenSpanHasLength16_UsingReadOnlySpan() { ReadOnlySpan span = stackalloc bool[32] @@ -500,10 +512,10 @@ public class SpanTest long expected = span.PackInt32(); long actual = span.PackInt64(); - Assert.AreEqual(expected, actual); + Assert.That(actual, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void PackInt64_ShouldReturnSameAsPackInt32_WhenSpanHasLength16_UsingSpan() { Span span = stackalloc bool[32] @@ -515,10 +527,10 @@ public class SpanTest long expected = span.PackInt32(); long actual = span.PackInt64(); - Assert.AreEqual(expected, actual); + Assert.That(actual, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void PackInt64_ShouldFallbackAndReturnCorrectValue_GivenNonPowerOfTwoLength_UsingReadOnlySpan() { const long expected = 0b00000000_00000000_00000000_00000000_00000000_00000000_00000001_01010011; @@ -526,10 +538,10 @@ public class SpanTest long actual = span.PackInt64(); - Assert.AreEqual(expected, actual); + Assert.That(actual, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void PackInt64_ShouldFallbackAndReturnCorrectValue_GivenNonPowerOfTwoLength_UsingSpan() { const long expected = 0b00000000_00000000_00000000_00000000_00000000_00000000_00000001_01010011; @@ -537,7 +549,7 @@ public class SpanTest long actual = span.PackInt64(); - Assert.AreEqual(expected, actual); + Assert.That(actual, Is.EqualTo(expected)); } private enum EnumByte : byte diff --git a/X10D.Tests/src/Drawing/CircleFTests.cs b/X10D.Tests/src/Drawing/CircleFTests.cs index d8e8256..67221e9 100644 --- a/X10D.Tests/src/Drawing/CircleFTests.cs +++ b/X10D.Tests/src/Drawing/CircleFTests.cs @@ -1,167 +1,181 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Drawing; +using NUnit.Framework; using X10D.Drawing; namespace X10D.Tests.Drawing; -[TestClass] +[TestFixture] public class CircleFTests { - [TestMethod] + [Test] public void Area_ShouldBePiRadiusRadius_GivenUnitCircle() { var unitCircle = CircleF.Unit; - Assert.AreEqual(MathF.PI, unitCircle.Area); + Assert.That(unitCircle.Area, Is.EqualTo(MathF.PI)); } - [TestMethod] + [Test] public void Circumference_ShouldBe2PiRadius_GivenUnitCircle() { var unitCircle = CircleF.Unit; - Assert.AreEqual(2 * MathF.PI, unitCircle.Circumference, 1e-6f); + Assert.That(unitCircle.Circumference, Is.EqualTo(2 * MathF.PI).Within(1e-6f)); } - [TestMethod] + [Test] public void CompareTo_ShouldBeNegativeOne_GivenUnitCircleAndEmpty() { - Assert.AreEqual(-1, CircleF.Empty.CompareTo(CircleF.Unit)); + Assert.That(CircleF.Empty.CompareTo(CircleF.Unit), Is.EqualTo(-1)); } - [TestMethod] + [Test] public void CompareTo_ShouldBeOne_GivenUnitCircleAndEmpty() { - Assert.AreEqual(1, CircleF.Unit.CompareTo(CircleF.Empty)); + Assert.That(CircleF.Unit.CompareTo(CircleF.Empty), Is.EqualTo(1)); } - [TestMethod] + [Test] public void CompareTo_ShouldBeNegativeOne_GivenEmptyCircleAndUnitCircleAsObject() { - Assert.AreEqual(-1, CircleF.Empty.CompareTo((object)CircleF.Unit)); + Assert.That(CircleF.Empty.CompareTo((object)CircleF.Unit), Is.EqualTo(-1)); } - [TestMethod] + [Test] public void CompareTo_ShouldBeOne_GivenNull() { - Assert.AreEqual(1, CircleF.Unit.CompareTo(null)); + Assert.That(CircleF.Unit.CompareTo(null), Is.EqualTo(1)); } - [TestMethod] + [Test] public void CompareTo_ShouldBeZero_GivenUnitCircle() { var unitCircle = CircleF.Unit; - Assert.AreEqual(0, unitCircle.CompareTo(unitCircle)); + Assert.That(unitCircle.CompareTo(unitCircle), Is.Zero); } - [TestMethod] + [Test] public void CompareTo_ShouldThrowArgumentException_GivenInvalidType() { - Assert.ThrowsException(() => CircleF.Unit.CompareTo(new object())); + Assert.Throws(() => _ = CircleF.Unit.CompareTo(new object())); } - [TestMethod] + [Test] public void Diameter_ShouldBe2_GivenUnitCircle() { - Assert.AreEqual(2.0f, CircleF.Unit.Diameter, 1e-6f); + Assert.That(CircleF.Unit.Diameter, Is.EqualTo(2.0f).Within(1e-6f)); } - [TestMethod] + [Test] public void Equals_ShouldBeTrue_GivenTwoUnitCircles() { var unitCircle1 = CircleF.Unit; var unitCircle2 = CircleF.Unit; - Assert.AreEqual(unitCircle1, unitCircle2); - Assert.IsTrue(unitCircle1 == unitCircle2); - Assert.IsFalse(unitCircle1 != unitCircle2); + Assert.Multiple(() => + { + Assert.That(unitCircle2, Is.EqualTo(unitCircle1)); + Assert.That(unitCircle1, Is.EqualTo(unitCircle2)); + Assert.That(unitCircle1 == unitCircle2); + Assert.That(unitCircle2 == unitCircle1); + }); } - [TestMethod] + [Test] public void Equals_ShouldBeTrue_GivenUnitCirclesAsObjects() { CircleF unitCircle1 = CircleF.Unit; object unitCircle2 = CircleF.Unit; - Assert.AreEqual(unitCircle1, unitCircle2); - Assert.IsTrue(unitCircle1.Equals(unitCircle2)); + Assert.Multiple(() => + { + Assert.That(unitCircle2, Is.EqualTo(unitCircle1)); + Assert.That(unitCircle1, Is.EqualTo(unitCircle2)); + }); } - [TestMethod] + [Test] public void Equals_ShouldBeFalse_GivenDifferentCircles() { - Assert.AreNotEqual(CircleF.Unit, CircleF.Empty); - Assert.IsFalse(CircleF.Unit == CircleF.Empty); - Assert.IsTrue(CircleF.Unit != CircleF.Empty); + Assert.Multiple(() => + { + Assert.That(CircleF.Empty, Is.Not.EqualTo(CircleF.Unit)); + Assert.That(CircleF.Unit, Is.Not.EqualTo(CircleF.Empty)); + }); } - [TestMethod] + [Test] public void Equals_ShouldBeFalse_GivenDifferentObjects() { - Assert.AreNotEqual((object?)null, CircleF.Empty); - Assert.IsFalse(CircleF.Empty.Equals(null)); + Assert.That(CircleF.Empty, Is.Not.EqualTo(null)); } - [TestMethod] + [Test] public void GetHashCode_ShouldBeCorrect_GivenEmptyCircle() { // this test is pretty pointless, it exists only for code coverage purposes int hashCode = CircleF.Empty.GetHashCode(); - Assert.AreEqual(hashCode, CircleF.Empty.GetHashCode()); + Assert.That(CircleF.Empty.GetHashCode(), Is.EqualTo(hashCode)); } - [TestMethod] + [Test] public void GetHashCode_ShouldBeCorrect_GivenUnitCircle() { // this test is pretty pointless, it exists only for code coverage purposes int hashCode = CircleF.Unit.GetHashCode(); - Assert.AreEqual(hashCode, CircleF.Unit.GetHashCode()); + Assert.That(CircleF.Unit.GetHashCode(), Is.EqualTo(hashCode)); } - [TestMethod] + [Test] public void op_Explicit_ShouldReturnEquivalentCircle_GivenCircle() { CircleF unitCircle = CircleF.Unit; Circle converted = (Circle)unitCircle; - Assert.AreEqual(unitCircle, converted); - Assert.AreEqual(unitCircle.Radius, converted.Radius); - Assert.AreEqual(unitCircle.Center, converted.Center); + Assert.Multiple(() => + { + Assert.That(converted, Is.EqualTo((Circle)unitCircle)); + Assert.That(converted.Radius, Is.EqualTo(unitCircle.Radius)); + Assert.That((PointF)converted.Center, Is.EqualTo(unitCircle.Center)); + }); } - [TestMethod] + [Test] public void op_GreaterThan_True_GivenUnitAndEmptyCircle() { - Assert.IsTrue(CircleF.Unit > CircleF.Empty); - Assert.IsTrue(CircleF.Unit >= CircleF.Empty); - Assert.IsFalse(CircleF.Unit < CircleF.Empty); - Assert.IsFalse(CircleF.Unit <= CircleF.Empty); + Assert.That(CircleF.Unit, Is.GreaterThan(CircleF.Empty)); + Assert.That(CircleF.Unit, Is.GreaterThanOrEqualTo(CircleF.Empty)); } - [TestMethod] + [Test] public void op_Implicit_ShouldReturnEquivalentCircle_GivenCircle() { Circle unitCircle = Circle.Unit; CircleF converted = unitCircle; - Assert.AreEqual(unitCircle, converted); - Assert.AreEqual(unitCircle.Radius, converted.Radius); - Assert.AreEqual(unitCircle.Center, converted.Center); + Assert.Multiple(() => + { + Assert.That(converted, Is.EqualTo((CircleF)unitCircle)); + Assert.That(converted.Radius, Is.EqualTo(unitCircle.Radius)); + Assert.That(converted.Center, Is.EqualTo((PointF)unitCircle.Center)); + }); } - [TestMethod] + [Test] public void op_LessThan_True_GivenEmptyAndUnitCircle() { - Assert.IsTrue(CircleF.Empty < CircleF.Unit); - Assert.IsTrue(CircleF.Empty <= CircleF.Unit); - Assert.IsFalse(CircleF.Empty > CircleF.Unit); - Assert.IsFalse(CircleF.Empty >= CircleF.Unit); + Assert.Multiple(() => + { + Assert.That(CircleF.Empty, Is.LessThan(CircleF.Unit)); + Assert.That(CircleF.Empty, Is.LessThanOrEqualTo(CircleF.Unit)); + }); } - [TestMethod] + [Test] public void Radius_ShouldBe0_GivenEmptyCircle() { - Assert.AreEqual(0.0f, CircleF.Empty.Radius, 1e-6f); + Assert.That(CircleF.Empty.Radius, Is.EqualTo(0.0f).Within(1e-6f)); } - [TestMethod] + [Test] public void Radius_ShouldBe1_GivenUnitCircle() { - Assert.AreEqual(1.0f, CircleF.Unit.Radius, 1e-6f); + Assert.That(CircleF.Unit.Radius, Is.EqualTo(1.0f).Within(1e-6f)); } } diff --git a/X10D.Tests/src/Drawing/CircleTests.cs b/X10D.Tests/src/Drawing/CircleTests.cs index 3151299..3fbfc46 100644 --- a/X10D.Tests/src/Drawing/CircleTests.cs +++ b/X10D.Tests/src/Drawing/CircleTests.cs @@ -1,145 +1,147 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Drawing; namespace X10D.Tests.Drawing; -[TestClass] +[TestFixture] public class CircleTests { - [TestMethod] + [Test] public void Area_ShouldBePiRadiusRadius_GivenUnitCircle() { var unitCircle = Circle.Unit; - Assert.AreEqual(MathF.PI * unitCircle.Radius * unitCircle.Radius, unitCircle.Area); + Assert.That(unitCircle.Area, Is.EqualTo(MathF.PI * unitCircle.Radius * unitCircle.Radius)); } - [TestMethod] + [Test] public void Circumference_ShouldBe2PiRadius_GivenUnitCircle() { var unitCircle = Circle.Unit; - Assert.AreEqual(2.0f * MathF.PI * unitCircle.Radius, unitCircle.Circumference, 1e-6f); + Assert.That(unitCircle.Circumference, Is.EqualTo(2.0f * MathF.PI * unitCircle.Radius).Within(1e-6f)); } - [TestMethod] + [Test] public void CompareTo_ShouldBeNegativeOne_GivenUnitCircleAndEmpty() { - Assert.AreEqual(-1, Circle.Empty.CompareTo(Circle.Unit)); + Assert.That(Circle.Empty.CompareTo(Circle.Unit), Is.EqualTo(-1)); } - [TestMethod] + [Test] public void CompareTo_ShouldBeOne_GivenUnitCircleAndEmpty() { - Assert.AreEqual(1, Circle.Unit.CompareTo(Circle.Empty)); + Assert.That(Circle.Unit.CompareTo(Circle.Empty), Is.EqualTo(1)); } - [TestMethod] + [Test] public void CompareTo_ShouldBeNegativeOne_GivenEmptyCircleAndUnitCircleAsObject() { - Assert.AreEqual(-1, Circle.Empty.CompareTo((object)Circle.Unit)); + Assert.That(Circle.Empty.CompareTo((object)Circle.Unit), Is.EqualTo(-1)); } - [TestMethod] + [Test] public void CompareTo_ShouldBeOne_GivenNull() { - Assert.AreEqual(1, Circle.Unit.CompareTo(null)); + Assert.That(Circle.Unit.CompareTo(null), Is.EqualTo(1)); } - [TestMethod] + [Test] public void CompareTo_ShouldBeZero_GivenUnitCircle() { var unitCircle = Circle.Unit; - Assert.AreEqual(0, unitCircle.CompareTo(unitCircle)); + Assert.That(unitCircle.CompareTo(unitCircle), Is.Zero); } - [TestMethod] + [Test] public void CompareTo_ShouldThrowArgumentException_GivenInvalidType() { - Assert.ThrowsException(() => Circle.Unit.CompareTo(new object())); + Assert.Throws(() => _ = Circle.Unit.CompareTo(new object())); } - [TestMethod] + [Test] public void Diameter_ShouldBe2_GivenUnitCircle() { - Assert.AreEqual(2.0f, Circle.Unit.Diameter, 1e-6f); + Assert.That(Circle.Unit.Diameter, Is.EqualTo(2.0f).Within(1e-6f)); } - [TestMethod] + [Test] public void Equals_ShouldBeTrue_GivenTwoUnitCircles() { var unitCircle1 = Circle.Unit; var unitCircle2 = Circle.Unit; - Assert.AreEqual(unitCircle1, unitCircle2); - Assert.IsTrue(unitCircle1 == unitCircle2); - Assert.IsFalse(unitCircle1 != unitCircle2); + Assert.Multiple(() => + { + Assert.That(unitCircle2, Is.EqualTo(unitCircle1)); + Assert.That(unitCircle1, Is.EqualTo(unitCircle2)); + }); } - [TestMethod] + [Test] public void Equals_ShouldBeTrue_GivenUnitCirclesAsObjects() { Circle unitCircle1 = Circle.Unit; object unitCircle2 = Circle.Unit; - Assert.AreEqual(unitCircle1, unitCircle2); - Assert.IsTrue(unitCircle1.Equals(unitCircle2)); + Assert.Multiple(() => + { + Assert.That(unitCircle2, Is.EqualTo(unitCircle1)); + Assert.That(unitCircle1, Is.EqualTo(unitCircle2)); + }); } - [TestMethod] + [Test] public void Equals_ShouldBeFalse_GivenDifferentCircles() { - Assert.AreNotEqual(Circle.Unit, Circle.Empty); - Assert.IsFalse(Circle.Unit == Circle.Empty); - Assert.IsTrue(Circle.Unit != Circle.Empty); + Assert.Multiple(() => + { + Assert.That(Circle.Empty, Is.Not.EqualTo(Circle.Unit)); + Assert.That(Circle.Unit, Is.Not.EqualTo(Circle.Empty)); + }); } - [TestMethod] + [Test] public void Equals_ShouldBeFalse_GivenDifferentObjects() { - Assert.AreNotEqual((object?)null, Circle.Empty); - Assert.IsFalse(Circle.Empty.Equals(null)); + Assert.That(Circle.Empty, Is.Not.EqualTo(null)); } - [TestMethod] + [Test] public void GetHashCode_ShouldBeCorrect_GivenEmptyCircle() { // this test is pretty pointless, it exists only for code coverage purposes int hashCode = Circle.Empty.GetHashCode(); - Assert.AreEqual(hashCode, Circle.Empty.GetHashCode()); + Assert.That(Circle.Empty.GetHashCode(), Is.EqualTo(hashCode)); } - [TestMethod] + [Test] public void GetHashCode_ShouldBeCorrect_GivenUnitCircle() { // this test is pretty pointless, it exists only for code coverage purposes int hashCode = Circle.Unit.GetHashCode(); - Assert.AreEqual(hashCode, Circle.Unit.GetHashCode()); + Assert.That(Circle.Unit.GetHashCode(), Is.EqualTo(hashCode)); } - [TestMethod] + [Test] public void op_GreaterThan_True_GivenUnitAndEmptyCircle() { - Assert.IsTrue(Circle.Unit > Circle.Empty); - Assert.IsTrue(Circle.Unit >= Circle.Empty); - Assert.IsFalse(Circle.Unit < Circle.Empty); - Assert.IsFalse(Circle.Unit <= Circle.Empty); + Assert.That(Circle.Unit, Is.GreaterThan(Circle.Empty)); + Assert.That(Circle.Unit, Is.GreaterThanOrEqualTo(Circle.Empty)); } - [TestMethod] + [Test] public void op_LessThan_True_GivenEmptyAndUnitCircle() { - Assert.IsTrue(Circle.Empty < Circle.Unit); - Assert.IsTrue(Circle.Empty <= Circle.Unit); - Assert.IsFalse(Circle.Empty > Circle.Unit); - Assert.IsFalse(Circle.Empty >= Circle.Unit); + Assert.That(Circle.Empty, Is.LessThan(Circle.Unit)); + Assert.That(Circle.Empty, Is.LessThanOrEqualTo(Circle.Unit)); } - [TestMethod] + [Test] public void Radius_ShouldBe0_GivenEmptyCircle() { - Assert.AreEqual(0, Circle.Empty.Radius); + Assert.That(Circle.Empty.Radius, Is.Zero); } - [TestMethod] + [Test] public void Radius_ShouldBe1_GivenUnitCircle() { - Assert.AreEqual(1, Circle.Unit.Radius); + Assert.That(Circle.Unit.Radius, Is.EqualTo(1)); } } diff --git a/X10D.Tests/src/Drawing/ColorTests.cs b/X10D.Tests/src/Drawing/ColorTests.cs index a7ecec9..ad29fb3 100644 --- a/X10D.Tests/src/Drawing/ColorTests.cs +++ b/X10D.Tests/src/Drawing/ColorTests.cs @@ -1,10 +1,10 @@ using System.Drawing; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Drawing; namespace X10D.Tests.Drawing; -[TestClass] +[TestFixture] public class ColorTests { private static readonly Color Black = Color.FromArgb(0, 0, 0); @@ -16,251 +16,278 @@ public class ColorTests private static readonly Color Magenta = Color.FromArgb(255, 0, 255); private static readonly Color Yellow = Color.FromArgb(255, 255, 0); - [TestMethod] + [Test] public void Deconstruct_ShouldDeconstructColor_GivenColor() { (byte r, byte g, byte b) = Black; - Assert.AreEqual(0, r); - Assert.AreEqual(0, g); - Assert.AreEqual(0, b); + Assert.Multiple(() => + { + Assert.That(r, Is.Zero); + Assert.That(g, Is.Zero); + Assert.That(b, Is.Zero); + }); (byte a, r, g, b) = Black; - Assert.AreEqual(255, a); - Assert.AreEqual(0, r); - Assert.AreEqual(0, g); - Assert.AreEqual(0, b); + Assert.Multiple(() => + { + Assert.That(a, Is.EqualTo(255)); + Assert.That(r, Is.Zero); + Assert.That(g, Is.Zero); + Assert.That(b, Is.Zero); + }); (r, g, b) = Red; - Assert.AreEqual(255, r); - Assert.AreEqual(0, g); - Assert.AreEqual(0, b); + Assert.Multiple(() => + { + Assert.That(r, Is.EqualTo(255)); + Assert.That(g, Is.Zero); + Assert.That(b, Is.Zero); + }); (a, r, g, b) = Red; - Assert.AreEqual(255, a); - Assert.AreEqual(255, r); - Assert.AreEqual(0, g); - Assert.AreEqual(0, b); + Assert.Multiple(() => + { + Assert.That(a, Is.EqualTo(255)); + Assert.That(r, Is.EqualTo(255)); + Assert.That(g, Is.Zero); + Assert.That(b, Is.Zero); + }); (r, g, b) = Green; - Assert.AreEqual(0, r); - Assert.AreEqual(255, g); - Assert.AreEqual(0, b); + Assert.Multiple(() => + { + Assert.That(r, Is.Zero); + Assert.That(g, Is.EqualTo(255)); + Assert.That(b, Is.Zero); + }); (a, r, g, b) = Green; - Assert.AreEqual(255, a); - Assert.AreEqual(0, r); - Assert.AreEqual(255, g); - Assert.AreEqual(0, b); + Assert.Multiple(() => + { + Assert.That(a, Is.EqualTo(255)); + Assert.That(r, Is.Zero); + Assert.That(g, Is.EqualTo(255)); + Assert.That(b, Is.Zero); + }); (r, g, b) = Blue; - Assert.AreEqual(0, r); - Assert.AreEqual(0, g); - Assert.AreEqual(255, b); + Assert.Multiple(() => + { + Assert.That(r, Is.Zero); + Assert.That(g, Is.Zero); + Assert.That(b, Is.EqualTo(255)); + }); (a, r, g, b) = Blue; - Assert.AreEqual(255, a); - Assert.AreEqual(0, r); - Assert.AreEqual(0, g); - Assert.AreEqual(255, b); + Assert.Multiple(() => + { + Assert.That(a, Is.EqualTo(255)); + Assert.That(r, Is.Zero); + Assert.That(g, Is.Zero); + Assert.That(b, Is.EqualTo(255)); + }); } - [TestMethod] + [Test] public void GetClosestConsoleColor_ShouldReturnClosestColor_GivenValidColor() { - Assert.AreEqual(ConsoleColor.White, Color.Transparent.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.White, Color.AliceBlue.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.White, Color.AntiqueWhite.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Cyan, Color.Aqua.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkGray, Color.Aquamarine.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.White, Color.Azure.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.White, Color.Beige.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.White, Color.Bisque.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Black, Color.Black.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.White, Color.BlanchedAlmond.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Blue, Color.Blue.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkMagenta, Color.BlueViolet.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkRed, Color.Brown.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkGray, Color.BurlyWood.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Gray, Color.CadetBlue.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Yellow, Color.Chartreuse.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkYellow, Color.Chocolate.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkYellow, Color.Coral.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkGray, Color.CornflowerBlue.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.White, Color.Cornsilk.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Red, Color.Crimson.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Cyan, Color.Cyan.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkBlue, Color.DarkBlue.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkCyan, Color.DarkCyan.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkYellow, Color.DarkGoldenrod.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkGray, Color.DarkGray.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkGreen, Color.DarkGreen.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkGray, Color.DarkKhaki.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkMagenta, Color.DarkMagenta.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Gray, Color.DarkOliveGreen.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkYellow, Color.DarkOrange.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkMagenta, Color.DarkOrchid.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkRed, Color.DarkRed.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkGray, Color.DarkSalmon.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkGray, Color.DarkSeaGreen.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Gray, Color.DarkSlateBlue.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkGreen, Color.DarkSlateGray.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Cyan, Color.DarkTurquoise.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkMagenta, Color.DarkViolet.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Magenta, Color.DeepPink.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Cyan, Color.DeepSkyBlue.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Gray, Color.DimGray.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Cyan, Color.DodgerBlue.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkRed, Color.Firebrick.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.White, Color.FloralWhite.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Green, Color.ForestGreen.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Magenta, Color.Fuchsia.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.White, Color.Gainsboro.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.White, Color.GhostWhite.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Yellow, Color.Gold.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkYellow, Color.Goldenrod.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Gray, Color.Gray.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Green, Color.Green.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Yellow, Color.GreenYellow.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.White, Color.Honeydew.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkGray, Color.HotPink.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Gray, Color.IndianRed.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkMagenta, Color.Indigo.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.White, Color.Ivory.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkGray, Color.Khaki.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.White, Color.Lavender.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.White, Color.LavenderBlush.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Yellow, Color.LawnGreen.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.White, Color.LemonChiffon.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkGray, Color.LightBlue.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkGray, Color.LightCoral.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.White, Color.LightCyan.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.White, Color.LightGoldenrodYellow.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkGray, Color.LightGreen.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkGray, Color.LightGray.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkGray, Color.LightPink.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkGray, Color.LightSalmon.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkCyan, Color.LightSeaGreen.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkGray, Color.LightSkyBlue.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Gray, Color.LightSlateGray.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkGray, Color.LightSteelBlue.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.White, Color.LightYellow.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Green, Color.Lime.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Green, Color.LimeGreen.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.White, Color.Linen.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Magenta, Color.Magenta.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkRed, Color.Maroon.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkGray, Color.MediumAquamarine.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Blue, Color.MediumBlue.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkGray, Color.MediumOrchid.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkGray, Color.MediumPurple.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkCyan, Color.MediumSeaGreen.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkGray, Color.MediumSlateBlue.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Cyan, Color.MediumSpringGreen.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Cyan, Color.MediumTurquoise.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkMagenta, Color.MediumVioletRed.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkBlue, Color.MidnightBlue.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.White, Color.MintCream.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.White, Color.MistyRose.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.White, Color.Moccasin.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.White, Color.NavajoWhite.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkBlue, Color.Navy.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.White, Color.OldLace.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Gray, Color.Olive.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Gray, Color.OliveDrab.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkYellow, Color.Orange.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Red, Color.OrangeRed.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkGray, Color.Orchid.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.White, Color.PaleGoldenrod.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkGray, Color.PaleGreen.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.White, Color.PaleTurquoise.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkGray, Color.PaleVioletRed.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.White, Color.PapayaWhip.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.White, Color.PeachPuff.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkYellow, Color.Peru.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.White, Color.Pink.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkGray, Color.Plum.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkGray, Color.PowderBlue.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkMagenta, Color.Purple.GetClosestConsoleColor()); + Assert.Multiple(() => + { + Assert.That(Color.Transparent.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); + Assert.That(Color.AliceBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); + Assert.That(Color.AntiqueWhite.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); + Assert.That(Color.Aqua.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Cyan)); + Assert.That(Color.Aquamarine.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); + Assert.That(Color.Azure.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); + Assert.That(Color.Beige.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); + Assert.That(Color.Bisque.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); + Assert.That(Color.Black.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Black)); + Assert.That(Color.BlanchedAlmond.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); + Assert.That(Color.Blue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Blue)); + Assert.That(Color.BlueViolet.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkMagenta)); + Assert.That(Color.Brown.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkRed)); + Assert.That(Color.BurlyWood.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); + Assert.That(Color.CadetBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Gray)); + Assert.That(Color.Chartreuse.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Yellow)); + Assert.That(Color.Chocolate.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkYellow)); + Assert.That(Color.Coral.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkYellow)); + Assert.That(Color.CornflowerBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); + Assert.That(Color.Cornsilk.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); + Assert.That(Color.Crimson.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Red)); + Assert.That(Color.Cyan.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Cyan)); + Assert.That(Color.DarkBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkBlue)); + Assert.That(Color.DarkCyan.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkCyan)); + Assert.That(Color.DarkGoldenrod.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkYellow)); + Assert.That(Color.DarkGray.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); + Assert.That(Color.DarkGreen.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGreen)); + Assert.That(Color.DarkKhaki.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); + Assert.That(Color.DarkMagenta.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkMagenta)); + Assert.That(Color.DarkOliveGreen.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Gray)); + Assert.That(Color.DarkOrange.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkYellow)); + Assert.That(Color.DarkOrchid.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkMagenta)); + Assert.That(Color.DarkRed.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkRed)); + Assert.That(Color.DarkSalmon.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); + Assert.That(Color.DarkSeaGreen.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); + Assert.That(Color.DarkSlateBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Gray)); + Assert.That(Color.DarkSlateGray.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGreen)); + Assert.That(Color.DarkTurquoise.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Cyan)); + Assert.That(Color.DarkViolet.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkMagenta)); + Assert.That(Color.DeepPink.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Magenta)); + Assert.That(Color.DeepSkyBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Cyan)); + Assert.That(Color.DimGray.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Gray)); + Assert.That(Color.DodgerBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Cyan)); + Assert.That(Color.Firebrick.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkRed)); + Assert.That(Color.FloralWhite.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); + Assert.That(Color.ForestGreen.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Green)); + Assert.That(Color.Fuchsia.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Magenta)); + Assert.That(Color.Gainsboro.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); + Assert.That(Color.GhostWhite.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); + Assert.That(Color.Gold.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Yellow)); + Assert.That(Color.Goldenrod.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkYellow)); + Assert.That(Color.Gray.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Gray)); + Assert.That(Color.Green.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Green)); + Assert.That(Color.GreenYellow.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Yellow)); + Assert.That(Color.Honeydew.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); + Assert.That(Color.HotPink.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); + Assert.That(Color.IndianRed.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Gray)); + Assert.That(Color.Indigo.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkMagenta)); + Assert.That(Color.Ivory.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); + Assert.That(Color.Khaki.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); + Assert.That(Color.Lavender.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); + Assert.That(Color.LavenderBlush.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); + Assert.That(Color.LawnGreen.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Yellow)); + Assert.That(Color.LemonChiffon.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); + Assert.That(Color.LightBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); + Assert.That(Color.LightCoral.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); + Assert.That(Color.LightCyan.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); + Assert.That(Color.LightGoldenrodYellow.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); + Assert.That(Color.LightGreen.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); + Assert.That(Color.LightGray.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); + Assert.That(Color.LightPink.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); + Assert.That(Color.LightSalmon.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); + Assert.That(Color.LightSeaGreen.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkCyan)); + Assert.That(Color.LightSkyBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); + Assert.That(Color.LightSlateGray.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Gray)); + Assert.That(Color.LightSteelBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); + Assert.That(Color.LightYellow.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); + Assert.That(Color.Lime.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Green)); + Assert.That(Color.LimeGreen.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Green)); + Assert.That(Color.Linen.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); + Assert.That(Color.Magenta.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Magenta)); + Assert.That(Color.Maroon.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkRed)); + Assert.That(Color.MediumAquamarine.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); + Assert.That(Color.MediumBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Blue)); + Assert.That(Color.MediumOrchid.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); + Assert.That(Color.MediumPurple.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); + Assert.That(Color.MediumSeaGreen.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkCyan)); + Assert.That(Color.MediumSlateBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); + Assert.That(Color.MediumSpringGreen.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Cyan)); + Assert.That(Color.MediumTurquoise.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Cyan)); + Assert.That(Color.MediumVioletRed.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkMagenta)); + Assert.That(Color.MidnightBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkBlue)); + Assert.That(Color.MintCream.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); + Assert.That(Color.MistyRose.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); + Assert.That(Color.Moccasin.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); + Assert.That(Color.NavajoWhite.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); + Assert.That(Color.Navy.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkBlue)); + Assert.That(Color.OldLace.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); + Assert.That(Color.Olive.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Gray)); + Assert.That(Color.OliveDrab.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Gray)); + Assert.That(Color.Orange.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkYellow)); + Assert.That(Color.OrangeRed.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Red)); + Assert.That(Color.Orchid.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); + Assert.That(Color.PaleGoldenrod.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); + Assert.That(Color.PaleGreen.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); + Assert.That(Color.PaleTurquoise.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); + Assert.That(Color.PaleVioletRed.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); + Assert.That(Color.PapayaWhip.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); + Assert.That(Color.PeachPuff.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); + Assert.That(Color.Peru.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkYellow)); + Assert.That(Color.Pink.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); + Assert.That(Color.Plum.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); + Assert.That(Color.PowderBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); + Assert.That(Color.Purple.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkMagenta)); #if NET6_0_OR_GREATER - Assert.AreEqual(ConsoleColor.DarkMagenta, Color.RebeccaPurple.GetClosestConsoleColor()); + Assert.That(Color.RebeccaPurple.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkMagenta)); #endif - Assert.AreEqual(ConsoleColor.Red, Color.Red.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkGray, Color.RosyBrown.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkCyan, Color.RoyalBlue.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkRed, Color.SaddleBrown.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkGray, Color.Salmon.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkYellow, Color.SandyBrown.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkCyan, Color.SeaGreen.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.White, Color.SeaShell.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkRed, Color.Sienna.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkGray, Color.Silver.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkGray, Color.SkyBlue.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Gray, Color.SlateBlue.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Gray, Color.SlateGray.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.White, Color.Snow.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkCyan, Color.SpringGreen.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Gray, Color.SteelBlue.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkGray, Color.Tan.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkCyan, Color.Teal.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkGray, Color.Thistle.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkYellow, Color.Tomato.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Cyan, Color.Turquoise.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.DarkGray, Color.Violet.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.White, Color.Wheat.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.White, Color.White.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.White, Color.WhiteSmoke.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Yellow, Color.Yellow.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Gray, Color.YellowGreen.GetClosestConsoleColor()); + Assert.That(Color.Red.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Red)); + Assert.That(Color.RosyBrown.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); + Assert.That(Color.RoyalBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkCyan)); + Assert.That(Color.SaddleBrown.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkRed)); + Assert.That(Color.Salmon.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); + Assert.That(Color.SandyBrown.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkYellow)); + Assert.That(Color.SeaGreen.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkCyan)); + Assert.That(Color.SeaShell.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); + Assert.That(Color.Sienna.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkRed)); + Assert.That(Color.Silver.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); + Assert.That(Color.SkyBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); + Assert.That(Color.SlateBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Gray)); + Assert.That(Color.SlateGray.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Gray)); + Assert.That(Color.Snow.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); + Assert.That(Color.SpringGreen.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkCyan)); + Assert.That(Color.SteelBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Gray)); + Assert.That(Color.Tan.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); + Assert.That(Color.Teal.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkCyan)); + Assert.That(Color.Thistle.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); + Assert.That(Color.Tomato.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkYellow)); + Assert.That(Color.Turquoise.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Cyan)); + Assert.That(Color.Violet.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); + Assert.That(Color.Wheat.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); + Assert.That(Color.White.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); + Assert.That(Color.WhiteSmoke.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); + Assert.That(Color.Yellow.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Yellow)); + Assert.That(Color.YellowGreen.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Gray)); + }); } - [TestMethod] + [Test] public void Inverted_ShouldReturnInvertedColor() { - Assert.AreEqual(White, Black.Inverted()); - Assert.AreEqual(Black, White.Inverted()); - Assert.AreEqual(Red, Cyan.Inverted()); - Assert.AreEqual(Cyan, Red.Inverted()); - Assert.AreEqual(Green, Magenta.Inverted()); - Assert.AreEqual(Magenta, Green.Inverted()); - Assert.AreEqual(Yellow, Blue.Inverted()); - Assert.AreEqual(Blue, Yellow.Inverted()); + Assert.That(Black.Inverted(), Is.EqualTo(White)); + Assert.That(White.Inverted(), Is.EqualTo(Black)); + Assert.That(Cyan.Inverted(), Is.EqualTo(Red)); + Assert.That(Red.Inverted(), Is.EqualTo(Cyan)); + Assert.That(Magenta.Inverted(), Is.EqualTo(Green)); + Assert.That(Green.Inverted(), Is.EqualTo(Magenta)); + Assert.That(Blue.Inverted(), Is.EqualTo(Yellow)); + Assert.That(Yellow.Inverted(), Is.EqualTo(Blue)); } - [TestMethod] + [Test] public void Inverted_ShouldIgnoreAlpha() { Color expected = Color.FromArgb(255, 0, 0, 0); Color actual = Color.FromArgb(255, 255, 255, 255).Inverted(); - Assert.AreEqual(expected, actual); + Assert.That(actual, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void WithA0_ShouldReturnSameColor_GivenWhite() { Color transparent = Color.FromArgb(0, 255, 255, 255); - Assert.AreEqual(transparent, White.WithA(0)); - Assert.AreEqual(transparent, transparent.WithA(0)); + Assert.That(White.WithA(0), Is.EqualTo(transparent)); + Assert.That(transparent.WithA(0), Is.EqualTo(transparent)); } - [TestMethod] + [Test] public void WithB0_ShouldReturnYellow_GivenWhite() { - Assert.AreEqual(Yellow, White.WithB(0)); - Assert.AreEqual(Yellow, Yellow.WithB(0)); + Assert.That(White.WithB(0), Is.EqualTo(Yellow)); + Assert.That(Yellow.WithB(0), Is.EqualTo(Yellow)); } - [TestMethod] + [Test] public void WithG0_ShouldReturnMagenta_GivenWhite() { - Assert.AreEqual(Magenta, White.WithG(0)); - Assert.AreEqual(Magenta, Magenta.WithG(0)); + Assert.That(White.WithG(0), Is.EqualTo(Magenta)); + Assert.That(Magenta.WithG(0), Is.EqualTo(Magenta)); } - [TestMethod] + [Test] public void WithR0_ShouldReturnCyan_GivenWhite() { - Assert.AreEqual(Cyan, White.WithR(0)); - Assert.AreEqual(Cyan, Cyan.WithR(0)); + Assert.That(White.WithR(0), Is.EqualTo(Cyan)); + Assert.That(Cyan.WithR(0), Is.EqualTo(Cyan)); } } diff --git a/X10D.Tests/src/Drawing/CuboidTests.cs b/X10D.Tests/src/Drawing/CuboidTests.cs index 451a02b..c687dcb 100644 --- a/X10D.Tests/src/Drawing/CuboidTests.cs +++ b/X10D.Tests/src/Drawing/CuboidTests.cs @@ -1,82 +1,79 @@ using System.Numerics; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Drawing; namespace X10D.Tests.Drawing; -[TestClass] +[TestFixture] public class CuboidTests { - [TestMethod] + [Test] public void Corners_ShouldBeCorrect_GivenCubeOfSize1() { Cuboid cube = Cuboid.Cube; - Assert.AreEqual(new Vector3(0.5f, 0.5f, -0.5f), cube.FrontTopRight); - Assert.AreEqual(new Vector3(-0.5f, 0.5f, -0.5f), cube.FrontTopLeft); - Assert.AreEqual(new Vector3(0.5f, -0.5f, -0.5f), cube.FrontBottomRight); - Assert.AreEqual(new Vector3(-0.5f, -0.5f, -0.5f), cube.FrontBottomLeft); - Assert.AreEqual(new Vector3(0.5f, 0.5f, 0.5f), cube.BackTopRight); - Assert.AreEqual(new Vector3(-0.5f, 0.5f, 0.5f), cube.BackTopLeft); - Assert.AreEqual(new Vector3(0.5f, -0.5f, 0.5f), cube.BackBottomRight); - Assert.AreEqual(new Vector3(-0.5f, -0.5f, 0.5f), cube.BackBottomLeft); + Assert.That(cube.FrontTopRight, Is.EqualTo(new Vector3(0.5f, 0.5f, -0.5f))); + Assert.That(cube.FrontTopLeft, Is.EqualTo(new Vector3(-0.5f, 0.5f, -0.5f))); + Assert.That(cube.FrontBottomRight, Is.EqualTo(new Vector3(0.5f, -0.5f, -0.5f))); + Assert.That(cube.FrontBottomLeft, Is.EqualTo(new Vector3(-0.5f, -0.5f, -0.5f))); + Assert.That(cube.BackTopRight, Is.EqualTo(new Vector3(0.5f, 0.5f, 0.5f))); + Assert.That(cube.BackTopLeft, Is.EqualTo(new Vector3(-0.5f, 0.5f, 0.5f))); + Assert.That(cube.BackBottomRight, Is.EqualTo(new Vector3(0.5f, -0.5f, 0.5f))); + Assert.That(cube.BackBottomLeft, Is.EqualTo(new Vector3(-0.5f, -0.5f, 0.5f))); } - [TestMethod] + [Test] public void Equals_ShouldBeTrue_GivenTwoCubesOfSize1() { var cube1 = Cuboid.Cube; var cube2 = Cuboid.Cube; - Assert.AreEqual(cube1, cube2); - Assert.IsTrue(cube1 == cube2); - Assert.IsFalse(cube1 != cube2); + Assert.That(cube1, Is.EqualTo(cube2)); + Assert.That(cube2, Is.EqualTo(cube1)); } - [TestMethod] + [Test] public void Equals_ShouldBeFalse_GivenDifferentCubes() { - Assert.AreNotEqual(Cuboid.Cube, Cuboid.Empty); - Assert.IsFalse(Cuboid.Cube == Cuboid.Empty); - Assert.IsTrue(Cuboid.Cube != Cuboid.Empty); + Assert.That(Cuboid.Empty, Is.Not.EqualTo(Cuboid.Cube)); } - [TestMethod] + [Test] public void Equals_ShouldBeFalse_GivenDifferentObjects() { - Assert.IsFalse(Cuboid.Cube.Equals(null)); + Assert.That(Cuboid.Cube.Equals(null), Is.False); } - [TestMethod] + [Test] public void GetHashCode_ShouldBeCorrect_GivenEmptyCircle() { // this test is pretty pointless, it exists only for code coverage purposes int hashCode = Cuboid.Empty.GetHashCode(); - Assert.AreEqual(hashCode, Cuboid.Empty.GetHashCode()); + Assert.That(Cuboid.Empty.GetHashCode(), Is.EqualTo(hashCode)); } - [TestMethod] + [Test] public void GetHashCode_ShouldBeCorrect_GivenCubeOfSize1() { // this test is pretty pointless, it exists only for code coverage purposes int hashCode = Cuboid.Cube.GetHashCode(); - Assert.AreEqual(hashCode, Cuboid.Cube.GetHashCode()); + Assert.That(Cuboid.Cube.GetHashCode(), Is.EqualTo(hashCode)); } - [TestMethod] + [Test] public void Size_ShouldBeOne_GivenCubeOfSize1() { - Assert.AreEqual(Vector3.One, Cuboid.Cube.Size); + Assert.That(Cuboid.Cube.Size, Is.EqualTo(Vector3.One)); } - [TestMethod] + [Test] public void Size_ShouldBeOne_GivenRotatedCube() { - Assert.AreEqual(Vector3.One, new Cuboid(0, 0, 0, 1, 1, 1, 90, 0, 0).Size); + Assert.That(new Cuboid(0, 0, 0, 1, 1, 1, 90, 0, 0).Size, Is.EqualTo(Vector3.One)); } - [TestMethod] + [Test] public void Volume_ShouldBe1_GivenCubeOfSize1() { - Assert.AreEqual(1.0f, Cuboid.Cube.Volume, 1e-6f); + Assert.That(Cuboid.Cube.Volume, Is.EqualTo(1.0f).Within(1e-6f)); } } diff --git a/X10D.Tests/src/Drawing/EllipseFTests.cs b/X10D.Tests/src/Drawing/EllipseFTests.cs index 97b5af5..a7fdd03 100644 --- a/X10D.Tests/src/Drawing/EllipseFTests.cs +++ b/X10D.Tests/src/Drawing/EllipseFTests.cs @@ -1,156 +1,165 @@ using System.Drawing; using System.Numerics; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Drawing; namespace X10D.Tests.Drawing; -[TestClass] +[TestFixture] public class EllipseFTests { - [TestMethod] + [Test] public void Area_ShouldBePiRadiusRadius_GivenUnitEllipse() { var unitEllipse = EllipseF.Unit; - Assert.AreEqual(MathF.PI, unitEllipse.Area, 1e-6f); + Assert.That(unitEllipse.Area, Is.EqualTo(MathF.PI).Within(1e-6f)); } - [TestMethod] + [Test] public void ApproximateCircumference_ShouldBe2PiRadius_GivenUnitEllipse() { var unitEllipse = EllipseF.Unit; - Assert.AreEqual(2 * MathF.PI, unitEllipse.ApproximateCircumference, 1e-6f); + Assert.That(unitEllipse.ApproximateCircumference, Is.EqualTo(2 * MathF.PI).Within(1e-6f)); } - [TestMethod] + [Test] public void Constructor_ShouldGiveCorrectEllipse() { var ellipse = new EllipseF(PointF.Empty, new SizeF(2, 1)); - Assert.AreEqual(new PointF(0, 0), ellipse.Center); - Assert.AreEqual(new SizeF(2, 1), ellipse.Radius); + Assert.That(ellipse.Center, Is.EqualTo(new PointF(0, 0))); + Assert.That(ellipse.Radius, Is.EqualTo(new SizeF(2, 1))); ellipse = new EllipseF(0, 0, 2, 1); - Assert.AreEqual(new PointF(0, 0), ellipse.Center); - Assert.AreEqual(new SizeF(2, 1), ellipse.Radius); + Assert.That(ellipse.Center, Is.EqualTo(new PointF(0, 0))); + Assert.That(ellipse.Radius, Is.EqualTo(new SizeF(2, 1))); ellipse = new EllipseF(PointF.Empty, new Vector2(2, 1)); - Assert.AreEqual(new PointF(0, 0), ellipse.Center); - Assert.AreEqual(new SizeF(2, 1), ellipse.Radius); + Assert.That(ellipse.Center, Is.EqualTo(new PointF(0, 0))); + Assert.That(ellipse.Radius, Is.EqualTo(new SizeF(2, 1))); ellipse = new EllipseF(Vector2.Zero, new Vector2(2, 1)); - Assert.AreEqual(new PointF(0, 0), ellipse.Center); - Assert.AreEqual(new SizeF(2, 1), ellipse.Radius); + Assert.That(ellipse.Center, Is.EqualTo(new PointF(0, 0))); + Assert.That(ellipse.Radius, Is.EqualTo(new SizeF(2, 1))); } - [TestMethod] + [Test] public void Equals_ShouldBeTrue_GivenTwoUnitEllipses() { var unitEllipse1 = EllipseF.Unit; var unitEllipse2 = EllipseF.Unit; - Assert.AreEqual(unitEllipse1, unitEllipse2); - Assert.IsTrue(unitEllipse1 == unitEllipse2); - Assert.IsFalse(unitEllipse1 != unitEllipse2); + Assert.That(unitEllipse2, Is.EqualTo(unitEllipse1)); + Assert.That(unitEllipse1, Is.EqualTo(unitEllipse2)); } - [TestMethod] + [Test] public void Equals_ShouldBeFalse_GivenDifferentEllipses() { - Assert.AreNotEqual(EllipseF.Unit, EllipseF.Empty); - Assert.IsFalse(EllipseF.Unit == EllipseF.Empty); - Assert.IsTrue(EllipseF.Unit != EllipseF.Empty); + Assert.That(EllipseF.Empty, Is.Not.EqualTo(EllipseF.Unit)); } - [TestMethod] + [Test] public void Equals_ShouldBeFalse_GivenDifferentObjects() { - Assert.IsFalse(EllipseF.Unit.Equals(null)); + Assert.That(EllipseF.Unit, Is.Not.EqualTo(null)); } - [TestMethod] + [Test] public void GetHashCode_ShouldBeCorrect_GivenEmptyEllipse() { // this test is pretty pointless, it exists only for code coverage purposes int hashCode = EllipseF.Empty.GetHashCode(); - Assert.AreEqual(hashCode, EllipseF.Empty.GetHashCode()); + Assert.That(EllipseF.Empty.GetHashCode(), Is.EqualTo(hashCode)); } - [TestMethod] + [Test] public void GetHashCode_ShouldBeCorrect_GivenUnitEllipse() { // this test is pretty pointless, it exists only for code coverage purposes int hashCode = EllipseF.Unit.GetHashCode(); - Assert.AreEqual(hashCode, EllipseF.Unit.GetHashCode()); + Assert.That(EllipseF.Unit.GetHashCode(), Is.EqualTo(hashCode)); } - [TestMethod] + [Test] public void HorizontalRadius_ShouldBe0_GivenEmptyEllipse() { - Assert.AreEqual(0, EllipseF.Empty.HorizontalRadius); + Assert.That(EllipseF.Empty.HorizontalRadius, Is.Zero); } - [TestMethod] + [Test] public void HorizontalRadius_ShouldBe1_GivenUnitEllipse() { - Assert.AreEqual(1, EllipseF.Unit.HorizontalRadius); + Assert.That(EllipseF.Unit.HorizontalRadius, Is.EqualTo(1)); } - [TestMethod] + [Test] public void op_Explicit_ShouldReturnEquivalentEllipse_GivenEllipse() { EllipseF unitEllipse = EllipseF.Unit; Ellipse converted = (Ellipse)unitEllipse; - Assert.AreEqual(unitEllipse, converted); - Assert.AreEqual(unitEllipse.HorizontalRadius, converted.HorizontalRadius); - Assert.AreEqual(unitEllipse.VerticalRadius, converted.VerticalRadius); - Assert.AreEqual(unitEllipse.Center, converted.Center); + Assert.Multiple(() => + { + Assert.That(converted, Is.EqualTo((Ellipse)unitEllipse)); + Assert.That(converted.HorizontalRadius, Is.EqualTo(unitEllipse.HorizontalRadius)); + Assert.That(converted.VerticalRadius, Is.EqualTo(unitEllipse.VerticalRadius)); + Assert.That((PointF)converted.Center, Is.EqualTo(unitEllipse.Center)); + }); } - [TestMethod] + [Test] public void op_Implicit_ShouldReturnEquivalentEllipse_GivenCircle() { Circle unitCircle = Circle.Unit; EllipseF converted = unitCircle; - Assert.AreEqual(unitCircle, converted); - Assert.AreEqual(unitCircle.Radius, converted.HorizontalRadius); - Assert.AreEqual(unitCircle.Radius, converted.VerticalRadius); - Assert.AreEqual(unitCircle.Center, converted.Center); + Assert.Multiple(() => + { + Assert.That(converted, Is.EqualTo((EllipseF)unitCircle)); + Assert.That(converted.HorizontalRadius, Is.EqualTo(unitCircle.Radius)); + Assert.That(converted.VerticalRadius, Is.EqualTo(unitCircle.Radius)); + Assert.That(converted.Center, Is.EqualTo((PointF)unitCircle.Center)); + }); } - [TestMethod] + [Test] public void op_Implicit_ShouldReturnEquivalentEllipse_GivenCircleF() { CircleF unitCircle = CircleF.Unit; EllipseF converted = unitCircle; - Assert.AreEqual(unitCircle, converted); - Assert.AreEqual(unitCircle.Radius, converted.HorizontalRadius); - Assert.AreEqual(unitCircle.Radius, converted.VerticalRadius); - Assert.AreEqual(unitCircle.Center, converted.Center); + Assert.Multiple(() => + { + Assert.That(converted, Is.EqualTo((EllipseF)unitCircle)); + Assert.That(converted.HorizontalRadius, Is.EqualTo(unitCircle.Radius)); + Assert.That(converted.VerticalRadius, Is.EqualTo(unitCircle.Radius)); + Assert.That(converted.Center, Is.EqualTo(unitCircle.Center)); + }); } - [TestMethod] + [Test] public void op_Implicit_ShouldReturnEquivalentEllipse_GivenEllipse() { Ellipse unitEllipse = Ellipse.Unit; EllipseF converted = unitEllipse; - Assert.AreEqual(unitEllipse, converted); - Assert.AreEqual(unitEllipse.HorizontalRadius, converted.HorizontalRadius); - Assert.AreEqual(unitEllipse.VerticalRadius, converted.VerticalRadius); - Assert.AreEqual(unitEllipse.Center, converted.Center); + Assert.Multiple(() => + { + Assert.That(converted, Is.EqualTo((EllipseF)unitEllipse)); + Assert.That(converted.HorizontalRadius, Is.EqualTo(unitEllipse.HorizontalRadius)); + Assert.That(converted.VerticalRadius, Is.EqualTo(unitEllipse.VerticalRadius)); + Assert.That(converted.Center, Is.EqualTo((PointF)unitEllipse.Center)); + }); } - [TestMethod] + [Test] public void VerticalRadius_ShouldBe0_GivenEmptyEllipse() { - Assert.AreEqual(0, EllipseF.Empty.VerticalRadius); + Assert.That(EllipseF.Empty.VerticalRadius, Is.Zero); } - [TestMethod] + [Test] public void VerticalRadius_ShouldBe1_GivenUnitEllipse() { - Assert.AreEqual(1, EllipseF.Unit.VerticalRadius); + Assert.That(EllipseF.Unit.VerticalRadius, Is.EqualTo(1)); } } diff --git a/X10D.Tests/src/Drawing/EllipseTests.cs b/X10D.Tests/src/Drawing/EllipseTests.cs index c5482a3..b740d28 100644 --- a/X10D.Tests/src/Drawing/EllipseTests.cs +++ b/X10D.Tests/src/Drawing/EllipseTests.cs @@ -1,111 +1,124 @@ using System.Drawing; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Drawing; namespace X10D.Tests.Drawing; -[TestClass] +[TestFixture] public class EllipseTests { - [TestMethod] + [Test] public void Area_ShouldBePiRadiusRadius_GivenUnitEllipse() { var unitEllipse = Ellipse.Unit; - Assert.AreEqual(MathF.PI, unitEllipse.Area, 1e-6f); + Assert.That(unitEllipse.Area, Is.EqualTo(MathF.PI).Within(1e-6f)); } - [TestMethod] + [Test] public void ApproximateCircumference_ShouldBe2PiRadius_GivenUnitEllipse() { var unitEllipse = Ellipse.Unit; - Assert.AreEqual(2 * MathF.PI, unitEllipse.ApproximateCircumference, 1e-6f); + Assert.That(unitEllipse.ApproximateCircumference, Is.EqualTo(2.0f * MathF.PI).Within(1e-6f)); } - [TestMethod] + [Test] public void Constructor_ShouldGiveCorrectEllipse() { var ellipse = new Ellipse(Point.Empty, new Size(2, 1)); - Assert.AreEqual(new Point(0, 0), ellipse.Center); - Assert.AreEqual(new Size(2, 1), ellipse.Radius); + Assert.Multiple(() => + { + Assert.That(ellipse.Center, Is.EqualTo(new Point(0, 0))); + Assert.That(ellipse.Radius, Is.EqualTo(new Size(2, 1))); + }); ellipse = new Ellipse(0, 0, 2, 1); - Assert.AreEqual(new Point(0, 0), ellipse.Center); - Assert.AreEqual(new Size(2, 1), ellipse.Radius); + Assert.Multiple(() => + { + Assert.That(ellipse.Center, Is.EqualTo(new Point(0, 0))); + Assert.That(ellipse.Radius, Is.EqualTo(new Size(2, 1))); + }); } - [TestMethod] + [Test] public void Equals_ShouldBeTrue_GivenTwoUnitEllipses() { var unitEllipse1 = Ellipse.Unit; var unitEllipse2 = Ellipse.Unit; - Assert.AreEqual(unitEllipse1, unitEllipse2); - Assert.IsTrue(unitEllipse1 == unitEllipse2); - Assert.IsFalse(unitEllipse1 != unitEllipse2); + Assert.Multiple(() => + { + Assert.That(unitEllipse2, Is.EqualTo(unitEllipse1)); + Assert.That(unitEllipse1, Is.EqualTo(unitEllipse2)); + }); } - [TestMethod] + [Test] public void Equals_ShouldBeFalse_GivenDifferentEllipses() { - Assert.AreNotEqual(Ellipse.Unit, Ellipse.Empty); - Assert.IsFalse(Ellipse.Unit == Ellipse.Empty); - Assert.IsTrue(Ellipse.Unit != Ellipse.Empty); + Assert.Multiple(() => + { + Assert.That(Ellipse.Empty, Is.Not.EqualTo(Ellipse.Unit)); + Assert.That(Ellipse.Unit, Is.Not.EqualTo(Ellipse.Empty)); + }); } - [TestMethod] + [Test] public void Equals_ShouldBeFalse_GivenDifferentObjects() { - Assert.IsFalse(Ellipse.Unit.Equals(null)); + Assert.That(Ellipse.Unit.Equals(null), Is.False); } - [TestMethod] + [Test] public void GetHashCode_ShouldBeCorrect_GivenEmptyEllipse() { // this test is pretty pointless, it exists only for code coverage purposes int hashCode = Ellipse.Empty.GetHashCode(); - Assert.AreEqual(hashCode, Ellipse.Empty.GetHashCode()); + Assert.That(Ellipse.Empty.GetHashCode(), Is.EqualTo(hashCode)); } - [TestMethod] + [Test] public void GetHashCode_ShouldBeCorrect_GivenUnitEllipse() { // this test is pretty pointless, it exists only for code coverage purposes int hashCode = Ellipse.Unit.GetHashCode(); - Assert.AreEqual(hashCode, Ellipse.Unit.GetHashCode()); + Assert.That(Ellipse.Unit.GetHashCode(), Is.EqualTo(hashCode)); } - [TestMethod] + [Test] public void HorizontalRadius_ShouldBe0_GivenEmptyEllipse() { - Assert.AreEqual(0, Ellipse.Empty.HorizontalRadius); + Assert.That(Ellipse.Empty.HorizontalRadius, Is.Zero); } - [TestMethod] + [Test] public void HorizontalRadius_ShouldBe1_GivenUnitEllipse() { - Assert.AreEqual(1, Ellipse.Unit.HorizontalRadius); + Assert.That(Ellipse.Unit.HorizontalRadius, Is.EqualTo(1)); } - [TestMethod] + [Test] public void op_Implicit_ShouldReturnEquivalentEllipse_GivenCircle() { Circle unitCircle = Circle.Unit; Ellipse converted = unitCircle; - Assert.AreEqual(unitCircle, converted); - Assert.AreEqual(unitCircle.Radius, converted.HorizontalRadius); - Assert.AreEqual(unitCircle.Radius, converted.VerticalRadius); - Assert.AreEqual(unitCircle.Center, converted.Center); + Assert.Multiple(() => + { + Assert.That(converted, Is.EqualTo((Ellipse)unitCircle)); + Assert.That(converted.HorizontalRadius, Is.EqualTo(unitCircle.Radius)); + Assert.That(converted.VerticalRadius, Is.EqualTo(unitCircle.Radius)); + Assert.That(converted.Center, Is.EqualTo(unitCircle.Center)); + }); } - [TestMethod] + [Test] public void VerticalRadius_ShouldBe0_GivenEmptyEllipse() { - Assert.AreEqual(0, Ellipse.Empty.VerticalRadius); + Assert.That(Ellipse.Empty.VerticalRadius, Is.Zero); } - [TestMethod] + [Test] public void VerticalRadius_ShouldBe1_GivenUnitEllipse() { - Assert.AreEqual(1, Ellipse.Unit.VerticalRadius); + Assert.That(Ellipse.Unit.VerticalRadius, Is.EqualTo(1)); } } diff --git a/X10D.Tests/src/Drawing/Line3DTests.cs b/X10D.Tests/src/Drawing/Line3DTests.cs index 8cbc7cf..f001b00 100644 --- a/X10D.Tests/src/Drawing/Line3DTests.cs +++ b/X10D.Tests/src/Drawing/Line3DTests.cs @@ -1,116 +1,112 @@ using System.Drawing; using System.Numerics; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Drawing; namespace X10D.Tests.Drawing; -[TestClass] +[TestFixture] public class Line3DTests { - [TestMethod] + [Test] public void CompareTo_ShouldBeNegativeOne_GivenEmptyAndOne() { - Assert.AreEqual(-1, Line3D.Empty.CompareTo(Line3D.One)); + Assert.That(Line3D.Empty.CompareTo(Line3D.One), Is.EqualTo(-1)); } - [TestMethod] + [Test] public void CompareTo_ShouldBeNegativeOne_GivenEmptyLineAndOneLineAsObject() { - Assert.AreEqual(-1, Line3D.Empty.CompareTo((object)Line3D.One)); + Assert.That(Line3D.Empty.CompareTo((object)Line3D.One), Is.EqualTo(-1)); } - [TestMethod] + [Test] public void CompareTo_ShouldBeOne_GivenNull() { - Assert.AreEqual(1, Line3D.One.CompareTo(null)); + Assert.That(Line3D.One.CompareTo(null), Is.EqualTo(1)); } - [TestMethod] + [Test] public void CompareTo_ShouldBeOne_GivenOneAndEmpty() { - Assert.AreEqual(1, Line3D.One.CompareTo(Line3D.Empty)); + Assert.That(Line3D.One.CompareTo(Line3D.Empty), Is.EqualTo(1)); } - [TestMethod] + [Test] public void CompareTo_ShouldBeZero_GivenUnitLine() { var unitLine3D = Line3D.One; - Assert.AreEqual(0, unitLine3D.CompareTo(unitLine3D)); + Assert.That(unitLine3D.CompareTo(unitLine3D), Is.Zero); } - [TestMethod] + [Test] public void CompareTo_ShouldThrowArgumentException_GivenInvalidType() { - Assert.ThrowsException(() => Line3D.Empty.CompareTo(new object())); + Assert.Throws(() => _ = Line3D.Empty.CompareTo(new object())); } - [TestMethod] + [Test] public void Length_ShouldBe0_GivenEmptyLine() { - Assert.AreEqual(0.0f, Line3D.Empty.Length); + Assert.That(Line3D.Empty.Length, Is.Zero); } - [TestMethod] + [Test] public void Length_ShouldBe1_GivenUnitXLine() { - Assert.AreEqual(1.0f, Line3D.UnitX.Length, 1e-6f); + Assert.That(Line3D.UnitX.Length, Is.EqualTo(1.0f).Within(1e-6f)); } - [TestMethod] + [Test] public void Length_ShouldBe1_GivenUnitYLine() { - Assert.AreEqual(1.0f, Line3D.UnitY.Length, 1e-6f); + Assert.That(Line3D.UnitY.Length, Is.EqualTo(1.0f).Within(1e-6f)); } - [TestMethod] + [Test] public void Length_ShouldBe1_GivenUnitZLine() { - Assert.AreEqual(1.0f, Line3D.UnitZ.Length, 1e-6f); + Assert.That(Line3D.UnitZ.Length, Is.EqualTo(1.0f).Within(1e-6f)); } - [TestMethod] + [Test] public void Equals_ShouldBeTrue_GivenTwoUnitLines() { Line3D first = Line3D.One; Line3D second = Line3D.One; - Assert.AreEqual(first, second); - Assert.IsTrue(first == second); - Assert.IsFalse(first != second); + Assert.That(second, Is.EqualTo(first)); } - [TestMethod] + [Test] public void Equals_ShouldBeFalse_GivenDifferentLines() { - Assert.AreNotEqual(Line3D.One, Line3D.Empty); - Assert.IsFalse(Line3D.One == Line3D.Empty); - Assert.IsTrue(Line3D.One != Line3D.Empty); + Assert.That(Line3D.Empty, Is.Not.EqualTo(Line3D.One)); } - [TestMethod] + [Test] public void Equals_ShouldBeFalse_GivenDifferentObjects() { - Assert.IsFalse(Line3D.One.Equals(null)); + Assert.That(Line3D.One, Is.Not.EqualTo(null)); } - [TestMethod] + [Test] public void GetHashCode_ShouldBeCorrect_GivenEmptyLine() { // this test is pretty pointless, it exists only for code coverage purposes int hashCode = Line3D.Empty.GetHashCode(); - Assert.AreEqual(hashCode, Line3D.Empty.GetHashCode()); + Assert.That(Line3D.Empty.GetHashCode(), Is.EqualTo(hashCode)); } - [TestMethod] + [Test] public void GetHashCode_ShouldBeCorrect_GivenUnitLine() { // this test is pretty pointless, it exists only for code coverage purposes int hashCode = Line3D.One.GetHashCode(); - Assert.AreEqual(hashCode, Line3D.One.GetHashCode()); + Assert.That(Line3D.One.GetHashCode(), Is.EqualTo(hashCode)); } - [TestMethod] + [Test] public void op_Explicit_ShouldReturnEquivalentLine_GivenLine() { Line3D oneLine = new Line3D(Vector3.Zero, Vector3.UnitX + Vector3.UnitY); @@ -119,12 +115,15 @@ public class Line3DTests var expectedStart = new Point((int)oneLine.Start.X, (int)oneLine.Start.Y); var expectedEnd = new Point((int)oneLine.End.X, (int)oneLine.End.Y); - Assert.AreEqual(oneLine.Length, converted.Length); - Assert.AreEqual(expectedStart, converted.Start); - Assert.AreEqual(expectedEnd, converted.End); + Assert.Multiple(() => + { + Assert.That(converted.Length, Is.EqualTo(oneLine.Length)); + Assert.That(converted.Start, Is.EqualTo(expectedStart)); + Assert.That(converted.End, Is.EqualTo(expectedEnd)); + }); } - [TestMethod] + [Test] public void op_Explicit_ShouldReturnEquivalentLineF_GivenLine() { Line3D oneLine = new Line3D(Vector3.Zero, Vector3.UnitX + Vector3.UnitY); @@ -133,21 +132,22 @@ public class Line3DTests var expectedStart = new PointF(oneLine.Start.X, oneLine.Start.Y); var expectedEnd = new PointF(oneLine.End.X, oneLine.End.Y); - Assert.AreEqual(oneLine.Length, converted.Length); - Assert.AreEqual(expectedStart, converted.Start); - Assert.AreEqual(expectedEnd, converted.End); + Assert.Multiple(() => + { + Assert.That(converted.Length, Is.EqualTo(oneLine.Length)); + Assert.That(converted.Start, Is.EqualTo(expectedStart)); + Assert.That(converted.End, Is.EqualTo(expectedEnd)); + }); } - [TestMethod] + [Test] public void op_GreaterThan_True_GivenUnitAndEmptyCircle() { - Assert.IsTrue(Line3D.One > Line3D.Empty); - Assert.IsTrue(Line3D.One >= Line3D.Empty); - Assert.IsFalse(Line3D.One < Line3D.Empty); - Assert.IsFalse(Line3D.One <= Line3D.Empty); + Assert.That(Line3D.One, Is.GreaterThan(Line3D.Empty)); + Assert.That(Line3D.One, Is.GreaterThanOrEqualTo(Line3D.Empty)); } - [TestMethod] + [Test] public void op_Implicit_ShouldReturnEquivalentLine_GivenLine() { Line oneLine = Line.One; @@ -156,13 +156,16 @@ public class Line3DTests var expectedStart = new Vector3(oneLine.Start.X, oneLine.Start.Y, 0.0f); var expectedEnd = new Vector3(oneLine.End.X, oneLine.End.Y, 0.0f); - Assert.AreEqual(oneLine, converted); - Assert.AreEqual(oneLine.Length, converted.Length); - Assert.AreEqual(expectedStart, converted.Start); - Assert.AreEqual(expectedEnd, converted.End); + Assert.Multiple(() => + { + Assert.That(converted, Is.EqualTo((Line3D)oneLine)); + Assert.That(converted.Length, Is.EqualTo(oneLine.Length)); + Assert.That(converted.Start, Is.EqualTo(expectedStart)); + Assert.That(converted.End, Is.EqualTo(expectedEnd)); + }); } - [TestMethod] + [Test] public void op_Implicit_ShouldReturnEquivalentLine_GivenLineF() { LineF oneLine = LineF.One; @@ -171,18 +174,19 @@ public class Line3DTests var expectedStart = new Vector3(oneLine.Start.X, oneLine.Start.Y, 0.0f); var expectedEnd = new Vector3(oneLine.End.X, oneLine.End.Y, 0.0f); - Assert.AreEqual(oneLine, converted); - Assert.AreEqual(oneLine.Length, converted.Length); - Assert.AreEqual(expectedStart, converted.Start); - Assert.AreEqual(expectedEnd, converted.End); + Assert.Multiple(() => + { + Assert.That(converted, Is.EqualTo((Line3D)oneLine)); + Assert.That(converted.Length, Is.EqualTo(oneLine.Length)); + Assert.That(converted.Start, Is.EqualTo(expectedStart)); + Assert.That(converted.End, Is.EqualTo(expectedEnd)); + }); } - [TestMethod] + [Test] public void op_LessThan_True_GivenEmptyAndUnitCircle() { - Assert.IsTrue(Line3D.Empty < Line3D.One); - Assert.IsTrue(Line3D.Empty <= Line3D.One); - Assert.IsFalse(Line3D.Empty > Line3D.One); - Assert.IsFalse(Line3D.Empty >= Line3D.One); + Assert.That(Line3D.Empty, Is.LessThan(Line3D.One)); + Assert.That(Line3D.Empty, Is.LessThanOrEqualTo(Line3D.One)); } } diff --git a/X10D.Tests/src/Drawing/LineFTests.cs b/X10D.Tests/src/Drawing/LineFTests.cs index 582bde3..3f59938 100644 --- a/X10D.Tests/src/Drawing/LineFTests.cs +++ b/X10D.Tests/src/Drawing/LineFTests.cs @@ -1,146 +1,152 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Drawing; +using NUnit.Framework; using X10D.Drawing; namespace X10D.Tests.Drawing; -[TestClass] +[TestFixture] public class LineFTests { - [TestMethod] + [Test] public void CompareTo_ShouldBeNegativeOne_GivenEmptyAndOne() { - Assert.AreEqual(-1, LineF.Empty.CompareTo(LineF.One)); + Assert.That(LineF.Empty.CompareTo(LineF.One), Is.EqualTo(-1)); } - [TestMethod] + [Test] public void CompareTo_ShouldBeNegativeOne_GivenEmptyLineAndOneLineAsObject() { - Assert.AreEqual(-1, LineF.Empty.CompareTo((object)LineF.One)); + Assert.That(LineF.Empty.CompareTo((object)LineF.One), Is.EqualTo(-1)); } - [TestMethod] + [Test] public void CompareTo_ShouldBeOne_GivenNull() { - Assert.AreEqual(1, LineF.One.CompareTo(null)); + Assert.That(LineF.One.CompareTo(null), Is.EqualTo(1)); } - [TestMethod] + [Test] public void CompareTo_ShouldBeOne_GivenOneAndEmpty() { - Assert.AreEqual(1, LineF.One.CompareTo(LineF.Empty)); + Assert.That(LineF.One.CompareTo(LineF.Empty), Is.EqualTo(1)); } - [TestMethod] + [Test] public void CompareTo_ShouldBeZero_GivenUnitLine() { - var unitLineF = LineF.One; - Assert.AreEqual(0, unitLineF.CompareTo(unitLineF)); + Assert.That(LineF.One.CompareTo(LineF.One), Is.Zero); } - [TestMethod] + [Test] public void CompareTo_ShouldThrowArgumentException_GivenInvalidType() { - Assert.ThrowsException(() => LineF.Empty.CompareTo(new object())); + Assert.Throws(() => _ = LineF.Empty.CompareTo(new object())); } - [TestMethod] + [Test] public void Length_ShouldBe0_GivenEmptyLine() { - Assert.AreEqual(0.0f, LineF.Empty.Length); + Assert.That(LineF.Empty.Length, Is.Zero); } - [TestMethod] + [Test] public void Length_ShouldBe1_GivenUnitXLine() { - Assert.AreEqual(1.0f, LineF.UnitX.Length, 1e-6f); + Assert.That(LineF.UnitX.Length, Is.EqualTo(1.0f).Within(1e-6f)); } - [TestMethod] + [Test] public void Length_ShouldBe1_GivenUnitYLine() { - Assert.AreEqual(1.0f, LineF.UnitY.Length, 1e-6f); + Assert.That(LineF.UnitY.Length, Is.EqualTo(1.0f).Within(1e-6f)); } - [TestMethod] + [Test] public void Equals_ShouldBeTrue_GivenTwoUnitLines() { LineF first = LineF.One; LineF second = LineF.One; - Assert.AreEqual(first, second); - Assert.IsTrue(first == second); - Assert.IsFalse(first != second); + Assert.Multiple(() => + { + Assert.That(second, Is.EqualTo(first)); + Assert.That(first, Is.EqualTo(second)); + }); } - [TestMethod] + [Test] public void Equals_ShouldBeFalse_GivenDifferentLines() { - Assert.AreNotEqual(LineF.One, LineF.Empty); - Assert.IsFalse(LineF.One == LineF.Empty); - Assert.IsTrue(LineF.One != LineF.Empty); + Assert.Multiple(() => + { + Assert.That(LineF.Empty, Is.Not.EqualTo(LineF.One)); + Assert.That(LineF.One, Is.Not.EqualTo(LineF.Empty)); + }); } - [TestMethod] + [Test] public void Equals_ShouldBeFalse_GivenDifferentObjects() { - Assert.IsFalse(LineF.One.Equals(null)); + Assert.That(LineF.One, Is.Not.EqualTo(null)); } - [TestMethod] + [Test] public void GetHashCode_ShouldBeCorrect_GivenEmptyLine() { // this test is pretty pointless, it exists only for code coverage purposes int hashCode = LineF.Empty.GetHashCode(); - Assert.AreEqual(hashCode, LineF.Empty.GetHashCode()); + Assert.That(LineF.Empty.GetHashCode(), Is.EqualTo(hashCode)); } - [TestMethod] + [Test] public void GetHashCode_ShouldBeCorrect_GivenUnitLine() { // this test is pretty pointless, it exists only for code coverage purposes int hashCode = LineF.One.GetHashCode(); - Assert.AreEqual(hashCode, LineF.One.GetHashCode()); + Assert.That(LineF.One.GetHashCode(), Is.EqualTo(hashCode)); } - [TestMethod] + [Test] public void op_Explicit_ShouldReturnEquivalentLine_GivenLine() { LineF oneLine = LineF.One; Line converted = (Line)oneLine; - Assert.AreEqual(oneLine, converted); - Assert.AreEqual(oneLine.Length, converted.Length); - Assert.AreEqual(oneLine.Start, converted.Start); - Assert.AreEqual(oneLine.End, converted.End); + Assert.Multiple(() => + { + Assert.That(converted, Is.EqualTo((Line)oneLine)); + Assert.That(converted.Length, Is.EqualTo(oneLine.Length)); + Assert.That((PointF)converted.Start, Is.EqualTo(oneLine.Start)); + Assert.That((PointF)converted.End, Is.EqualTo(oneLine.End)); + }); } - [TestMethod] + [Test] public void op_GreaterThan_True_GivenUnitAndEmptyCircle() { - Assert.IsTrue(LineF.One > LineF.Empty); - Assert.IsTrue(LineF.One >= LineF.Empty); - Assert.IsFalse(LineF.One < LineF.Empty); - Assert.IsFalse(LineF.One <= LineF.Empty); + Assert.That(LineF.One, Is.GreaterThan(LineF.Empty)); + Assert.That(LineF.One, Is.GreaterThanOrEqualTo(LineF.Empty)); } - [TestMethod] + [Test] public void op_Implicit_ShouldReturnEquivalentLine_GivenLine() { Line oneLine = Line.One; LineF converted = oneLine; - Assert.AreEqual(oneLine, converted); - Assert.AreEqual(oneLine.Length, converted.Length); - Assert.AreEqual(oneLine.Start, converted.Start); - Assert.AreEqual(oneLine.End, converted.End); + Assert.Multiple(() => + { + Assert.That(converted, Is.EqualTo((LineF)oneLine)); + Assert.That(converted.Length, Is.EqualTo(oneLine.Length)); + Assert.That(converted.Start, Is.EqualTo((PointF)oneLine.Start)); + Assert.That(converted.End, Is.EqualTo((PointF)oneLine.End)); + }); } - [TestMethod] + [Test] public void op_LessThan_True_GivenEmptyAndUnitCircle() { - Assert.IsTrue(LineF.Empty < LineF.One); - Assert.IsTrue(LineF.Empty <= LineF.One); - Assert.IsFalse(LineF.Empty > LineF.One); - Assert.IsFalse(LineF.Empty >= LineF.One); + Assert.That(LineF.Empty, Is.LessThan(LineF.One)); + Assert.That(LineF.Empty, Is.LessThanOrEqualTo(LineF.One)); } } diff --git a/X10D.Tests/src/Drawing/LineTests.cs b/X10D.Tests/src/Drawing/LineTests.cs index 2a690e8..8fba47f 100644 --- a/X10D.Tests/src/Drawing/LineTests.cs +++ b/X10D.Tests/src/Drawing/LineTests.cs @@ -1,122 +1,122 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Drawing; namespace X10D.Tests.Drawing; -[TestClass] +[TestFixture] public class LineTests { - [TestMethod] + [Test] public void CompareTo_ShouldBeNegativeOne_GivenEmptyAndOne() { - Assert.AreEqual(-1, Line.Empty.CompareTo(Line.One)); + Assert.That(Line.Empty.CompareTo(Line.One), Is.EqualTo(-1)); } - [TestMethod] + [Test] public void CompareTo_ShouldBeNegativeOne_GivenEmptyLineAndOneLineAsObject() { - Assert.AreEqual(-1, Line.Empty.CompareTo((object)Line.One)); + Assert.That(Line.Empty.CompareTo((object)Line.One), Is.EqualTo(-1)); } - [TestMethod] + [Test] public void CompareTo_ShouldBeOne_GivenNull() { - Assert.AreEqual(1, Line.One.CompareTo(null)); + Assert.That(Line.One.CompareTo(null), Is.EqualTo(1)); } - [TestMethod] + [Test] public void CompareTo_ShouldBeOne_GivenOneAndEmpty() { - Assert.AreEqual(1, Line.One.CompareTo(Line.Empty)); + Assert.That(Line.One.CompareTo(Line.Empty), Is.EqualTo(1)); } - [TestMethod] + [Test] public void CompareTo_ShouldBeZero_GivenUnitLine() { var unitLine = Line.One; - Assert.AreEqual(0, unitLine.CompareTo(unitLine)); + Assert.That(unitLine.CompareTo(unitLine), Is.Zero); } - [TestMethod] + [Test] public void CompareTo_ShouldThrowArgumentException_GivenInvalidType() { - Assert.ThrowsException(() => Line.Empty.CompareTo(new object())); + Assert.Throws(() => _ = Line.Empty.CompareTo(new object())); } - [TestMethod] + [Test] public void Equals_ShouldBeTrue_GivenTwoUnitLines() { Line first = Line.One; Line second = Line.One; - Assert.AreEqual(first, second); - Assert.IsTrue(first == second); - Assert.IsFalse(first != second); + Assert.Multiple(() => + { + Assert.That(second, Is.EqualTo(first)); + Assert.That(first, Is.EqualTo(second)); + }); } - [TestMethod] + [Test] public void Equals_ShouldBeFalse_GivenDifferentLines() { - Assert.AreNotEqual(Line.One, Line.Empty); - Assert.IsFalse(Line.One == Line.Empty); - Assert.IsTrue(Line.One != Line.Empty); + Assert.Multiple(() => + { + Assert.That(Line.Empty, Is.Not.EqualTo(Line.One)); + Assert.That(Line.One, Is.Not.EqualTo(Line.Empty)); + }); } - [TestMethod] + [Test] public void Equals_ShouldBeFalse_GivenDifferentObjects() { - Assert.IsFalse(Line.One.Equals(null)); + Assert.That(Line.One, Is.Not.EqualTo(null)); } - [TestMethod] + [Test] public void GetHashCode_ShouldBeCorrect_GivenEmptyLine() { // this test is pretty pointless, it exists only for code coverage purposes int hashCode = Line.Empty.GetHashCode(); - Assert.AreEqual(hashCode, Line.Empty.GetHashCode()); + Assert.That(Line.Empty.GetHashCode(), Is.EqualTo(hashCode)); } - [TestMethod] + [Test] public void GetHashCode_ShouldBeCorrect_GivenUnitLine() { // this test is pretty pointless, it exists only for code coverage purposes int hashCode = Line.One.GetHashCode(); - Assert.AreEqual(hashCode, Line.One.GetHashCode()); + Assert.That(Line.One.GetHashCode(), Is.EqualTo(hashCode)); } - [TestMethod] + [Test] public void Length_ShouldBe0_GivenEmptyLine() { - Assert.AreEqual(0.0f, Line.Empty.Length); + Assert.That(Line.Empty.Length, Is.Zero); } - [TestMethod] + [Test] public void Length_ShouldBe1_GivenUnitXLine() { - Assert.AreEqual(1.0f, Line.UnitX.Length, 1e-6f); + Assert.That(Line.UnitX.Length, Is.EqualTo(1.0f).Within(1e-6f)); } - [TestMethod] + [Test] public void Length_ShouldBe1_GivenUnitYLine() { - Assert.AreEqual(1.0f, Line.UnitY.Length, 1e-6f); + Assert.That(Line.UnitY.Length, Is.EqualTo(1.0f).Within(1e-6f)); } - [TestMethod] + [Test] public void op_GreaterThan_True_GivenUnitAndEmptyCircle() { - Assert.IsTrue(Line.One > Line.Empty); - Assert.IsTrue(Line.One >= Line.Empty); - Assert.IsFalse(Line.One < Line.Empty); - Assert.IsFalse(Line.One <= Line.Empty); + Assert.That(Line.One, Is.GreaterThan(Line.Empty)); + Assert.That(Line.One, Is.GreaterThanOrEqualTo(Line.Empty)); } - [TestMethod] + [Test] public void op_LessThan_True_GivenEmptyAndUnitCircle() { - Assert.IsTrue(Line.Empty < Line.One); - Assert.IsTrue(Line.Empty <= Line.One); - Assert.IsFalse(Line.Empty > Line.One); - Assert.IsFalse(Line.Empty >= Line.One); + Assert.That(Line.Empty, Is.LessThan(Line.One)); + Assert.That(Line.Empty, Is.LessThanOrEqualTo(Line.One)); } } diff --git a/X10D.Tests/src/Drawing/PointFTests.cs b/X10D.Tests/src/Drawing/PointFTests.cs index 87b6f63..9bcd0c9 100644 --- a/X10D.Tests/src/Drawing/PointFTests.cs +++ b/X10D.Tests/src/Drawing/PointFTests.cs @@ -1,5 +1,5 @@ using System.Drawing; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; #if !NET6_0_OR_GREATER using X10D.Core; #endif @@ -7,59 +7,74 @@ using X10D.Drawing; namespace X10D.Tests.Drawing; -[TestClass] +[TestFixture] public class PointFTests { - [TestMethod] + [Test] public void IsOnLine_ShouldReturnTrue_GivenPointOnLine() { var point = new PointF(1.0f, 0.0f); var line = new LineF(PointF.Empty, new PointF(2.0f, 0.0f)); - Assert.IsTrue(point.IsOnLine(line)); - Assert.IsTrue(point.IsOnLine(line.Start, line.End)); - Assert.IsTrue(point.IsOnLine(line.Start.ToVector2(), line.End.ToVector2())); + Assert.Multiple(() => + { + Assert.That(point.IsOnLine(line)); + Assert.That(point.IsOnLine(line.Start, line.End)); + Assert.That(point.IsOnLine(line.Start.ToVector2(), line.End.ToVector2())); + }); } - [TestMethod] + [Test] public void IsOnLine_ShouldReturnFalse_GivenPointNotOnLine() { var point = new PointF(1.0f, 1.0f); var line = new LineF(PointF.Empty, new PointF(2.0f, 0.0f)); - Assert.IsFalse(point.IsOnLine(line)); - Assert.IsFalse(point.IsOnLine(line.Start, line.End)); - Assert.IsFalse(point.IsOnLine(line.Start.ToVector2(), line.End.ToVector2())); + Assert.Multiple(() => + { + Assert.That(point.IsOnLine(line), Is.False); + Assert.That(point.IsOnLine(line.Start, line.End), Is.False); + Assert.That(point.IsOnLine(line.Start.ToVector2(), line.End.ToVector2()), Is.False); + }); } - [TestMethod] + [Test] public void Round_ShouldRoundToNearestInteger_GivenNoParameters() { var point = new PointF(1.5f, 2.6f); var rounded = point.Round(); - Assert.AreEqual(2, rounded.X); - Assert.AreEqual(3, rounded.Y); + Assert.Multiple(() => + { + Assert.That(rounded.X, Is.EqualTo(2)); + Assert.That(rounded.Y, Is.EqualTo(3)); + }); } - [TestMethod] + [Test] public void Round_ShouldRoundToNearest10_GivenPrecision10() { var point = new PointF(1.5f, 25.2f); var rounded = point.Round(10); - Assert.AreEqual(0, rounded.X); - Assert.AreEqual(30, rounded.Y); + Assert.Multiple(() => + { + Assert.That(rounded.X, Is.Zero); + Assert.That(rounded.Y, Is.EqualTo(30)); + }); } - [TestMethod] + [Test] public void ToSizeF_ShouldReturnSize_WithEquivalentMembers() { var random = new Random(); var point = new PointF(random.NextSingle(), random.NextSingle()); var size = point.ToSizeF(); - Assert.AreEqual(point.X, size.Width, 1e-6f); - Assert.AreEqual(point.Y, size.Height, 1e-6f); + Assert.Multiple(() => + { + Assert.That(size.Width, Is.EqualTo(point.X).Within(1e-6f)); + Assert.That(size.Height, Is.EqualTo(point.Y).Within(1e-6f)); + }); } } diff --git a/X10D.Tests/src/Drawing/PointTests.cs b/X10D.Tests/src/Drawing/PointTests.cs index 19e5890..818a3f5 100644 --- a/X10D.Tests/src/Drawing/PointTests.cs +++ b/X10D.Tests/src/Drawing/PointTests.cs @@ -1,64 +1,79 @@ using System.Drawing; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Drawing; namespace X10D.Tests.Drawing; -[TestClass] +[TestFixture] public class PointTests { - [TestMethod] + [Test] public void IsOnLine_ShouldReturnTrue_GivenPointOnLine() { var point = new Point(1, 0); var line = new Line(Point.Empty, new Point(2, 0)); - Assert.IsTrue(point.IsOnLine(line)); - Assert.IsTrue(point.IsOnLine(line.Start, line.End)); - Assert.IsTrue(point.IsOnLine(line.Start.ToVector2(), line.End.ToVector2())); + Assert.Multiple(() => + { + Assert.That(point.IsOnLine(line)); + Assert.That(point.IsOnLine(line.Start, line.End)); + Assert.That(point.IsOnLine(line.Start.ToVector2(), line.End.ToVector2())); + }); } - [TestMethod] + [Test] public void IsOnLine_ShouldReturnFalse_GivenPointNotOnLine() { var point = new Point(1, 1); var line = new Line(Point.Empty, new Point(2, 0)); - Assert.IsFalse(point.IsOnLine(line)); - Assert.IsFalse(point.IsOnLine(line.Start, line.End)); - Assert.IsFalse(point.IsOnLine(line.Start.ToVector2(), line.End.ToVector2())); + Assert.Multiple(() => + { + Assert.That(point.IsOnLine(line), Is.False); + Assert.That(point.IsOnLine(line.Start, line.End), Is.False); + Assert.That(point.IsOnLine(line.Start.ToVector2(), line.End.ToVector2()), Is.False); + }); } - [TestMethod] + [Test] public void ToSize_ShouldReturnSize_WithEquivalentMembers() { var random = new Random(); var point = new Point(random.Next(), random.Next()); var size = point.ToSize(); - Assert.AreEqual(point.X, size.Width); - Assert.AreEqual(point.Y, size.Height); + Assert.Multiple(() => + { + Assert.That(size.Width, Is.EqualTo(point.X)); + Assert.That(size.Height, Is.EqualTo(point.Y)); + }); } - [TestMethod] + [Test] public void ToSizeF_ShouldReturnSize_WithEquivalentMembers() { var random = new Random(); var point = new Point(random.Next(), random.Next()); var size = point.ToSizeF(); - Assert.AreEqual(point.X, size.Width, 1e-6f); - Assert.AreEqual(point.Y, size.Height, 1e-6f); + Assert.Multiple(() => + { + Assert.That(size.Width, Is.EqualTo(point.X).Within(1e-6f)); + Assert.That(size.Height, Is.EqualTo(point.Y).Within(1e-6f)); + }); } - [TestMethod] + [Test] public void ToVector2_ShouldReturnVector_WithEquivalentMembers() { var random = new Random(); var point = new Point(random.Next(), random.Next()); var size = point.ToVector2(); - Assert.AreEqual(point.X, size.X, 1e-6f); - Assert.AreEqual(point.Y, size.Y, 1e-6f); + Assert.Multiple(() => + { + Assert.That(size.X, Is.EqualTo(point.X).Within(1e-6f)); + Assert.That(size.Y, Is.EqualTo(point.Y).Within(1e-6f)); + }); } } diff --git a/X10D.Tests/src/Drawing/PolygonFTests.cs b/X10D.Tests/src/Drawing/PolygonFTests.cs index 6f7cb99..196b88c 100644 --- a/X10D.Tests/src/Drawing/PolygonFTests.cs +++ b/X10D.Tests/src/Drawing/PolygonFTests.cs @@ -1,228 +1,223 @@ using System.Drawing; using System.Numerics; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Drawing; namespace X10D.Tests.Drawing; -[TestClass] +[TestFixture] public class PolygonFTests { - [TestMethod] + [Test] public void AddVertices_ShouldAddVertices() { var polygon = PolygonF.Empty; polygon.AddVertices(new[] {new PointF(1, 2), new PointF(3, 4)}); - Assert.AreEqual(2, polygon.VertexCount); + Assert.That(polygon.VertexCount, Is.EqualTo(2)); // assert that the empty polygon was not modified - Assert.AreEqual(0, PolygonF.Empty.VertexCount); + Assert.That(PolygonF.Empty.VertexCount, Is.Zero); } - [TestMethod] + [Test] public void AddVertices_ShouldThrowArgumentNullException_GivenNullEnumerableOfPointF() { var polygon = PolygonF.Empty; IEnumerable vertices = null!; - Assert.ThrowsException(() => polygon.AddVertices(vertices)); + Assert.Throws(() => polygon.AddVertices(vertices)); } - [TestMethod] + [Test] public void AddVertices_ShouldThrowArgumentNullException_GivenNullEnumerableOfVector2() { var polygon = PolygonF.Empty; IEnumerable vertices = null!; - Assert.ThrowsException(() => polygon.AddVertices(vertices)); + Assert.Throws(() => polygon.AddVertices(vertices)); } - [TestMethod] + [Test] public void ClearVertices_ShouldClearVertices() { var polygon = PolygonF.Empty; polygon.AddVertices(new[] {new Vector2(1, 2), new Vector2(3, 4)}); - Assert.AreEqual(2, polygon.VertexCount); + Assert.That(polygon.VertexCount, Is.EqualTo(2)); // assert that the empty polygon was not modified - Assert.AreEqual(0, PolygonF.Empty.VertexCount); + Assert.That(PolygonF.Empty.VertexCount, Is.Zero); polygon.ClearVertices(); - Assert.AreEqual(0, polygon.VertexCount); + Assert.That(polygon.VertexCount, Is.Zero); } - [TestMethod] + [Test] public void Constructor_ShouldPopulateVertices_GivenPolygon() { var pointPolygon = new PolygonF(new[] {new PointF(1, 2), new PointF(3, 4)}); var vectorPolygon = new PolygonF(new[] {new Vector2(1, 2), new Vector2(3, 4)}); - Assert.AreEqual(2, pointPolygon.VertexCount); - Assert.AreEqual(2, vectorPolygon.VertexCount); + Assert.That(pointPolygon.VertexCount, Is.EqualTo(2)); + Assert.That(vectorPolygon.VertexCount, Is.EqualTo(2)); } - - [TestMethod] + + [Test] public void Constructor_ShouldThrowArgumentNullException_GivenNullEnumerableOfPointF() { IEnumerable vertices = null!; - Assert.ThrowsException(() => new PolygonF(vertices)); + Assert.Throws(() => _ = new PolygonF(vertices)); } - [TestMethod] + [Test] public void Constructor_ShouldThrowArgumentNullException_GivenNullEnumerableOfVector2() { IEnumerable vertices = null!; - Assert.ThrowsException(() => new PolygonF(vertices)); + Assert.Throws(() => _ = new PolygonF(vertices)); } - [TestMethod] + [Test] public void CopyConstructor_ShouldCopyVertices_GivenPolygon() { var first = PolygonF.Empty; first.AddVertices(new[] {new PointF(1, 2), new PointF(3, 4)}); var second = new PolygonF(first); - Assert.AreEqual(2, first.VertexCount); - Assert.AreEqual(2, second.VertexCount); + Assert.That(first.VertexCount, Is.EqualTo(2)); + Assert.That(second.VertexCount, Is.EqualTo(2)); // we cannot use CollectionAssert here for reasons I am not entirely sure of. // it seems to dislike casting from IReadOnlyList to ICollection. but okay. - Assert.IsTrue(first.Vertices.SequenceEqual(second.Vertices)); + CollectionAssert.AreEqual(first.Vertices, second.Vertices); // assert that the empty polygon was not modified - Assert.AreEqual(0, PolygonF.Empty.VertexCount); + Assert.That(PolygonF.Empty.VertexCount, Is.Zero); } - [TestMethod] + [Test] public void CopyConstructor_ShouldThrowArgumentNullException_GivenNullPolygonF() { PolygonF polygon = null!; - Assert.ThrowsException(() => new PolygonF(polygon)); + Assert.Throws(() => _ = new PolygonF(polygon)); } - [TestMethod] + [Test] public void Equals_ShouldBeTrue_GivenTwoEmptyPolygons() { var first = PolygonF.Empty; var second = PolygonF.Empty; - Assert.AreEqual(first, second); - Assert.AreEqual(second, first); - Assert.IsTrue(first.Equals(second)); - Assert.IsTrue(second.Equals(first)); - Assert.IsTrue(first == second); - Assert.IsTrue(second == first); - Assert.IsFalse(first != second); - Assert.IsFalse(second != first); + Assert.Multiple(() => + { + Assert.That(second, Is.EqualTo(first)); + Assert.That(first, Is.EqualTo(second)); + }); } - [TestMethod] + [Test] public void Equals_ShouldBeTrue_GivenTwoHexagons() { PolygonF first = CreateHexagon(); PolygonF second = CreateHexagon(); - Assert.AreEqual(first, second); - Assert.AreEqual(second, first); - Assert.IsTrue(first.Equals(second)); - Assert.IsTrue(second.Equals(first)); - Assert.IsTrue(first == second); - Assert.IsTrue(second == first); - Assert.IsFalse(first != second); - Assert.IsFalse(second != first); + Assert.Multiple(() => + { + Assert.That(second, Is.EqualTo(first)); + Assert.That(first, Is.EqualTo(second)); + }); } - [TestMethod] + [Test] public void Equals_ShouldBeFalse_GivenHexagonAndEmptyPolygon() { PolygonF first = CreateHexagon(); PolygonF second = PolygonF.Empty; - Assert.AreNotEqual(first, second); - Assert.AreNotEqual(second, first); - Assert.IsFalse(first.Equals(second)); - Assert.IsFalse(second.Equals(first)); - Assert.IsFalse(first == second); - Assert.IsFalse(second == first); - Assert.IsTrue(first != second); - Assert.IsTrue(second != first); + Assert.Multiple(() => + { + Assert.That(second, Is.Not.EqualTo(first)); + Assert.That(first, Is.Not.EqualTo(second)); + }); } - [TestMethod] + [Test] public void FromPolygon_ShouldThrowArgumentNullException_GivenNullPolygonF() { - Assert.ThrowsException(() => PolygonF.FromPolygon(null!)); + Assert.Throws(() => PolygonF.FromPolygon(null!)); } - [TestMethod] + [Test] public void IsConvex_ShouldBeFalse_GivenEmptyPolygon() { - Assert.IsFalse(PolygonF.Empty.IsConvex); + Assert.That(PolygonF.Empty.IsConvex, Is.False); } - [TestMethod] + [Test] public void IsConvex_ShouldBeTrue_GivenHexagon() { - Assert.IsTrue(CreateHexagon().IsConvex); + Assert.That(CreateHexagon().IsConvex, Is.True); } - [TestMethod] + [Test] public void IsConvex_ShouldBeFalse_GivenConcavePolygon() { - Assert.IsFalse(CreateConcavePolygon().IsConvex); + Assert.That(CreateConcavePolygon().IsConvex, Is.False); } - [TestMethod] + [Test] public void op_Explicit_ShouldReturnEquivalentCircle_GivenCircle() { PolygonF polygon = CreateHexagon(); Polygon converted = (Polygon)polygon; - Assert.AreEqual(polygon, converted); - Assert.AreEqual(polygon.IsConvex, converted.IsConvex); - Assert.AreEqual(polygon.VertexCount, converted.VertexCount); - - Assert.IsTrue(polygon.Vertices.SequenceEqual(converted.Vertices.Select(p => (PointF)p))); + Assert.Multiple(() => + { + Assert.That(converted, Is.EqualTo((Polygon)polygon)); + Assert.That(converted.IsConvex, Is.EqualTo(polygon.IsConvex)); + Assert.That(converted.VertexCount, Is.EqualTo(polygon.VertexCount)); + CollectionAssert.AreEqual(polygon.Vertices, converted.Vertices.Select(p => (PointF)p)); + }); } - [TestMethod] + [Test] public void op_Implicit_ShouldReturnEquivalentCircle_GivenCircle() { Polygon polygon = PolygonTests.CreateHexagon(); PolygonF converted = polygon; - Assert.AreEqual(polygon, converted); - Assert.AreEqual(polygon.IsConvex, converted.IsConvex); - Assert.AreEqual(polygon.VertexCount, converted.VertexCount); - - Assert.IsTrue(converted.Vertices.SequenceEqual(polygon.Vertices.Select(p => (PointF)p))); + Assert.Multiple(() => + { + Assert.That(converted, Is.EqualTo((PolygonF)polygon)); + Assert.That(converted.IsConvex, Is.EqualTo(polygon.IsConvex)); + Assert.That(converted.VertexCount, Is.EqualTo(polygon.VertexCount)); + CollectionAssert.AreEqual(converted.Vertices, polygon.Vertices.Select(p => (PointF)p)); + }); } - [TestMethod] + [Test] public void PointCount_ShouldBe1_GivenPolygonFWith1Point() { var polygon = new PolygonF(); polygon.AddVertex(new Point(1, 1)); - Assert.AreEqual(1, polygon.VertexCount); + Assert.That(polygon.VertexCount, Is.EqualTo(1)); // assert that the empty polygon was not modified - Assert.AreEqual(0, PolygonF.Empty.VertexCount); + Assert.That(PolygonF.Empty.VertexCount, Is.Zero); } - [TestMethod] + [Test] public void PointCount_ShouldBe0_GivenEmptyPolygon() { - Assert.AreEqual(0, PolygonF.Empty.VertexCount); + Assert.That(PolygonF.Empty.VertexCount, Is.Zero); } - [TestMethod] + [Test] public void GetHashCode_ShouldBeCorrect_GivenEmptyCircle() { // this test is pretty pointless, it exists only for code coverage purposes int hashCode = PolygonF.Empty.GetHashCode(); - Assert.AreEqual(hashCode, PolygonF.Empty.GetHashCode()); + Assert.That(PolygonF.Empty.GetHashCode(), Is.EqualTo(hashCode)); } - internal static PolygonF CreateHexagon() + private static PolygonF CreateHexagon() { var hexagon = new PolygonF(); hexagon.AddVertex(new Vector2(0, 0)); @@ -234,7 +229,7 @@ public class PolygonFTests return hexagon; } - internal static PolygonF CreateConcavePolygon() + private static PolygonF CreateConcavePolygon() { var hexagon = new PolygonF(); hexagon.AddVertex(new Vector2(0, 0)); diff --git a/X10D.Tests/src/Drawing/PolygonTests.cs b/X10D.Tests/src/Drawing/PolygonTests.cs index f8d55ae..96aadec 100644 --- a/X10D.Tests/src/Drawing/PolygonTests.cs +++ b/X10D.Tests/src/Drawing/PolygonTests.cs @@ -1,120 +1,118 @@ using System.Drawing; -using System.Numerics; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Drawing; namespace X10D.Tests.Drawing; -[TestClass] +[TestFixture] public class PolygonTests { - [TestMethod] + [Test] public void AddVertices_ShouldAddVertices() { var polygon = Polygon.Empty; polygon.AddVertices(new[] {new Point(1, 2), new Point(3, 4)}); - Assert.AreEqual(2, polygon.VertexCount); - + Assert.That(polygon.VertexCount, Is.EqualTo(2)); // assert that the empty polygon was not modified - Assert.AreEqual(0, Polygon.Empty.VertexCount); + Assert.That(Polygon.Empty.VertexCount, Is.Zero); } - [TestMethod] + [Test] public void AddVertices_ShouldThrowArgumentNullException_GivenNullEnumerable() { var polygon = Polygon.Empty; IEnumerable vertices = null!; - Assert.ThrowsException(() => polygon.AddVertices(vertices)); + Assert.Throws(() => polygon.AddVertices(vertices)); } - [TestMethod] + [Test] public void ClearVertices_ShouldClearVertices() { var polygon = Polygon.Empty; polygon.AddVertices(new[] {new Point(1, 2), new Point(3, 4)}); - Assert.AreEqual(2, polygon.VertexCount); + Assert.That(polygon.VertexCount, Is.EqualTo(2)); // assert that the empty polygon was not modified - Assert.AreEqual(0, Polygon.Empty.VertexCount); + Assert.That(Polygon.Empty.VertexCount, Is.Zero); polygon.ClearVertices(); - Assert.AreEqual(0, polygon.VertexCount); + Assert.That(polygon.VertexCount, Is.Zero); } - [TestMethod] + [Test] public void Constructor_ShouldPopulateVertices_GivenPolygon() { var pointPolygon = new Polygon(new[] {new Point(1, 2), new Point(3, 4)}); - Assert.AreEqual(2, pointPolygon.VertexCount); + Assert.That(pointPolygon.VertexCount, Is.EqualTo(2)); } - [TestMethod] + [Test] public void Constructor_ShouldThrowArgumentNullException_GivenNullEnumerableOfPoint() { IEnumerable vertices = null!; - Assert.ThrowsException(() => new Polygon(vertices)); + Assert.Throws(() => new Polygon(vertices)); } - [TestMethod] + [Test] public void CopyConstructor_ShouldCopyVertices_GivenPolygon() { var first = Polygon.Empty; first.AddVertices(new[] {new Point(1, 2), new Point(3, 4)}); var second = new Polygon(first); - Assert.AreEqual(2, first.VertexCount); - Assert.AreEqual(2, second.VertexCount); + Assert.That(first.VertexCount, Is.EqualTo(2)); + Assert.That(second.VertexCount, Is.EqualTo(2)); // we cannot use CollectionAssert here for reasons I am not entirely sure of. // it seems to dislike casting from IReadOnlyList to ICollection. but okay. - Assert.IsTrue(first.Vertices.SequenceEqual(second.Vertices)); + Assert.That(first.Vertices.SequenceEqual(second.Vertices)); // assert that the empty polygon was not modified - Assert.AreEqual(0, Polygon.Empty.VertexCount); + Assert.That(Polygon.Empty.VertexCount, Is.Zero); } - [TestMethod] + [Test] public void CopyConstructor_ShouldThrowArgumentNullException_GivenNullPolygon() { Polygon polygon = null!; - Assert.ThrowsException(() => new Polygon(polygon)); + Assert.Throws(() => new Polygon(polygon)); } - [TestMethod] + [Test] public void Equals_ShouldBeTrue_GivenTwoEmptyPolygons() { var first = Polygon.Empty; var second = Polygon.Empty; - Assert.AreEqual(first, second); - Assert.AreEqual(second, first); - Assert.IsTrue(first.Equals(second)); - Assert.IsTrue(second.Equals(first)); - Assert.IsTrue(first == second); - Assert.IsTrue(second == first); - Assert.IsFalse(first != second); - Assert.IsFalse(second != first); + Assert.That(second, Is.EqualTo(first)); + Assert.That(first, Is.EqualTo(second)); + Assert.That(first.Equals(second)); + Assert.That(second.Equals(first)); + Assert.That(first == second); + Assert.That(second == first); + Assert.That(first != second, Is.False); + Assert.That(second != first, Is.False); } - [TestMethod] + [Test] public void Equals_ShouldBeTrue_GivenTwoHexagons() { Polygon first = CreateHexagon(); Polygon second = CreateHexagon(); - Assert.AreEqual(first, second); - Assert.AreEqual(second, first); - Assert.IsTrue(first.Equals(second)); - Assert.IsTrue(second.Equals(first)); - Assert.IsTrue(first == second); - Assert.IsTrue(second == first); - Assert.IsFalse(first != second); - Assert.IsFalse(second != first); + Assert.That(second, Is.EqualTo(first)); + Assert.That(first, Is.EqualTo(second)); + Assert.That(first.Equals(second)); + Assert.That(second.Equals(first)); + Assert.That(first == second); + Assert.That(second == first); + Assert.That(first != second, Is.False); + Assert.That(second != first, Is.False); } - [TestMethod] + [Test] public void Equals_ShouldBeFalse_GivenHexagonAndEmptyPolygon() { Polygon first = CreateHexagon(); @@ -122,15 +120,15 @@ public class PolygonTests Assert.AreNotEqual(first, second); Assert.AreNotEqual(second, first); - Assert.IsFalse(first.Equals(second)); - Assert.IsFalse(second.Equals(first)); - Assert.IsFalse(first == second); - Assert.IsFalse(second == first); - Assert.IsTrue(first != second); - Assert.IsTrue(second != first); + Assert.That(first.Equals(second), Is.False); + Assert.That(second.Equals(first), Is.False); + Assert.That(first == second, Is.False); + Assert.That(second == first, Is.False); + Assert.That(first != second); + Assert.That(second != first); } - [TestMethod] + [Test] public void FromPolygonF_ShouldReturnEquivalentPolygon_GivenPolygon() { PolygonF hexagon = CreateHexagonF(); @@ -138,57 +136,57 @@ public class PolygonTests Polygon expected = CreateHexagon(); Polygon actual = Polygon.FromPolygonF(hexagon); - Assert.AreEqual(expected, actual); + Assert.That(actual, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void FromPolygonF_ShouldThrowArgumentNullException_GivenNullPolygon() { - Assert.ThrowsException(() => Polygon.FromPolygonF(null!)); + Assert.Throws(() => Polygon.FromPolygonF(null!)); } - [TestMethod] + [Test] public void IsConvex_ShouldBeFalse_GivenEmptyPolygon() { - Assert.IsFalse(Polygon.Empty.IsConvex); + Assert.That(Polygon.Empty.IsConvex, Is.False); } - [TestMethod] + [Test] public void IsConvex_ShouldBeTrue_GivenHexagon() { - Assert.IsTrue(CreateHexagon().IsConvex); + Assert.That(CreateHexagon().IsConvex); } - [TestMethod] + [Test] public void IsConvex_ShouldBeFalse_GivenConcavePolygon() { - Assert.IsFalse(CreateConcavePolygon().IsConvex); + Assert.That(CreateConcavePolygon().IsConvex, Is.False); } - [TestMethod] + [Test] public void PointCount_ShouldBe1_GivenPolygonWith1Point() { var polygon = Polygon.Empty; polygon.AddVertex(new Point(1, 1)); - Assert.AreEqual(1, polygon.VertexCount); + Assert.That(polygon.VertexCount, Is.EqualTo(1)); // assert that the empty polygon was not modified - Assert.AreEqual(0, Polygon.Empty.VertexCount); + Assert.That(Polygon.Empty.VertexCount, Is.Zero); } - [TestMethod] + [Test] public void PointCount_ShouldBe0_GivenEmptyPolygon() { - Assert.AreEqual(0, Polygon.Empty.VertexCount); + Assert.That(Polygon.Empty.VertexCount, Is.Zero); } - [TestMethod] + [Test] public void GetHashCode_ShouldBeCorrect_GivenEmptyCircle() { // this test is pretty pointless, it exists only for code coverage purposes int hashCode = Polygon.Empty.GetHashCode(); - Assert.AreEqual(hashCode, Polygon.Empty.GetHashCode()); + Assert.That(Polygon.Empty.GetHashCode(), Is.EqualTo(hashCode)); } internal static Polygon CreateHexagon() diff --git a/X10D.Tests/src/Drawing/PolyhedronTests.cs b/X10D.Tests/src/Drawing/PolyhedronTests.cs index f45ea1b..78b50e4 100644 --- a/X10D.Tests/src/Drawing/PolyhedronTests.cs +++ b/X10D.Tests/src/Drawing/PolyhedronTests.cs @@ -1,196 +1,217 @@ using System.Numerics; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Drawing; namespace X10D.Tests.Drawing; -[TestClass] +[TestFixture] public class PolyhedronTests { - [TestMethod] + [Test] public void AddVertices_ShouldAddVertices() { var polyhedron = Polyhedron.Empty; polyhedron.AddVertices(new[] {new Vector3(1, 2, 3), new Vector3(4, 5, 6)}); - Assert.AreEqual(2, polyhedron.VertexCount); - // assert that the empty polyhedron was not modified - Assert.AreEqual(0, Polyhedron.Empty.VertexCount); + Assert.Multiple(() => + { + Assert.That(polyhedron.VertexCount, Is.EqualTo(2)); + + // assert that the empty polyhedron was not modified + Assert.That(Polyhedron.Empty.VertexCount, Is.Zero); + }); } - [TestMethod] + [Test] public void AddVertices_ShouldThrowArgumentNullException_GivenNullEnumerableOfVector3() { var polygon = Polyhedron.Empty; IEnumerable vertices = null!; - Assert.ThrowsException(() => polygon.AddVertices(vertices)); + Assert.Throws(() => polygon.AddVertices(vertices)); } - [TestMethod] + [Test] public void ClearVertices_ShouldClearVertices() { var polyhedron = Polyhedron.Empty; polyhedron.AddVertices(new[] {new Vector3(1, 2, 3), new Vector3(4, 5, 6)}); - Assert.AreEqual(2, polyhedron.VertexCount); + Assert.Multiple(() => + { + Assert.That(polyhedron.VertexCount, Is.EqualTo(2)); - // assert that the empty polyhedron was not modified - Assert.AreEqual(0, Polyhedron.Empty.VertexCount); + // assert that the empty polyhedron was not modified + Assert.That(Polyhedron.Empty.VertexCount, Is.Zero); + }); polyhedron.ClearVertices(); - Assert.AreEqual(0, polyhedron.VertexCount); + Assert.That(polyhedron.VertexCount, Is.Zero); } - [TestMethod] + [Test] public void Constructor_ShouldPopulateVertices_GivenPolyhedron() { var polyhedron = new Polyhedron(new[] {new Vector3(1, 2, 3), new Vector3(4, 5, 6)}); - Assert.AreEqual(2, polyhedron.VertexCount); + Assert.That(polyhedron.VertexCount, Is.EqualTo(2)); } - [TestMethod] + [Test] public void Constructor_ShouldThrowArgumentNullException_GivenNullEnumerableOfVector3() { IEnumerable vertices = null!; - Assert.ThrowsException(() => new Polyhedron(vertices)); + Assert.Throws(() => _ = new Polyhedron(vertices)); } - [TestMethod] + [Test] public void CopyConstructor_ShouldCopyVertices_GivenPolyhedron() { var first = Polyhedron.Empty; first.AddVertices(new[] {new Vector3(1, 2, 3), new Vector3(4, 5, 6)}); var second = new Polyhedron(first); - Assert.AreEqual(2, first.VertexCount); - Assert.AreEqual(2, second.VertexCount); + Assert.Multiple(() => + { + Assert.That(first.VertexCount, Is.EqualTo(2)); + Assert.That(second.VertexCount, Is.EqualTo(2)); - // we cannot use CollectionAssert here for reasons I am not entirely sure of. - // it seems to dislike casting from IReadOnlyList to ICollection. but okay. - Assert.IsTrue(first.Vertices.SequenceEqual(second.Vertices)); + // we cannot use CollectionAssert here for reasons I am not entirely sure of. + // it seems to dislike casting from IReadOnlyList to ICollection. but okay. + CollectionAssert.AreEqual(first.Vertices, second.Vertices); - // assert that the empty polyhedron was not modified - Assert.AreEqual(0, Polyhedron.Empty.VertexCount); + // assert that the empty polyhedron was not modified + Assert.That(Polyhedron.Empty.VertexCount, Is.Zero); + }); } - [TestMethod] + [Test] public void Equals_ShouldBeTrue_GivenTwoEmptyPolyhedrons() { var first = Polyhedron.Empty; var second = Polyhedron.Empty; - Assert.AreEqual(first, second); - Assert.AreEqual(second, first); - Assert.IsTrue(first.Equals(second)); - Assert.IsTrue(second.Equals(first)); - Assert.IsTrue(first == second); - Assert.IsTrue(second == first); - Assert.IsFalse(first != second); - Assert.IsFalse(second != first); + Assert.Multiple(() => + { + Assert.That(second, Is.EqualTo(first)); + Assert.That(first, Is.EqualTo(second)); + }); } - [TestMethod] + [Test] public void Equals_ShouldBeTrue_GivenTwoHexagons() { - Polyhedron first = CreateHexagon(); - Polyhedron second = CreateHexagon(); + Polyhedron first = CreateHexagonPolyhedron(); + Polyhedron second = CreateHexagonPolyhedron(); - Assert.AreEqual(first, second); - Assert.AreEqual(second, first); - Assert.IsTrue(first.Equals(second)); - Assert.IsTrue(second.Equals(first)); - Assert.IsTrue(first == second); - Assert.IsTrue(second == first); - Assert.IsFalse(first != second); - Assert.IsFalse(second != first); + Assert.Multiple(() => + { + Assert.That(second, Is.EqualTo(first)); + Assert.That(first, Is.EqualTo(second)); + }); } - [TestMethod] + [Test] public void Equals_ShouldBeFalse_GivenHexagonAndEmptyPolyhedron() { - Polyhedron first = CreateHexagon(); + Polyhedron first = CreateHexagonPolyhedron(); Polyhedron second = Polyhedron.Empty; - Assert.AreNotEqual(first, second); - Assert.AreNotEqual(second, first); - Assert.IsFalse(first.Equals(second)); - Assert.IsFalse(second.Equals(first)); - Assert.IsFalse(first == second); - Assert.IsFalse(second == first); - Assert.IsTrue(first != second); - Assert.IsTrue(second != first); + Assert.Multiple(() => + { + Assert.That(second, Is.Not.EqualTo(first)); + Assert.That(first, Is.Not.EqualTo(second)); + }); } - [TestMethod] + [Test] public void FromPolygon_ShouldThrowArgumentNullException_GivenNullPolygonF() { - Assert.ThrowsException(() => Polyhedron.FromPolygon(null!)); + Assert.Throws(() => Polyhedron.FromPolygon(null!)); } - [TestMethod] + [Test] public void FromPolygonF_ShouldThrowArgumentNullException_GivenNullPolygonF() { - Assert.ThrowsException(() => Polyhedron.FromPolygonF(null!)); + Assert.Throws(() => Polyhedron.FromPolygonF(null!)); } - [TestMethod] + [Test] public void op_Implicit_ShouldReturnEquivalentPolyhedron_GivenPolyhedron() { Polygon polygon = PolygonTests.CreateHexagon(); Polyhedron converted = polygon; - Assert.AreEqual(polygon, converted); - Assert.AreEqual(polygon.VertexCount, converted.VertexCount); - - Assert.IsTrue(converted.Vertices.SequenceEqual(polygon.Vertices.Select(p => + Assert.Multiple(() => { - var point = p.ToVector2(); - return new Vector3(point.X, point.Y, 0); - }))); + Assert.That(converted, Is.EqualTo((Polyhedron)polygon)); + Assert.That(converted.VertexCount, Is.EqualTo(polygon.VertexCount)); + + CollectionAssert.AreEqual(converted.Vertices, polygon.Vertices.Select(p => + { + var point = p.ToVector2(); + return new Vector3(point.X, point.Y, 0); + })); + }); } - [TestMethod] + [Test] public void op_Implicit_ShouldReturnEquivalentPolyhedron_GivenPolyhedronF() { - PolygonF polygon = PolygonFTests.CreateHexagon(); + PolygonF polygon = CreateHexagonPolygon(); Polyhedron converted = polygon; - Assert.AreEqual(polygon, converted); - Assert.AreEqual(polygon.VertexCount, converted.VertexCount); - - Assert.IsTrue(converted.Vertices.SequenceEqual(polygon.Vertices.Select(v => + Assert.Multiple(() => { - var point = v.ToVector2(); - return new Vector3(point.X, point.Y, 0); - }))); + Assert.That(converted, Is.EqualTo((Polyhedron)polygon)); + Assert.That(converted.VertexCount, Is.EqualTo(polygon.VertexCount)); + CollectionAssert.AreEqual(converted.Vertices, polygon.Vertices.Select(p => + { + var point = p.ToVector2(); + return new Vector3(point.X, point.Y, 0); + })); + }); } - [TestMethod] + [Test] public void PointCount_ShouldBe1_GivenPolyhedronWith1Point() { var polyhedron = new Polyhedron(); polyhedron.AddVertex(Vector3.One); - Assert.AreEqual(1, polyhedron.VertexCount); + Assert.Multiple(() => + { + Assert.That(polyhedron.VertexCount, Is.EqualTo(1)); - // assert that the empty polyhedron was not modified - Assert.AreEqual(0, Polyhedron.Empty.VertexCount); + // assert that the empty polyhedron was not modified + Assert.That(Polyhedron.Empty.VertexCount, Is.Zero); + }); } - [TestMethod] + [Test] public void PointCount_ShouldBe0_GivenEmptyPolyhedron() { - Assert.AreEqual(0, Polyhedron.Empty.VertexCount); + Assert.That(Polyhedron.Empty.VertexCount, Is.Zero); } - [TestMethod] + [Test] public void GetHashCode_ShouldBeCorrect_GivenEmptyCircle() { // this test is pretty pointless, it exists only for code coverage purposes int hashCode = Polyhedron.Empty.GetHashCode(); - Assert.AreEqual(hashCode, Polyhedron.Empty.GetHashCode()); + Assert.That(Polyhedron.Empty.GetHashCode(), Is.EqualTo(hashCode)); } - internal static Polyhedron CreateHexagon() + private static PolygonF CreateHexagonPolygon() + { + var hexagon = new PolygonF(); + hexagon.AddVertex(new Vector2(0, 0)); + hexagon.AddVertex(new Vector2(1, 0)); + hexagon.AddVertex(new Vector2(1, 1)); + hexagon.AddVertex(new Vector2(0, 1)); + hexagon.AddVertex(new Vector2(-1, 1)); + hexagon.AddVertex(new Vector2(-1, 0)); + return hexagon; + } + + private static Polyhedron CreateHexagonPolyhedron() { var hexagon = new Polyhedron(); hexagon.AddVertex(new Vector3(0, 0, 0)); @@ -202,7 +223,7 @@ public class PolyhedronTests return hexagon; } - internal static Polyhedron CreateConcavePolyhedron() + private static Polyhedron CreateConcavePolyhedron() { var hexagon = new Polyhedron(); hexagon.AddVertex(new Vector3(0, 0, 0)); diff --git a/X10D.Tests/src/Drawing/RandomTests.cs b/X10D.Tests/src/Drawing/RandomTests.cs index 5dfce5f..cad12e4 100644 --- a/X10D.Tests/src/Drawing/RandomTests.cs +++ b/X10D.Tests/src/Drawing/RandomTests.cs @@ -1,37 +1,37 @@ using System.Drawing; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Drawing; namespace X10D.Tests.Drawing; -[TestClass] +[TestFixture] public class RandomTests { - [TestMethod] + [Test] public void NextColorArgb_ShouldReturn331515e5_GivenSeed1234() { var random = new Random(1234); - Assert.AreEqual(Color.FromArgb(51, 21, 21, 229), random.NextColorArgb()); + Assert.That(random.NextColorArgb(), Is.EqualTo(Color.FromArgb(51, 21, 21, 229))); } - [TestMethod] + [Test] public void NextColorArgb_ShouldThrow_GivenNull() { - Random? random = null; - Assert.ThrowsException(() => random!.NextColorArgb()); + Random random = null!; + Assert.Throws(() => random.NextColorArgb()); } - [TestMethod] + [Test] public void NextColorRgb_ShouldReturn1515e5_GivenSeed1234() { var random = new Random(1234); - Assert.AreEqual(Color.FromArgb(255, 21, 21, 229), random.NextColorRgb()); + Assert.That(random.NextColorRgb(), Is.EqualTo(Color.FromArgb(255, 21, 21, 229))); } - [TestMethod] + [Test] public void NextColorRgb_ShouldThrow_GivenNull() { - Random? random = null; - Assert.ThrowsException(() => random!.NextColorRgb()); + Random random = null!; + Assert.Throws(() => random.NextColorRgb()); } } diff --git a/X10D.Tests/src/Drawing/SizeTests.cs b/X10D.Tests/src/Drawing/SizeTests.cs index 8dbd957..e72bbbb 100644 --- a/X10D.Tests/src/Drawing/SizeTests.cs +++ b/X10D.Tests/src/Drawing/SizeTests.cs @@ -1,42 +1,51 @@ using System.Drawing; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Drawing; namespace X10D.Tests.Drawing; -[TestClass] +[TestFixture] public class SizeTests { - [TestMethod] + [Test] public void ToPoint_ShouldReturnPoint_WithEquivalentMembers() { var random = new Random(); var size = new Size(random.Next(), random.Next()); var point = size.ToPoint(); - Assert.AreEqual(size.Width, point.X); - Assert.AreEqual(size.Height, point.Y); + Assert.Multiple(() => + { + Assert.That(point.X, Is.EqualTo(size.Width)); + Assert.That(point.Y, Is.EqualTo(size.Height)); + }); } - [TestMethod] + [Test] public void ToPointF_ShouldReturnPoint_WithEquivalentMembers() { var random = new Random(); var size = new Size(random.Next(), random.Next()); var point = size.ToPointF(); - Assert.AreEqual(size.Width, point.X, 1e-6f); - Assert.AreEqual(size.Height, point.Y, 1e-6f); + Assert.Multiple(() => + { + Assert.That(point.X, Is.EqualTo(size.Width).Within(1e-6f)); + Assert.That(point.Y, Is.EqualTo(size.Height).Within(1e-6f)); + }); } - [TestMethod] + [Test] public void ToVector2_ShouldReturnVector_WithEquivalentMembers() { var random = new Random(); var point = new Size(random.Next(), random.Next()); var size = point.ToVector2(); - Assert.AreEqual(point.Width, size.X, 1e-6f); - Assert.AreEqual(point.Height, size.Y, 1e-6f); + Assert.Multiple(() => + { + Assert.That(size.X, Is.EqualTo(point.Width).Within(1e-6f)); + Assert.That(size.Y, Is.EqualTo(point.Height).Within(1e-6f)); + }); } } diff --git a/X10D.Tests/src/Drawing/SphereTests.cs b/X10D.Tests/src/Drawing/SphereTests.cs index 3457b35..90a4afa 100644 --- a/X10D.Tests/src/Drawing/SphereTests.cs +++ b/X10D.Tests/src/Drawing/SphereTests.cs @@ -1,135 +1,133 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Drawing; namespace X10D.Tests.Drawing; -[TestClass] +[TestFixture] public class SphereTests { - [TestMethod] + [Test] public void Circumference_ShouldBe2PiRadius_GivenUnitCircle() { var unitSphere = Sphere.Unit; - Assert.AreEqual(2.0f * MathF.PI * unitSphere.Radius, unitSphere.Circumference, 1e-6f); + Assert.That(unitSphere.Circumference, Is.EqualTo(2.0f * MathF.PI * unitSphere.Radius).Within(1e-6f)); } - [TestMethod] + [Test] public void CompareTo_ShouldBeNegativeOne_GivenUnitCircleAndEmpty() { - Assert.AreEqual(-1, Sphere.Empty.CompareTo(Sphere.Unit)); + Assert.That(Sphere.Empty.CompareTo(Sphere.Unit), Is.EqualTo(-1)); } - [TestMethod] + [Test] public void CompareTo_ShouldBeOne_GivenUnitCircleAndEmpty() { - Assert.AreEqual(1, Sphere.Unit.CompareTo(Sphere.Empty)); + Assert.That(Sphere.Unit.CompareTo(Sphere.Empty), Is.EqualTo(1)); } - [TestMethod] + [Test] public void CompareTo_ShouldBeNegativeOne_GivenEmptyCircleAndUnitCircleAsObject() { - Assert.AreEqual(-1, Sphere.Empty.CompareTo((object)Sphere.Unit)); + Assert.That(Sphere.Empty.CompareTo((object)Sphere.Unit), Is.EqualTo(-1)); } - [TestMethod] + [Test] public void CompareTo_ShouldBeOne_GivenNull() { - Assert.AreEqual(1, Sphere.Unit.CompareTo(null)); + Assert.That(Sphere.Unit.CompareTo(null), Is.EqualTo(1)); } - [TestMethod] + [Test] public void CompareTo_ShouldBeZero_GivenUnitCircle() { var unitCircle = Sphere.Unit; - Assert.AreEqual(0, unitCircle.CompareTo(unitCircle)); + Assert.That(unitCircle.CompareTo(unitCircle), Is.Zero); } - [TestMethod] + [Test] public void CompareTo_ShouldThrowArgumentException_GivenInvalidType() { - Assert.ThrowsException(() => Sphere.Unit.CompareTo(new object())); + Assert.Throws(() => _ = Sphere.Unit.CompareTo(new object())); } - [TestMethod] + [Test] public void Diameter_ShouldBe2_GivenUnitSphere() { - Assert.AreEqual(2.0f, Sphere.Unit.Diameter, 1e-6f); + Assert.That(Sphere.Unit.Diameter, Is.EqualTo(2.0f).Within(1e-6f)); } - [TestMethod] + [Test] public void Equals_ShouldBeTrue_GivenTwoUnitCircles() { var unitCircle1 = Sphere.Unit; var unitCircle2 = Sphere.Unit; - Assert.AreEqual(unitCircle1, unitCircle2); - Assert.IsTrue(unitCircle1 == unitCircle2); - Assert.IsFalse(unitCircle1 != unitCircle2); + + Assert.Multiple(() => + { + Assert.That(unitCircle2, Is.EqualTo(unitCircle1)); + Assert.That(unitCircle1, Is.EqualTo(unitCircle2)); + }); } - [TestMethod] + [Test] public void Equals_ShouldBeFalse_GivenDifferentObjects() { - Assert.IsFalse(Sphere.Unit.Equals(null)); + Assert.That(Sphere.Unit, Is.Not.EqualTo(null)); } - [TestMethod] + [Test] public void Equals_ShouldBeFalse_GivenDifferentCircles() { - Assert.AreNotEqual(Sphere.Unit, Sphere.Empty); - Assert.IsFalse(Sphere.Unit == Sphere.Empty); - Assert.IsTrue(Sphere.Unit != Sphere.Empty); + Assert.That(Sphere.Empty, Is.Not.EqualTo(Sphere.Unit)); + Assert.That(Sphere.Unit, Is.Not.EqualTo(Sphere.Empty)); } - [TestMethod] + [Test] public void GetHashCode_ShouldBeCorrect_GivenEmptyCircle() { // this test is pretty pointless, it exists only for code coverage purposes int hashCode = Sphere.Empty.GetHashCode(); - Assert.AreEqual(hashCode, Sphere.Empty.GetHashCode()); + Assert.That(Sphere.Empty.GetHashCode(), Is.EqualTo(hashCode)); } - [TestMethod] + [Test] public void GetHashCode_ShouldBeCorrect_GivenUnitCircle() { // this test is pretty pointless, it exists only for code coverage purposes int hashCode = Sphere.Unit.GetHashCode(); - Assert.AreEqual(hashCode, Sphere.Unit.GetHashCode()); + Assert.That(Sphere.Unit.GetHashCode(), Is.EqualTo(hashCode)); } - [TestMethod] + [Test] public void op_GreaterThan_True_GivenUnitAndEmptyCircle() { - Assert.IsTrue(Sphere.Unit > Sphere.Empty); - Assert.IsTrue(Sphere.Unit >= Sphere.Empty); - Assert.IsFalse(Sphere.Unit < Sphere.Empty); - Assert.IsFalse(Sphere.Unit <= Sphere.Empty); + Assert.That(Sphere.Unit, Is.GreaterThan(Sphere.Empty)); + Assert.That(Sphere.Unit, Is.GreaterThanOrEqualTo(Sphere.Empty)); } - [TestMethod] + [Test] public void op_LessThan_True_GivenEmptyAndUnitCircle() { - Assert.IsTrue(Sphere.Empty < Sphere.Unit); - Assert.IsTrue(Sphere.Empty <= Sphere.Unit); - Assert.IsFalse(Sphere.Empty > Sphere.Unit); - Assert.IsFalse(Sphere.Empty >= Sphere.Unit); + Assert.That(Sphere.Empty, Is.LessThan(Sphere.Unit)); + Assert.That(Sphere.Empty, Is.LessThanOrEqualTo(Sphere.Unit)); } - [TestMethod] + [Test] public void Radius_ShouldBe0_GivenEmptySphere() { - Assert.AreEqual(0, Sphere.Empty.Radius); + Assert.That(Sphere.Empty.Radius, Is.Zero); } - [TestMethod] + [Test] public void Radius_ShouldBe1_GivenUnitSphere() { - Assert.AreEqual(1, Sphere.Unit.Radius); + Assert.That(Sphere.Unit.Radius, Is.EqualTo(1)); } - [TestMethod] + [Test] public void Volume_ShouldBe4Over3TimesPi_GivenUnitCircle() { var unitSphere = Sphere.Unit; - Assert.AreEqual(4.0f / 3.0f * MathF.PI, unitSphere.Volume); + Assert.That(unitSphere.Volume, Is.EqualTo(4.0f / 3.0f * MathF.PI)); } } diff --git a/X10D.Tests/src/Hosting/ServiceCollectionTests.cs b/X10D.Tests/src/Hosting/ServiceCollectionTests.cs index a4c673c..0ce3fd2 100644 --- a/X10D.Tests/src/Hosting/ServiceCollectionTests.cs +++ b/X10D.Tests/src/Hosting/ServiceCollectionTests.cs @@ -1,14 +1,14 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Hosting.DependencyInjection; namespace X10D.Tests.Hosting; -[TestClass] +[TestFixture] public class ServiceCollectionTests { - [TestMethod] + [Test] public void AddHostedSingleton_ShouldRegisterServiceAsSingletonAndAsHostedService() { var services = new ServiceCollection(); @@ -19,14 +19,17 @@ public class ServiceCollectionTests var service = serviceProvider.GetService(); var hostedService = serviceProvider.GetService(); - Assert.IsNotNull(service); - Assert.IsNotNull(hostedService); - Assert.IsInstanceOfType(service, typeof(TestService)); - Assert.IsInstanceOfType(hostedService, typeof(TestService)); - Assert.AreSame(service, hostedService); + Assert.Multiple(() => + { + Assert.That(service, Is.Not.Null); + Assert.That(hostedService, Is.Not.Null); + Assert.IsAssignableFrom(service); + Assert.IsAssignableFrom(hostedService); + Assert.That(hostedService, Is.SameAs(service)); + }); } - [TestMethod] + [Test] public void AddHostedSingleton_ShouldRegisterServiceTypeAsSingletonAndAsHostedService() { var services = new ServiceCollection(); @@ -37,11 +40,14 @@ public class ServiceCollectionTests var service = serviceProvider.GetService(); var hostedService = serviceProvider.GetService(); - Assert.IsNotNull(service); - Assert.IsNotNull(hostedService); - Assert.IsInstanceOfType(service, typeof(TestService)); - Assert.IsInstanceOfType(hostedService, typeof(TestService)); - Assert.AreSame(service, hostedService); + Assert.Multiple(() => + { + Assert.That(service, Is.Not.Null); + Assert.That(hostedService, Is.Not.Null); + Assert.IsAssignableFrom(service); + Assert.IsAssignableFrom(hostedService); + Assert.That(hostedService, Is.SameAs(service)); + }); } private sealed class TestService : IHostedService diff --git a/X10D.Tests/src/IO/BooleanTests.cs b/X10D.Tests/src/IO/BooleanTests.cs index 8b4701d..86ebdd9 100644 --- a/X10D.Tests/src/IO/BooleanTests.cs +++ b/X10D.Tests/src/IO/BooleanTests.cs @@ -1,32 +1,32 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; -[TestClass] +[TestFixture] public class BooleanTests { - [TestMethod] + [Test] public void GetBytes_ReturnsArrayContaining1() { const bool value = true; CollectionAssert.AreEqual(new byte[] {1}, value.GetBytes()); } - [TestMethod] + [Test] public void TryWriteBytes_ReturnsTrue_FillsSpanContaining1_GivenLargeEnoughSpan() { const bool value = true; Span buffer = stackalloc byte[1]; - Assert.IsTrue(value.TryWriteBytes(buffer)); + Assert.That(value.TryWriteBytes(buffer)); CollectionAssert.AreEqual(new byte[] {1}, buffer.ToArray()); } - [TestMethod] + [Test] public void TryWriteBytes_ReturnsFalse_GivenSmallSpan() { const bool value = true; Span buffer = stackalloc byte[0]; - Assert.IsFalse(value.TryWriteBytes(buffer)); + Assert.That(value.TryWriteBytes(buffer), Is.False); } } diff --git a/X10D.Tests/src/IO/ByteTests.cs b/X10D.Tests/src/IO/ByteTests.cs index 47c14cb..4c13411 100644 --- a/X10D.Tests/src/IO/ByteTests.cs +++ b/X10D.Tests/src/IO/ByteTests.cs @@ -1,32 +1,32 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; -[TestClass] +[TestFixture] public class ByteTests { - [TestMethod] + [Test] public void GetBytes_ReturnsArrayContainingItself() { const byte value = 0xFF; CollectionAssert.AreEqual(new[] {value}, value.GetBytes()); } - [TestMethod] + [Test] public void TryWriteBytes_ReturnsTrue_FillsSpanContainingItself_GivenLargeEnoughSpan() { const byte value = 0xFF; Span buffer = stackalloc byte[1]; - Assert.IsTrue(value.TryWriteBytes(buffer)); + Assert.That(value.TryWriteBytes(buffer)); CollectionAssert.AreEqual(new[] {value}, buffer.ToArray()); } - [TestMethod] + [Test] public void TryWriteBytes_ReturnsFalse_GivenSmallSpan() { const byte value = 0x0F; Span buffer = stackalloc byte[0]; - Assert.IsFalse(value.TryWriteBytes(buffer)); + Assert.That(value.TryWriteBytes(buffer), Is.False); } } diff --git a/X10D.Tests/src/IO/DirectoryInfoTests.cs b/X10D.Tests/src/IO/DirectoryInfoTests.cs index aa3e46e..62df128 100644 --- a/X10D.Tests/src/IO/DirectoryInfoTests.cs +++ b/X10D.Tests/src/IO/DirectoryInfoTests.cs @@ -1,19 +1,19 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; -[TestClass] +[TestFixture] public class DirectoryInfoTests { - [TestMethod] + [Test] public void Clear_ShouldClear_GivenValidDirectory() { string tempDirectoryPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); var tempDirectory = new DirectoryInfo(tempDirectoryPath); tempDirectory.Create(); - Assert.IsTrue(tempDirectory.Exists); + Assert.That(tempDirectory.Exists); var file = new FileInfo(Path.Combine(tempDirectory.FullName, "file")); file.Create().Close(); @@ -24,34 +24,42 @@ public class DirectoryInfoTests var childFile = new FileInfo(Path.Combine(childDirectory.FullName, "childFile")); childFile.Create().Close(); - Assert.AreEqual(1, tempDirectory.GetFiles().Length); - Assert.AreEqual(1, tempDirectory.GetDirectories().Length); + Assert.Multiple(() => + { + Assert.That(tempDirectory.GetFiles(), Has.Length.EqualTo(1)); + Assert.That(tempDirectory.GetDirectories(), Has.Length.EqualTo(1)); + }); + tempDirectory.Clear(); - Assert.AreEqual(0, tempDirectory.GetFiles().Length); - Assert.AreEqual(0, tempDirectory.GetDirectories().Length); - Assert.IsTrue(tempDirectory.Exists); + + Assert.Multiple(() => + { + Assert.That(tempDirectory.GetFiles(), Is.Empty); + Assert.That(tempDirectory.GetDirectories(), Is.Empty); + Assert.That(tempDirectory.Exists); + }); tempDirectory.Delete(); } - [TestMethod] + [Test] public void Clear_ShouldThrowArgumentNullException_GivenNull() { - Assert.ThrowsException(() => ((DirectoryInfo?)null)!.Clear()); + Assert.Throws(() => ((DirectoryInfo?)null)!.Clear()); } - [TestMethod] + [Test] public void Clear_ShouldThrowDirectoryNotFoundException_GivenInvalidDirectory() { var directory = new DirectoryInfo(@"123:/@12#3"); - Assert.ThrowsException(() => directory.Clear()); + Assert.Throws(() => directory.Clear()); } - [TestMethod] + [Test] public void Clear_ShouldThrowDirectoryNotFoundException_GivenNonExistentDirectory() { var directory = new DirectoryInfo(@"/@12#3"); - Assert.IsFalse(directory.Exists); - Assert.ThrowsException(() => directory.Clear()); + Assert.That(directory.Exists, Is.False); + Assert.Throws(() => directory.Clear()); } } diff --git a/X10D.Tests/src/IO/DoubleTests.cs b/X10D.Tests/src/IO/DoubleTests.cs index 616fd79..c327e9f 100644 --- a/X10D.Tests/src/IO/DoubleTests.cs +++ b/X10D.Tests/src/IO/DoubleTests.cs @@ -1,12 +1,12 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; -[TestClass] +[TestFixture] public class DoubleTests { - [TestMethod] + [Test] public void GetBytes_ReturnsCorrectValue() { const double value = 42.5; @@ -16,7 +16,7 @@ public class DoubleTests CollectionAssert.AreEqual(bytes, value.GetBytes()); } - [TestMethod] + [Test] public void GetBytes_ReturnsCorrectValue_WithEndianness() { const double value = 42.5; @@ -27,7 +27,7 @@ public class DoubleTests CollectionAssert.AreEqual(bigEndian, value.GetBytes(Endianness.BigEndian)); } - [TestMethod] + [Test] public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan() { const double value = 42.5; @@ -36,11 +36,11 @@ public class DoubleTests : new byte[] {0x40, 0x45, 0x40, 0, 0, 0, 0, 0}; Span buffer = stackalloc byte[8]; - Assert.IsTrue(value.TryWriteBytes(buffer)); + Assert.That(value.TryWriteBytes(buffer)); CollectionAssert.AreEqual(bytes, buffer.ToArray()); } - [TestMethod] + [Test] public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan_WithEndianness() { const double value = 42.5; @@ -49,18 +49,18 @@ public class DoubleTests Span buffer = stackalloc byte[8]; - Assert.IsTrue(value.TryWriteBytes(buffer, Endianness.LittleEndian)); + Assert.That(value.TryWriteBytes(buffer, Endianness.LittleEndian)); CollectionAssert.AreEqual(littleEndian, buffer.ToArray()); - Assert.IsTrue(value.TryWriteBytes(buffer, Endianness.BigEndian)); + Assert.That(value.TryWriteBytes(buffer, Endianness.BigEndian)); CollectionAssert.AreEqual(bigEndian, buffer.ToArray()); } - [TestMethod] + [Test] public void TryWriteBytes_ReturnsFalse_GivenSmallSpan() { const double value = 42.5; Span buffer = stackalloc byte[0]; - Assert.IsFalse(value.TryWriteBytes(buffer)); + Assert.That(value.TryWriteBytes(buffer), Is.False); } } diff --git a/X10D.Tests/src/IO/FileInfoTests.cs b/X10D.Tests/src/IO/FileInfoTests.cs index a1047ba..b182b94 100644 --- a/X10D.Tests/src/IO/FileInfoTests.cs +++ b/X10D.Tests/src/IO/FileInfoTests.cs @@ -1,23 +1,23 @@ using System.Security.Cryptography; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; -[TestClass] +[TestFixture] public class FileInfoTests { - [TestMethod] + [Test] public void GetHashSha1ShouldBeCorrect() { - string fileName = $"temp.{DateTimeOffset.Now.ToUnixTimeSeconds()}.bin"; + var fileName = $"temp.{DateTimeOffset.Now.ToUnixTimeSeconds()}.bin"; if (File.Exists(fileName)) { Assert.Fail("Temporary file already exists"); } File.WriteAllText(fileName, "Hello World"); - Assert.IsTrue(File.Exists(fileName)); + Assert.That(File.Exists(fileName)); // SHA-1 byte[] expectedHash = @@ -37,17 +37,17 @@ public class FileInfoTests } } - [TestMethod] + [Test] public void TryWriteHashSha1ShouldBeCorrect() { - string fileName = $"temp.{DateTimeOffset.Now.ToUnixTimeSeconds()}.bin"; + var fileName = $"temp.{DateTimeOffset.Now.ToUnixTimeSeconds()}.bin"; if (File.Exists(fileName)) { Assert.Fail("Temporary file already exists"); } File.WriteAllText(fileName, "Hello World"); - Assert.IsTrue(File.Exists(fileName)); + Assert.That(File.Exists(fileName)); // SHA-1 byte[] expectedHash = @@ -60,7 +60,7 @@ public class FileInfoTests { Span hash = stackalloc byte[20]; new FileInfo(fileName).TryWriteHash(hash, out int bytesWritten); - Assert.AreEqual(expectedHash.Length, bytesWritten); + Assert.That(bytesWritten, Is.EqualTo(expectedHash.Length)); CollectionAssert.AreEqual(expectedHash, hash.ToArray()); } finally @@ -69,25 +69,25 @@ public class FileInfoTests } } - [TestMethod] + [Test] public void GetHashNullShouldThrow() { // any HashAlgorithm will do, but SHA1 is used above. so to remain consistent, we use it here - Assert.ThrowsException(() => ((FileInfo?)null)!.GetHash()); - Assert.ThrowsException(() => ((FileInfo?)null)!.TryWriteHash(Span.Empty, out _)); + Assert.Throws(() => _ = ((FileInfo?)null)!.GetHash()); + Assert.Throws(() => ((FileInfo?)null)!.TryWriteHash(Span.Empty, out _)); } - [TestMethod] + [Test] public void GetHashInvalidFileShouldThrow() { - string fileName = $"temp.{DateTimeOffset.Now.ToUnixTimeSeconds()}.bin"; + var fileName = $"temp.{DateTimeOffset.Now.ToUnixTimeSeconds()}.bin"; if (File.Exists(fileName)) { Assert.Fail("Temporary file already exists"); } // any HashAlgorithm will do, but SHA1 is used above. so to remain consistent, we use it here - Assert.ThrowsException(() => new FileInfo(fileName).GetHash()); - Assert.ThrowsException(() => new FileInfo(fileName).TryWriteHash(Span.Empty, out _)); + Assert.Throws(() => _ = new FileInfo(fileName).GetHash()); + Assert.Throws(() => new FileInfo(fileName).TryWriteHash(Span.Empty, out _)); } } diff --git a/X10D.Tests/src/IO/Int16Tests.cs b/X10D.Tests/src/IO/Int16Tests.cs index 346e95a..ae4dcbe 100644 --- a/X10D.Tests/src/IO/Int16Tests.cs +++ b/X10D.Tests/src/IO/Int16Tests.cs @@ -1,12 +1,12 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; -[TestClass] +[TestFixture] public class Int16Tests { - [TestMethod] + [Test] public void GetBytes_ReturnsCorrectValue() { const short value = 0x0F; @@ -14,7 +14,7 @@ public class Int16Tests CollectionAssert.AreEqual(bytes, value.GetBytes()); } - [TestMethod] + [Test] public void GetBytes_ReturnsCorrectValue_WithEndianness() { const short value = 0x0F; @@ -25,18 +25,18 @@ public class Int16Tests CollectionAssert.AreEqual(bigEndian, value.GetBytes(Endianness.BigEndian)); } - [TestMethod] + [Test] public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan() { const short value = 0x0F; byte[] bytes = BitConverter.IsLittleEndian ? new byte[] {0x0F, 0} : new byte[] {0, 0x0F}; Span buffer = stackalloc byte[2]; - Assert.IsTrue(value.TryWriteBytes(buffer)); + Assert.That(value.TryWriteBytes(buffer)); CollectionAssert.AreEqual(bytes, buffer.ToArray()); } - [TestMethod] + [Test] public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan_WithEndianness() { const short value = 0x0F; @@ -45,18 +45,18 @@ public class Int16Tests Span buffer = stackalloc byte[2]; - Assert.IsTrue(value.TryWriteBytes(buffer, Endianness.LittleEndian)); + Assert.That(value.TryWriteBytes(buffer, Endianness.LittleEndian)); CollectionAssert.AreEqual(littleEndian, buffer.ToArray()); - Assert.IsTrue(value.TryWriteBytes(buffer, Endianness.BigEndian)); + Assert.That(value.TryWriteBytes(buffer, Endianness.BigEndian)); CollectionAssert.AreEqual(bigEndian, buffer.ToArray()); } - [TestMethod] + [Test] public void TryWriteBytes_ReturnsFalse_GivenSmallSpan() { const short value = 0x0F; Span buffer = stackalloc byte[0]; - Assert.IsFalse(value.TryWriteBytes(buffer)); + Assert.That(value.TryWriteBytes(buffer), Is.False); } } diff --git a/X10D.Tests/src/IO/Int32Tests.cs b/X10D.Tests/src/IO/Int32Tests.cs index 7135b7c..d69b2be 100644 --- a/X10D.Tests/src/IO/Int32Tests.cs +++ b/X10D.Tests/src/IO/Int32Tests.cs @@ -1,12 +1,12 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; -[TestClass] +[TestFixture] public class Int32Tests { - [TestMethod] + [Test] public void GetBytes_ReturnsCorrectValue() { const int value = 0x0F; @@ -14,7 +14,7 @@ public class Int32Tests CollectionAssert.AreEqual(bytes, value.GetBytes()); } - [TestMethod] + [Test] public void GetBytes_ReturnsCorrectValue_WithEndianness() { const int value = 0x0F; @@ -25,18 +25,18 @@ public class Int32Tests CollectionAssert.AreEqual(bigEndian, value.GetBytes(Endianness.BigEndian)); } - [TestMethod] + [Test] public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan() { const int value = 0x0F; byte[] bytes = BitConverter.IsLittleEndian ? new byte[] {0x0F, 0, 0, 0} : new byte[] {0, 0, 0, 0x0F}; Span buffer = stackalloc byte[4]; - Assert.IsTrue(value.TryWriteBytes(buffer)); + Assert.That(value.TryWriteBytes(buffer)); CollectionAssert.AreEqual(bytes, buffer.ToArray()); } - [TestMethod] + [Test] public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan_WithEndianness() { const int value = 0x0F; @@ -45,18 +45,18 @@ public class Int32Tests Span buffer = stackalloc byte[4]; - Assert.IsTrue(value.TryWriteBytes(buffer, Endianness.LittleEndian)); + Assert.That(value.TryWriteBytes(buffer, Endianness.LittleEndian)); CollectionAssert.AreEqual(littleEndian, buffer.ToArray()); - Assert.IsTrue(value.TryWriteBytes(buffer, Endianness.BigEndian)); + Assert.That(value.TryWriteBytes(buffer, Endianness.BigEndian)); CollectionAssert.AreEqual(bigEndian, buffer.ToArray()); } - [TestMethod] + [Test] public void TryWriteBytes_ReturnsFalse_GivenSmallSpan() { const int value = 0x0F; Span buffer = stackalloc byte[0]; - Assert.IsFalse(value.TryWriteBytes(buffer)); + Assert.That(value.TryWriteBytes(buffer), Is.False); } } diff --git a/X10D.Tests/src/IO/Int64Tests.cs b/X10D.Tests/src/IO/Int64Tests.cs index 1f7623b..ccd3673 100644 --- a/X10D.Tests/src/IO/Int64Tests.cs +++ b/X10D.Tests/src/IO/Int64Tests.cs @@ -1,12 +1,12 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; -[TestClass] +[TestFixture] public class Int64Tests { - [TestMethod] + [Test] public void GetBytes_ReturnsCorrectValue() { const long value = 0x0F; @@ -16,7 +16,7 @@ public class Int64Tests CollectionAssert.AreEqual(bytes, value.GetBytes()); } - [TestMethod] + [Test] public void GetBytes_ReturnsCorrectValue_WithEndianness() { const long value = 0x0F; @@ -27,7 +27,7 @@ public class Int64Tests CollectionAssert.AreEqual(bigEndian, value.GetBytes(Endianness.BigEndian)); } - [TestMethod] + [Test] public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan() { const long value = 0x0F; @@ -36,11 +36,11 @@ public class Int64Tests : new byte[] {0, 0, 0, 0, 0, 0, 0, 0x0F}; Span buffer = stackalloc byte[8]; - Assert.IsTrue(value.TryWriteBytes(buffer)); + Assert.That(value.TryWriteBytes(buffer)); CollectionAssert.AreEqual(bytes, buffer.ToArray()); } - [TestMethod] + [Test] public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan_WithEndianness() { const long value = 0x0F; @@ -49,18 +49,18 @@ public class Int64Tests Span buffer = stackalloc byte[8]; - Assert.IsTrue(value.TryWriteBytes(buffer, Endianness.LittleEndian)); + Assert.That(value.TryWriteBytes(buffer, Endianness.LittleEndian)); CollectionAssert.AreEqual(littleEndian, buffer.ToArray()); - Assert.IsTrue(value.TryWriteBytes(buffer, Endianness.BigEndian)); + Assert.That(value.TryWriteBytes(buffer, Endianness.BigEndian)); CollectionAssert.AreEqual(bigEndian, buffer.ToArray()); } - [TestMethod] + [Test] public void TryWriteBytes_ReturnsFalse_GivenSmallSpan() { const long value = 0x0F; Span buffer = stackalloc byte[0]; - Assert.IsFalse(value.TryWriteBytes(buffer)); + Assert.That(value.TryWriteBytes(buffer), Is.False); } } diff --git a/X10D.Tests/src/IO/ListOfByteTests.cs b/X10D.Tests/src/IO/ListOfByteTests.cs index 9fe2056..17bd66d 100644 --- a/X10D.Tests/src/IO/ListOfByteTests.cs +++ b/X10D.Tests/src/IO/ListOfByteTests.cs @@ -1,27 +1,27 @@ using System.Text; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; -[TestClass] +[TestFixture] public class ListOfByteTests { - [TestMethod] + [Test] public void AsString_ShouldReturnBytes_GivenBytes() { var bytes = new byte[] {0x01, 0x02, 0x03, 0x04, 0x05}; - Assert.AreEqual("01-02-03-04-05", bytes.AsString()); + Assert.That(bytes.AsString(), Is.EqualTo("01-02-03-04-05")); } - [TestMethod] + [Test] public void AsString_ShouldThrow_GivenNullArray() { byte[]? bytes = null; - Assert.ThrowsException(() => bytes!.AsString()); + Assert.Throws(() => bytes!.AsString()); } - [TestMethod] + [Test] public void ToDouble_ShouldReturnDouble_GivenBytes() { var bytes = new byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x7A, 0x40}; @@ -31,59 +31,59 @@ public class ListOfByteTests Array.Reverse(bytes); } - Assert.AreEqual(420.0, bytes.ToDouble(), 1e-6); + Assert.That(bytes.ToDouble(), Is.EqualTo(420.0).Within(1e-6)); } - [TestMethod] + [Test] public void ToDouble_ShouldThrow_GivenNullArray() { - byte[]? bytes = null; - Assert.ThrowsException(() => bytes!.ToDouble()); + byte[] bytes = null!; + Assert.Throws(() => bytes.ToDouble()); } - [TestMethod] + [Test] public void ToInt16_ShouldReturnInt16_GivenBytes() { var bytes = new byte[] {0xA4, 0x01}; - Assert.AreEqual(420, bytes.ToInt16()); + Assert.That(bytes.ToInt16(), Is.EqualTo(420)); } - [TestMethod] + [Test] public void ToInt16_ShouldThrow_GivenNullArray() { - byte[]? bytes = null; - Assert.ThrowsException(() => bytes!.ToInt16()); + byte[] bytes = null!; + Assert.Throws(() => bytes.ToInt16()); } - [TestMethod] + [Test] public void ToInt32_ShouldReturnInt32_GivenBytes() { var bytes = new byte[] {0xA4, 0x01, 0x00, 0x00}; - Assert.AreEqual(420, bytes.ToInt32()); + Assert.That(bytes.ToInt32(), Is.EqualTo(420)); } - [TestMethod] + [Test] public void ToInt32_ShouldThrow_GivenNullArray() { - byte[]? bytes = null; - Assert.ThrowsException(() => bytes!.ToInt32()); + byte[] bytes = null!; + Assert.Throws(() => bytes.ToInt32()); } - [TestMethod] + [Test] public void ToInt64_ShouldReturnInt32_GivenBytes() { var bytes = new byte[] {0xA4, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; - Assert.AreEqual(420L, bytes.ToInt64()); + Assert.That(bytes.ToInt64(), Is.EqualTo(420L)); } - [TestMethod] + [Test] public void ToInt64_ShouldThrow_GivenNullArray() { byte[]? bytes = null; - Assert.ThrowsException(() => bytes!.ToInt64()); + Assert.Throws(() => bytes!.ToInt64()); } - [TestMethod] + [Test] public void ToSingle_ShouldReturnDouble_GivenBytes() { var bytes = new byte[] {0x00, 0x00, 0xD2, 0x43}; @@ -93,76 +93,76 @@ public class ListOfByteTests Array.Reverse(bytes); } - Assert.AreEqual(420.0, bytes.ToSingle(), 1e-6); + Assert.That(bytes.ToSingle(), Is.EqualTo(420.0).Within(1e-6)); } - [TestMethod] + [Test] public void ToSingle_ShouldThrow_GivenNullArray() { - byte[]? bytes = null; - Assert.ThrowsException(() => bytes!.ToSingle()); + byte[] bytes = null!; + Assert.Throws(() => bytes.ToSingle()); } - [TestMethod] + [Test] public void ToString_ShouldReturnHelloWorld_GivenUTF8() { var bytes = new byte[] {0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64}; - Assert.AreEqual("Hello World", bytes.ToString(Encoding.UTF8)); + Assert.That(bytes.ToString(Encoding.UTF8), Is.EqualTo("Hello World")); } - [TestMethod] + [Test] public void ToString_ShouldThrow_GivenNullArray() { - byte[]? bytes = null; - Assert.ThrowsException(() => bytes!.ToString(Encoding.UTF8)); + byte[] bytes = null!; + Assert.Throws(() => bytes.ToString(Encoding.UTF8)); } - [TestMethod] + [Test] public void ToString_ShouldThrow_GivenNullEncoding() { var bytes = new byte[] {0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64}; - Assert.ThrowsException(() => bytes.ToString(null!)); + Assert.Throws(() => bytes.ToString(null!)); } - [TestMethod] + [Test] public void ToUInt16_ShouldReturnInt16_GivenBytes() { var bytes = new byte[] {0xA4, 0x01}; - Assert.AreEqual((ushort)420, bytes.ToUInt16()); + Assert.That(bytes.ToUInt16(), Is.EqualTo((ushort)420)); } - [TestMethod] + [Test] public void ToUInt16_ShouldThrow_GivenNullArray() { - byte[]? bytes = null; - Assert.ThrowsException(() => bytes!.ToUInt16()); + byte[] bytes = null!; + Assert.Throws(() => bytes.ToUInt16()); } - [TestMethod] + [Test] public void ToUInt32_ShouldReturnInt32_GivenBytes() { var bytes = new byte[] {0xA4, 0x01, 0x00, 0x00}; - Assert.AreEqual(420U, bytes.ToUInt32()); + Assert.That(bytes.ToUInt32(), Is.EqualTo(420U)); } - [TestMethod] + [Test] public void ToUInt32_ShouldThrow_GivenNullArray() { byte[]? bytes = null; - Assert.ThrowsException(() => bytes!.ToUInt32()); + Assert.Throws(() => bytes!.ToUInt32()); } - [TestMethod] + [Test] public void ToUInt64_ShouldReturnInt32_GivenBytes() { var bytes = new byte[] {0xA4, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; - Assert.AreEqual(420UL, bytes.ToUInt64()); + Assert.That(bytes.ToUInt64(), Is.EqualTo(420UL)); } - [TestMethod] + [Test] public void ToUInt64_ShouldThrow_GivenNullArray() { - byte[]? bytes = null; - Assert.ThrowsException(() => bytes!.ToUInt64()); + byte[] bytes = null!; + Assert.Throws(() => bytes.ToUInt64()); } } diff --git a/X10D.Tests/src/IO/SByteTests.cs b/X10D.Tests/src/IO/SByteTests.cs index 8f28976..23143ad 100644 --- a/X10D.Tests/src/IO/SByteTests.cs +++ b/X10D.Tests/src/IO/SByteTests.cs @@ -1,33 +1,33 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; -[TestClass] +[TestFixture] [CLSCompliant(false)] public class SByteTests { - [TestMethod] + [Test] public void GetBytes_ReturnsArrayContainingItself() { const sbyte value = 0x0F; CollectionAssert.AreEqual(new[] {(byte)value}, value.GetBytes()); } - [TestMethod] + [Test] public void TryWriteBytes_ReturnsTrue_FillsSpanContainingItself_GivenLargeEnoughSpan() { const sbyte value = 0x0F; Span buffer = stackalloc byte[1]; - Assert.IsTrue(value.TryWriteBytes(buffer)); + Assert.That(value.TryWriteBytes(buffer)); CollectionAssert.AreEqual(new[] {(byte)value}, buffer.ToArray()); } - [TestMethod] + [Test] public void TryWriteBytes_ReturnsFalse_GivenSmallSpan() { const sbyte value = 0x0F; Span buffer = stackalloc byte[0]; - Assert.IsFalse(value.TryWriteBytes(buffer)); + Assert.That(value.TryWriteBytes(buffer), Is.False); } } diff --git a/X10D.Tests/src/IO/SingleTests.cs b/X10D.Tests/src/IO/SingleTests.cs index 0bca2ce..b0b1bf3 100644 --- a/X10D.Tests/src/IO/SingleTests.cs +++ b/X10D.Tests/src/IO/SingleTests.cs @@ -1,12 +1,12 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; -[TestClass] +[TestFixture] public class SingleTests { - [TestMethod] + [Test] public void GetBytes_ReturnsCorrectValue() { const float value = 42.5f; @@ -16,7 +16,7 @@ public class SingleTests CollectionAssert.AreEqual(bytes, value.GetBytes()); } - [TestMethod] + [Test] public void GetBytes_ReturnsCorrectValue_WithEndianness() { const float value = 42.5f; @@ -27,7 +27,7 @@ public class SingleTests CollectionAssert.AreEqual(bigEndian, value.GetBytes(Endianness.BigEndian)); } - [TestMethod] + [Test] public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan() { const float value = 42.5f; @@ -36,11 +36,11 @@ public class SingleTests : new byte[] {0x42, 0x2A, 0, 0}; Span buffer = stackalloc byte[4]; - Assert.IsTrue(value.TryWriteBytes(buffer)); + Assert.That(value.TryWriteBytes(buffer)); CollectionAssert.AreEqual(bytes, buffer.ToArray()); } - [TestMethod] + [Test] public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan_WithEndianness() { const float value = 42.5f; @@ -49,18 +49,18 @@ public class SingleTests Span buffer = stackalloc byte[4]; - Assert.IsTrue(value.TryWriteBytes(buffer, Endianness.LittleEndian)); + Assert.That(value.TryWriteBytes(buffer, Endianness.LittleEndian)); CollectionAssert.AreEqual(littleEndian, buffer.ToArray()); - Assert.IsTrue(value.TryWriteBytes(buffer, Endianness.BigEndian)); + Assert.That(value.TryWriteBytes(buffer, Endianness.BigEndian)); CollectionAssert.AreEqual(bigEndian, buffer.ToArray()); } - [TestMethod] + [Test] public void TryWriteBytes_ReturnsFalse_GivenSmallSpan() { const float value = 42.5f; Span buffer = stackalloc byte[0]; - Assert.IsFalse(value.TryWriteBytes(buffer)); + Assert.That(value.TryWriteBytes(buffer), Is.False); } } diff --git a/X10D.Tests/src/IO/StreamTests.ReadDecimal.cs b/X10D.Tests/src/IO/StreamTests.ReadDecimal.cs index 0c65320..3209443 100644 --- a/X10D.Tests/src/IO/StreamTests.ReadDecimal.cs +++ b/X10D.Tests/src/IO/StreamTests.ReadDecimal.cs @@ -1,29 +1,29 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; public partial class StreamTests { - [TestMethod] + [Test] public void ReadDecimal_ShouldThrowArgumentException_GivenNonReadableStream() { Stream stream = new DummyStream(); - Assert.ThrowsException(() => stream.ReadDecimal()); - Assert.ThrowsException(() => stream.ReadDecimal(Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.ReadDecimal(Endianness.BigEndian)); + Assert.Throws(() => stream.ReadDecimal()); + Assert.Throws(() => stream.ReadDecimal(Endianness.LittleEndian)); + Assert.Throws(() => stream.ReadDecimal(Endianness.BigEndian)); } - [TestMethod] + [Test] public void ReadDecimal_ShouldThrowArgumentNullException_GivenNullStream() { Stream stream = null!; - Assert.ThrowsException(() => stream.ReadDecimal()); - Assert.ThrowsException(() => stream.ReadDecimal(Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.ReadDecimal(Endianness.BigEndian)); + Assert.Throws(() => stream.ReadDecimal()); + Assert.Throws(() => stream.ReadDecimal(Endianness.LittleEndian)); + Assert.Throws(() => stream.ReadDecimal(Endianness.BigEndian)); } - [TestMethod] + [Test] public void ReadDecimal_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() { // we don't need to enclose this stream in a using declaration, since disposing a @@ -32,10 +32,10 @@ public partial class StreamTests // analyser to trip up and think the stream is disposed by the time the local is captured in // assertion lambda - means this line is fine as it is. please do not change. Stream stream = Stream.Null; - Assert.ThrowsException(() => stream.ReadDecimal((Endianness)(-1))); + Assert.Throws(() => stream.ReadDecimal((Endianness)(-1))); } - [TestMethod] + [Test] public void ReadDecimal_ShouldReadBigEndian_GivenBigEndian() { using var stream = new MemoryStream(); @@ -49,11 +49,14 @@ public partial class StreamTests const decimal expected = 420.0m; decimal actual = stream.ReadDecimal(Endianness.BigEndian); - Assert.AreEqual(16, stream.Position); - Assert.AreEqual(expected, actual); + Assert.Multiple(() => + { + Assert.That(stream.Position, Is.EqualTo(16)); + Assert.That(actual, Is.EqualTo(expected)); + }); } - [TestMethod] + [Test] public void ReadDecimal_ShouldWriteLittleEndian_GivenLittleEndian() { using var stream = new MemoryStream(); @@ -67,7 +70,10 @@ public partial class StreamTests const decimal expected = 420.0m; decimal actual = stream.ReadDecimal(Endianness.LittleEndian); - Assert.AreEqual(16, stream.Position); - Assert.AreEqual(expected, actual); + Assert.Multiple(() => + { + Assert.That(stream.Position, Is.EqualTo(16)); + Assert.That(actual, Is.EqualTo(expected)); + }); } } diff --git a/X10D.Tests/src/IO/StreamTests.ReadDouble.cs b/X10D.Tests/src/IO/StreamTests.ReadDouble.cs index 352df60..6084984 100644 --- a/X10D.Tests/src/IO/StreamTests.ReadDouble.cs +++ b/X10D.Tests/src/IO/StreamTests.ReadDouble.cs @@ -1,29 +1,29 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; public partial class StreamTests { - [TestMethod] + [Test] public void ReadDouble_ShouldThrowArgumentException_GivenNonReadableStream() { Stream stream = new DummyStream(); - Assert.ThrowsException(() => stream.ReadDouble()); - Assert.ThrowsException(() => stream.ReadDouble(Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.ReadDouble(Endianness.BigEndian)); + Assert.Throws(() => stream.ReadDouble()); + Assert.Throws(() => stream.ReadDouble(Endianness.LittleEndian)); + Assert.Throws(() => stream.ReadDouble(Endianness.BigEndian)); } - [TestMethod] + [Test] public void ReadDouble_ShouldThrowArgumentNullException_GivenNullStream() { Stream stream = null!; - Assert.ThrowsException(() => stream.ReadDouble()); - Assert.ThrowsException(() => stream.ReadDouble(Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.ReadDouble(Endianness.BigEndian)); + Assert.Throws(() => stream.ReadDouble()); + Assert.Throws(() => stream.ReadDouble(Endianness.LittleEndian)); + Assert.Throws(() => stream.ReadDouble(Endianness.BigEndian)); } - [TestMethod] + [Test] public void ReadDouble_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() { // we don't need to enclose this stream in a using declaration, since disposing a @@ -32,10 +32,10 @@ public partial class StreamTests // analyser to trip up and think the stream is disposed by the time the local is captured in // assertion lambda - means this line is fine as it is. please do not change. Stream stream = Stream.Null; - Assert.ThrowsException(() => stream.ReadDouble((Endianness)(-1))); + Assert.Throws(() => stream.ReadDouble((Endianness)(-1))); } - [TestMethod] + [Test] public void ReadDouble_ShouldReadBigEndian_GivenBigEndian() { using var stream = new MemoryStream(); @@ -46,11 +46,11 @@ public partial class StreamTests const double expected = 420.0; double actual = stream.ReadDouble(Endianness.BigEndian); - Assert.AreEqual(8, stream.Position); - Assert.AreEqual(expected, actual); + Assert.That(stream.Position, Is.EqualTo(8)); + Assert.That(actual, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void ReadDouble_ShouldWriteLittleEndian_GivenLittleEndian() { using var stream = new MemoryStream(); @@ -61,7 +61,7 @@ public partial class StreamTests const double expected = 420.0; double actual = stream.ReadDouble(Endianness.LittleEndian); - Assert.AreEqual(8, stream.Position); - Assert.AreEqual(expected, actual); + Assert.That(stream.Position, Is.EqualTo(8)); + Assert.That(actual, Is.EqualTo(expected)); } } diff --git a/X10D.Tests/src/IO/StreamTests.ReadInt16.cs b/X10D.Tests/src/IO/StreamTests.ReadInt16.cs index b41c82a..bdb045c 100644 --- a/X10D.Tests/src/IO/StreamTests.ReadInt16.cs +++ b/X10D.Tests/src/IO/StreamTests.ReadInt16.cs @@ -1,29 +1,29 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; public partial class StreamTests { - [TestMethod] + [Test] public void ReadInt16_ShouldThrowArgumentException_GivenNonReadableStream() { Stream stream = new DummyStream(); - Assert.ThrowsException(() => stream.ReadInt16()); - Assert.ThrowsException(() => stream.ReadInt16(Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.ReadInt16(Endianness.BigEndian)); + Assert.Throws(() => stream.ReadInt16()); + Assert.Throws(() => stream.ReadInt16(Endianness.LittleEndian)); + Assert.Throws(() => stream.ReadInt16(Endianness.BigEndian)); } - [TestMethod] + [Test] public void ReadInt16_ShouldThrowArgumentNullException_GivenNullStream() { Stream stream = null!; - Assert.ThrowsException(() => stream.ReadInt16()); - Assert.ThrowsException(() => stream.ReadInt16(Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.ReadInt16(Endianness.BigEndian)); + Assert.Throws(() => stream.ReadInt16()); + Assert.Throws(() => stream.ReadInt16(Endianness.LittleEndian)); + Assert.Throws(() => stream.ReadInt16(Endianness.BigEndian)); } - [TestMethod] + [Test] public void ReadInt16_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() { // we don't need to enclose this stream in a using declaration, since disposing a @@ -32,10 +32,10 @@ public partial class StreamTests // analyser to trip up and think the stream is disposed by the time the local is captured in // assertion lambda - means this line is fine as it is. please do not change. Stream stream = Stream.Null; - Assert.ThrowsException(() => stream.ReadInt16((Endianness)(-1))); + Assert.Throws(() => stream.ReadInt16((Endianness)(-1))); } - [TestMethod] + [Test] public void ReadInt16_ShouldReadBigEndian_GivenBigEndian() { using var stream = new MemoryStream(); @@ -46,11 +46,11 @@ public partial class StreamTests const short expected = 420; short actual = stream.ReadInt16(Endianness.BigEndian); - Assert.AreEqual(2, stream.Position); - Assert.AreEqual(expected, actual); + Assert.That(stream.Position, Is.EqualTo(2)); + Assert.That(actual, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void ReadInt16_ShouldReadLittleEndian_GivenLittleEndian() { using var stream = new MemoryStream(); @@ -61,7 +61,7 @@ public partial class StreamTests const short expected = 420; short actual = stream.ReadInt16(Endianness.LittleEndian); - Assert.AreEqual(2, stream.Position); - Assert.AreEqual(expected, actual); + Assert.That(stream.Position, Is.EqualTo(2)); + Assert.That(actual, Is.EqualTo(expected)); } } diff --git a/X10D.Tests/src/IO/StreamTests.ReadInt32.cs b/X10D.Tests/src/IO/StreamTests.ReadInt32.cs index 60442fe..64f4c75 100644 --- a/X10D.Tests/src/IO/StreamTests.ReadInt32.cs +++ b/X10D.Tests/src/IO/StreamTests.ReadInt32.cs @@ -1,29 +1,29 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; public partial class StreamTests { - [TestMethod] + [Test] public void ReadInt32_ShouldThrowArgumentException_GivenNonReadableStream() { Stream stream = new DummyStream(); - Assert.ThrowsException(() => stream.ReadInt32()); - Assert.ThrowsException(() => stream.ReadInt32(Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.ReadInt32(Endianness.BigEndian)); + Assert.Throws(() => stream.ReadInt32()); + Assert.Throws(() => stream.ReadInt32(Endianness.LittleEndian)); + Assert.Throws(() => stream.ReadInt32(Endianness.BigEndian)); } - [TestMethod] + [Test] public void ReadInt32_ShouldThrowArgumentNullException_GivenNullStream() { Stream stream = null!; - Assert.ThrowsException(() => stream.ReadInt32()); - Assert.ThrowsException(() => stream.ReadInt32(Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.ReadInt32(Endianness.BigEndian)); + Assert.Throws(() => stream.ReadInt32()); + Assert.Throws(() => stream.ReadInt32(Endianness.LittleEndian)); + Assert.Throws(() => stream.ReadInt32(Endianness.BigEndian)); } - [TestMethod] + [Test] public void ReadInt32_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() { // we don't need to enclose this stream in a using declaration, since disposing a @@ -32,10 +32,10 @@ public partial class StreamTests // analyser to trip up and think the stream is disposed by the time the local is captured in // assertion lambda - means this line is fine as it is. please do not change. Stream stream = Stream.Null; - Assert.ThrowsException(() => stream.ReadInt32((Endianness)(-1))); + Assert.Throws(() => stream.ReadInt32((Endianness)(-1))); } - [TestMethod] + [Test] public void ReadInt32_ShouldReadBigEndian_GivenBigEndian() { using var stream = new MemoryStream(); @@ -46,11 +46,11 @@ public partial class StreamTests const int expected = 420; int actual = stream.ReadInt32(Endianness.BigEndian); - Assert.AreEqual(4, stream.Position); - Assert.AreEqual(expected, actual); + Assert.That(stream.Position, Is.EqualTo(4)); + Assert.That(actual, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void ReadInt32_ShouldReadLittleEndian_GivenLittleEndian() { using var stream = new MemoryStream(); @@ -61,7 +61,7 @@ public partial class StreamTests const int expected = 420; int actual = stream.ReadInt32(Endianness.LittleEndian); - Assert.AreEqual(4, stream.Position); - Assert.AreEqual(expected, actual); + Assert.That(stream.Position, Is.EqualTo(4)); + Assert.That(actual, Is.EqualTo(expected)); } } diff --git a/X10D.Tests/src/IO/StreamTests.ReadInt64.cs b/X10D.Tests/src/IO/StreamTests.ReadInt64.cs index 23554b1..d9f938e 100644 --- a/X10D.Tests/src/IO/StreamTests.ReadInt64.cs +++ b/X10D.Tests/src/IO/StreamTests.ReadInt64.cs @@ -1,29 +1,29 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; public partial class StreamTests { - [TestMethod] + [Test] public void ReadInt64_ShouldThrowArgumentException_GivenNonReadableStream() { Stream stream = new DummyStream(); - Assert.ThrowsException(() => stream.ReadInt64()); - Assert.ThrowsException(() => stream.ReadInt64(Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.ReadInt64(Endianness.BigEndian)); + Assert.Throws(() => stream.ReadInt64()); + Assert.Throws(() => stream.ReadInt64(Endianness.LittleEndian)); + Assert.Throws(() => stream.ReadInt64(Endianness.BigEndian)); } - [TestMethod] + [Test] public void ReadInt64_ShouldThrowArgumentNullException_GivenNullStream() { Stream stream = null!; - Assert.ThrowsException(() => stream.ReadInt64()); - Assert.ThrowsException(() => stream.ReadInt64(Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.ReadInt64(Endianness.BigEndian)); + Assert.Throws(() => stream.ReadInt64()); + Assert.Throws(() => stream.ReadInt64(Endianness.LittleEndian)); + Assert.Throws(() => stream.ReadInt64(Endianness.BigEndian)); } - [TestMethod] + [Test] public void ReadInt64_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() { // we don't need to enclose this stream in a using declaration, since disposing a @@ -32,10 +32,10 @@ public partial class StreamTests // analyser to trip up and think the stream is disposed by the time the local is captured in // assertion lambda - means this line is fine as it is. please do not change. Stream stream = Stream.Null; - Assert.ThrowsException(() => stream.ReadInt64((Endianness)(-1))); + Assert.Throws(() => stream.ReadInt64((Endianness)(-1))); } - [TestMethod] + [Test] public void ReadInt64_ShouldReadBigEndian_GivenBigEndian() { using var stream = new MemoryStream(); @@ -46,11 +46,11 @@ public partial class StreamTests const long expected = 420; long actual = stream.ReadInt64(Endianness.BigEndian); - Assert.AreEqual(8, stream.Position); - Assert.AreEqual(expected, actual); + Assert.That(stream.Position, Is.EqualTo(8)); + Assert.That(actual, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void ReadInt64_ShouldWriteLittleEndian_GivenLittleEndian() { using var stream = new MemoryStream(); @@ -61,7 +61,7 @@ public partial class StreamTests const long expected = 420; long actual = stream.ReadInt64(Endianness.LittleEndian); - Assert.AreEqual(8, stream.Position); - Assert.AreEqual(expected, actual); + Assert.That(stream.Position, Is.EqualTo(8)); + Assert.That(actual, Is.EqualTo(expected)); } } diff --git a/X10D.Tests/src/IO/StreamTests.ReadSingle.cs b/X10D.Tests/src/IO/StreamTests.ReadSingle.cs index 35976c5..2dc2292 100644 --- a/X10D.Tests/src/IO/StreamTests.ReadSingle.cs +++ b/X10D.Tests/src/IO/StreamTests.ReadSingle.cs @@ -1,29 +1,29 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; public partial class StreamTests { - [TestMethod] + [Test] public void ReadSingle_ShouldThrowArgumentException_GivenNonReadableStream() { Stream stream = new DummyStream(); - Assert.ThrowsException(() => stream.ReadSingle()); - Assert.ThrowsException(() => stream.ReadSingle(Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.ReadSingle(Endianness.BigEndian)); + Assert.Throws(() => stream.ReadSingle()); + Assert.Throws(() => stream.ReadSingle(Endianness.LittleEndian)); + Assert.Throws(() => stream.ReadSingle(Endianness.BigEndian)); } - [TestMethod] + [Test] public void ReadSingle_ShouldThrowArgumentNullException_GivenNullStream() { Stream stream = null!; - Assert.ThrowsException(() => stream.ReadSingle()); - Assert.ThrowsException(() => stream.ReadSingle(Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.ReadSingle(Endianness.BigEndian)); + Assert.Throws(() => stream.ReadSingle()); + Assert.Throws(() => stream.ReadSingle(Endianness.LittleEndian)); + Assert.Throws(() => stream.ReadSingle(Endianness.BigEndian)); } - [TestMethod] + [Test] public void ReadSingle_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() { // we don't need to enclose this stream in a using declaration, since disposing a @@ -32,10 +32,10 @@ public partial class StreamTests // analyser to trip up and think the stream is disposed by the time the local is captured in // assertion lambda - means this line is fine as it is. please do not change. Stream stream = Stream.Null; - Assert.ThrowsException(() => stream.ReadSingle((Endianness)(-1))); + Assert.Throws(() => stream.ReadSingle((Endianness)(-1))); } - [TestMethod] + [Test] public void ReadSingle_ShouldReadBigEndian_GivenBigEndian() { using var stream = new MemoryStream(); @@ -46,11 +46,11 @@ public partial class StreamTests const float expected = 420.0f; float actual = stream.ReadSingle(Endianness.BigEndian); - Assert.AreEqual(4, stream.Position); - Assert.AreEqual(expected, actual); + Assert.That(stream.Position, Is.EqualTo(4)); + Assert.That(actual, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void ReadSingle_ShouldReadLittleEndian_GivenLittleEndian() { using var stream = new MemoryStream(); @@ -61,7 +61,7 @@ public partial class StreamTests const float expected = 420.0f; float actual = stream.ReadSingle(Endianness.LittleEndian); - Assert.AreEqual(4, stream.Position); - Assert.AreEqual(expected, actual); + Assert.That(stream.Position, Is.EqualTo(4)); + Assert.That(actual, Is.EqualTo(expected)); } } diff --git a/X10D.Tests/src/IO/StreamTests.ReadUInt16.cs b/X10D.Tests/src/IO/StreamTests.ReadUInt16.cs index b28c3e7..23508dc 100644 --- a/X10D.Tests/src/IO/StreamTests.ReadUInt16.cs +++ b/X10D.Tests/src/IO/StreamTests.ReadUInt16.cs @@ -1,31 +1,31 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; public partial class StreamTests { - [TestMethod] + [Test] [CLSCompliant(false)] public void ReadUInt16_ShouldThrowArgumentException_GivenNonReadableStream() { Stream stream = new DummyStream(); - Assert.ThrowsException(() => stream.ReadUInt16()); - Assert.ThrowsException(() => stream.ReadUInt16(Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.ReadUInt16(Endianness.BigEndian)); + Assert.Throws(() => stream.ReadUInt16()); + Assert.Throws(() => stream.ReadUInt16(Endianness.LittleEndian)); + Assert.Throws(() => stream.ReadUInt16(Endianness.BigEndian)); } - [TestMethod] + [Test] [CLSCompliant(false)] public void ReadUInt16_ShouldThrowArgumentNullException_GivenNullStream() { Stream stream = null!; - Assert.ThrowsException(() => stream.ReadUInt16()); - Assert.ThrowsException(() => stream.ReadUInt16(Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.ReadUInt16(Endianness.BigEndian)); + Assert.Throws(() => stream.ReadUInt16()); + Assert.Throws(() => stream.ReadUInt16(Endianness.LittleEndian)); + Assert.Throws(() => stream.ReadUInt16(Endianness.BigEndian)); } - [TestMethod] + [Test] [CLSCompliant(false)] public void ReadUInt16_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() { @@ -35,10 +35,10 @@ public partial class StreamTests // analyser to trip up and think the stream is disposed by the time the local is captured in // assertion lambda - means this line is fine as it is. please do not change. Stream stream = Stream.Null; - Assert.ThrowsException(() => stream.ReadUInt16((Endianness)(-1))); + Assert.Throws(() => stream.ReadUInt16((Endianness)(-1))); } - [TestMethod] + [Test] [CLSCompliant(false)] public void ReadUInt16_ShouldReadBigEndian_GivenBigEndian() { @@ -50,11 +50,11 @@ public partial class StreamTests const ushort expected = 420; ushort actual = stream.ReadUInt16(Endianness.BigEndian); - Assert.AreEqual(2, stream.Position); - Assert.AreEqual(expected, actual); + Assert.That(stream.Position, Is.EqualTo(2)); + Assert.That(actual, Is.EqualTo(expected)); } - [TestMethod] + [Test] [CLSCompliant(false)] public void ReadUInt16_ShouldReadLittleEndian_GivenLittleEndian() { @@ -66,7 +66,7 @@ public partial class StreamTests const ushort expected = 420; ushort actual = stream.ReadUInt16(Endianness.LittleEndian); - Assert.AreEqual(2, stream.Position); - Assert.AreEqual(expected, actual); + Assert.That(stream.Position, Is.EqualTo(2)); + Assert.That(actual, Is.EqualTo(expected)); } } diff --git a/X10D.Tests/src/IO/StreamTests.ReadUInt32.cs b/X10D.Tests/src/IO/StreamTests.ReadUInt32.cs index 6112b80..8bd57a3 100644 --- a/X10D.Tests/src/IO/StreamTests.ReadUInt32.cs +++ b/X10D.Tests/src/IO/StreamTests.ReadUInt32.cs @@ -1,31 +1,31 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; public partial class StreamTests { - [TestMethod] + [Test] [CLSCompliant(false)] public void ReadUInt32_ShouldThrowArgumentException_GivenNonReadableStream() { Stream stream = new DummyStream(); - Assert.ThrowsException(() => stream.ReadUInt32()); - Assert.ThrowsException(() => stream.ReadUInt32(Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.ReadUInt32(Endianness.BigEndian)); + Assert.Throws(() => stream.ReadUInt32()); + Assert.Throws(() => stream.ReadUInt32(Endianness.LittleEndian)); + Assert.Throws(() => stream.ReadUInt32(Endianness.BigEndian)); } - [TestMethod] + [Test] [CLSCompliant(false)] public void ReadUInt32_ShouldThrowArgumentNullException_GivenNullStream() { Stream stream = null!; - Assert.ThrowsException(() => stream.ReadUInt32()); - Assert.ThrowsException(() => stream.ReadUInt32(Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.ReadUInt32(Endianness.BigEndian)); + Assert.Throws(() => stream.ReadUInt32()); + Assert.Throws(() => stream.ReadUInt32(Endianness.LittleEndian)); + Assert.Throws(() => stream.ReadUInt32(Endianness.BigEndian)); } - [TestMethod] + [Test] [CLSCompliant(false)] public void ReadUInt32_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() { @@ -35,10 +35,10 @@ public partial class StreamTests // analyser to trip up and think the stream is disposed by the time the local is captured in // assertion lambda - means this line is fine as it is. please do not change. Stream stream = Stream.Null; - Assert.ThrowsException(() => stream.ReadUInt32((Endianness)(-1))); + Assert.Throws(() => stream.ReadUInt32((Endianness)(-1))); } - [TestMethod] + [Test] [CLSCompliant(false)] public void ReadUInt32_ShouldReadBigEndian_GivenBigEndian() { @@ -50,11 +50,11 @@ public partial class StreamTests const uint expected = 420; uint actual = stream.ReadUInt32(Endianness.BigEndian); - Assert.AreEqual(4, stream.Position); - Assert.AreEqual(expected, actual); + Assert.That(stream.Position, Is.EqualTo(4)); + Assert.That(actual, Is.EqualTo(expected)); } - [TestMethod] + [Test] [CLSCompliant(false)] public void ReadUInt32_ShouldReadLittleEndian_GivenLittleEndian() { @@ -66,7 +66,7 @@ public partial class StreamTests const uint expected = 420; uint actual = stream.ReadUInt32(Endianness.LittleEndian); - Assert.AreEqual(4, stream.Position); - Assert.AreEqual(expected, actual); + Assert.That(stream.Position, Is.EqualTo(4)); + Assert.That(actual, Is.EqualTo(expected)); } } diff --git a/X10D.Tests/src/IO/StreamTests.ReadUInt64.cs b/X10D.Tests/src/IO/StreamTests.ReadUInt64.cs index 6e5a0c7..f315b47 100644 --- a/X10D.Tests/src/IO/StreamTests.ReadUInt64.cs +++ b/X10D.Tests/src/IO/StreamTests.ReadUInt64.cs @@ -1,31 +1,31 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; public partial class StreamTests { - [TestMethod] + [Test] [CLSCompliant(false)] public void ReadUInt64_ShouldThrowArgumentException_GivenNonReadableStream() { Stream stream = new DummyStream(); - Assert.ThrowsException(() => stream.ReadUInt64()); - Assert.ThrowsException(() => stream.ReadUInt64(Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.ReadUInt64(Endianness.BigEndian)); + Assert.Throws(() => stream.ReadUInt64()); + Assert.Throws(() => stream.ReadUInt64(Endianness.LittleEndian)); + Assert.Throws(() => stream.ReadUInt64(Endianness.BigEndian)); } - [TestMethod] + [Test] [CLSCompliant(false)] public void ReadUInt64_ShouldThrowArgumentNullException_GivenNullStream() { Stream stream = null!; - Assert.ThrowsException(() => stream.ReadUInt64()); - Assert.ThrowsException(() => stream.ReadUInt64(Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.ReadUInt64(Endianness.BigEndian)); + Assert.Throws(() => stream.ReadUInt64()); + Assert.Throws(() => stream.ReadUInt64(Endianness.LittleEndian)); + Assert.Throws(() => stream.ReadUInt64(Endianness.BigEndian)); } - [TestMethod] + [Test] [CLSCompliant(false)] public void ReadUInt64_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() { @@ -35,10 +35,10 @@ public partial class StreamTests // analyser to trip up and think the stream is disposed by the time the local is captured in // assertion lambda - means this line is fine as it is. please do not change. Stream stream = Stream.Null; - Assert.ThrowsException(() => stream.ReadUInt64((Endianness)(-1))); + Assert.Throws(() => stream.ReadUInt64((Endianness)(-1))); } - [TestMethod] + [Test] [CLSCompliant(false)] public void ReadUInt64_ShouldReadBigEndian_GivenBigEndian() { @@ -50,11 +50,11 @@ public partial class StreamTests const ulong expected = 420; ulong actual = stream.ReadUInt64(Endianness.BigEndian); - Assert.AreEqual(8, stream.Position); - Assert.AreEqual(expected, actual); + Assert.That(stream.Position, Is.EqualTo(8)); + Assert.That(actual, Is.EqualTo(expected)); } - [TestMethod] + [Test] [CLSCompliant(false)] public void ReadUInt64_ShouldWriteLittleEndian_GivenLittleEndian() { @@ -66,7 +66,7 @@ public partial class StreamTests const ulong expected = 420; ulong actual = stream.ReadUInt64(Endianness.LittleEndian); - Assert.AreEqual(8, stream.Position); - Assert.AreEqual(expected, actual); + Assert.That(stream.Position, Is.EqualTo(8)); + Assert.That(actual, Is.EqualTo(expected)); } } diff --git a/X10D.Tests/src/IO/StreamTests.WriteDecimal.cs b/X10D.Tests/src/IO/StreamTests.WriteDecimal.cs index 1412f37..e34a816 100644 --- a/X10D.Tests/src/IO/StreamTests.WriteDecimal.cs +++ b/X10D.Tests/src/IO/StreamTests.WriteDecimal.cs @@ -1,28 +1,28 @@ using System.Diagnostics; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; public partial class StreamTests { - [TestMethod] + [Test] public void WriteDecimal_ShouldThrowArgumentException_GivenNonWriteableStream() { Stream stream = new DummyStream(); - Assert.ThrowsException(() => stream.Write(420.0m, Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.Write(420.0m, Endianness.BigEndian)); + Assert.Throws(() => stream.Write(420.0m, Endianness.LittleEndian)); + Assert.Throws(() => stream.Write(420.0m, Endianness.BigEndian)); } - [TestMethod] + [Test] public void WriteDecimal_ShouldThrowArgumentNullException_GivenNullStream() { Stream stream = null!; - Assert.ThrowsException(() => stream.Write(420.0m, Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.Write(420.0m, Endianness.BigEndian)); + Assert.Throws(() => stream.Write(420.0m, Endianness.LittleEndian)); + Assert.Throws(() => stream.Write(420.0m, Endianness.BigEndian)); } - [TestMethod] + [Test] public void WriteDecimal_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() { // we don't need to enclose this stream in a using declaration, since disposing a @@ -31,16 +31,16 @@ public partial class StreamTests // analyser to trip up and think the stream is disposed by the time the local is captured in // assertion lambda - means this line is fine as it is. please do not change. Stream stream = Stream.Null; - Assert.ThrowsException(() => stream.Write(420.0m, (Endianness)(-1))); - Assert.ThrowsException(() => stream.Write(420.0m, (Endianness)(-1))); + Assert.Throws(() => stream.Write(420.0m, (Endianness)(-1))); + Assert.Throws(() => stream.Write(420.0m, (Endianness)(-1))); } - [TestMethod] + [Test] public void WriteDecimal_ShouldWriteBigEndian_GivenBigEndian() { using var stream = new MemoryStream(); stream.Write(420.0m, Endianness.BigEndian); - Assert.AreEqual(16, stream.Position); + Assert.That(stream.Position, Is.EqualTo(16)); stream.Position = 0; Span actual = stackalloc byte[16]; @@ -50,16 +50,16 @@ public partial class StreamTests }; int read = stream.Read(actual); - Assert.AreEqual(16, read); + Assert.That(read, Is.EqualTo(16)); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); } - [TestMethod] + [Test] public void WriteDecimal_ShouldWriteLittleEndian_GivenLittleEndian() { using var stream = new MemoryStream(); stream.Write(420.0m, Endianness.LittleEndian); - Assert.AreEqual(16, stream.Position); + Assert.That(stream.Position, Is.EqualTo(16)); stream.Position = 0; Span actual = stackalloc byte[16]; @@ -71,7 +71,7 @@ public partial class StreamTests Trace.WriteLine(string.Join(", ", actual.ToArray().Select(b => $"0x{b:X2}"))); - Assert.AreEqual(16, read); + Assert.That(read, Is.EqualTo(16)); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); } } diff --git a/X10D.Tests/src/IO/StreamTests.WriteDouble.cs b/X10D.Tests/src/IO/StreamTests.WriteDouble.cs index 5605830..b1b43e1 100644 --- a/X10D.Tests/src/IO/StreamTests.WriteDouble.cs +++ b/X10D.Tests/src/IO/StreamTests.WriteDouble.cs @@ -1,27 +1,27 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; public partial class StreamTests { - [TestMethod] + [Test] public void WriteDouble_ShouldThrowArgumentException_GivenNonWriteableStream() { Stream stream = new DummyStream(); - Assert.ThrowsException(() => stream.Write(420.0, Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.Write(420.0, Endianness.BigEndian)); + Assert.Throws(() => stream.Write(420.0, Endianness.LittleEndian)); + Assert.Throws(() => stream.Write(420.0, Endianness.BigEndian)); } - [TestMethod] + [Test] public void WriteDouble_ShouldThrowArgumentNullException_GivenNullStream() { Stream stream = null!; - Assert.ThrowsException(() => stream.Write(420.0, Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.Write(420.0, Endianness.BigEndian)); + Assert.Throws(() => stream.Write(420.0, Endianness.LittleEndian)); + Assert.Throws(() => stream.Write(420.0, Endianness.BigEndian)); } - [TestMethod] + [Test] public void WriteDouble_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() { // we don't need to enclose this stream in a using declaration, since disposing a @@ -30,39 +30,39 @@ public partial class StreamTests // analyser to trip up and think the stream is disposed by the time the local is captured in // assertion lambda - means this line is fine as it is. please do not change. Stream stream = Stream.Null; - Assert.ThrowsException(() => stream.Write(420.0, (Endianness)(-1))); - Assert.ThrowsException(() => stream.Write(420.0, (Endianness)(-1))); + Assert.Throws(() => stream.Write(420.0, (Endianness)(-1))); + Assert.Throws(() => stream.Write(420.0, (Endianness)(-1))); } - [TestMethod] + [Test] public void WriteDouble_ShouldWriteBigEndian_GivenBigEndian() { using var stream = new MemoryStream(); stream.Write(420.0, Endianness.BigEndian); - Assert.AreEqual(8, stream.Position); + Assert.That(stream.Position, Is.EqualTo(8)); stream.Position = 0; Span actual = stackalloc byte[8]; ReadOnlySpan expected = stackalloc byte[] {0x40, 0x7A, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00}; int read = stream.Read(actual); - Assert.AreEqual(8, read); + Assert.That(read, Is.EqualTo(8)); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); } - [TestMethod] + [Test] public void WriteDouble_ShouldWriteLittleEndian_GivenLittleEndian() { using var stream = new MemoryStream(); stream.Write(420.0, Endianness.LittleEndian); - Assert.AreEqual(8, stream.Position); + Assert.That(stream.Position, Is.EqualTo(8)); stream.Position = 0; Span actual = stackalloc byte[8]; ReadOnlySpan expected = stackalloc byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x7A, 0x40}; int read = stream.Read(actual); - Assert.AreEqual(8, read); + Assert.That(read, Is.EqualTo(8)); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); } } diff --git a/X10D.Tests/src/IO/StreamTests.WriteInt16.cs b/X10D.Tests/src/IO/StreamTests.WriteInt16.cs index 1e0a1e9..ce0bc8d 100644 --- a/X10D.Tests/src/IO/StreamTests.WriteInt16.cs +++ b/X10D.Tests/src/IO/StreamTests.WriteInt16.cs @@ -1,27 +1,27 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; public partial class StreamTests { - [TestMethod] + [Test] public void WriteInt16_ShouldThrowArgumentException_GivenNonWriteableStream() { Stream stream = new DummyStream(); - Assert.ThrowsException(() => stream.Write((short)420, Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.Write((short)420, Endianness.BigEndian)); + Assert.Throws(() => stream.Write((short)420, Endianness.LittleEndian)); + Assert.Throws(() => stream.Write((short)420, Endianness.BigEndian)); } - [TestMethod] + [Test] public void WriteInt16_ShouldThrowArgumentNullException_GivenNullStream() { Stream stream = null!; - Assert.ThrowsException(() => stream.Write((short)420, Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.Write((short)420, Endianness.BigEndian)); + Assert.Throws(() => stream.Write((short)420, Endianness.LittleEndian)); + Assert.Throws(() => stream.Write((short)420, Endianness.BigEndian)); } - [TestMethod] + [Test] public void WriteInt16_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() { // we don't need to enclose this stream in a using declaration, since disposing a @@ -30,39 +30,39 @@ public partial class StreamTests // analyser to trip up and think the stream is disposed by the time the local is captured in // assertion lambda - means this line is fine as it is. please do not change. Stream stream = Stream.Null; - Assert.ThrowsException(() => stream.Write((short)420, (Endianness)(-1))); - Assert.ThrowsException(() => stream.Write((short)420, (Endianness)(-1))); + Assert.Throws(() => stream.Write((short)420, (Endianness)(-1))); + Assert.Throws(() => stream.Write((short)420, (Endianness)(-1))); } - [TestMethod] + [Test] public void WriteInt16_ShouldWriteBigEndian_GivenBigEndian() { using var stream = new MemoryStream(); stream.Write((short)420, Endianness.BigEndian); - Assert.AreEqual(2, stream.Position); + Assert.That(stream.Position, Is.EqualTo(2)); stream.Position = 0; Span actual = stackalloc byte[2]; ReadOnlySpan expected = stackalloc byte[] {0x01, 0xA4}; int read = stream.Read(actual); - Assert.AreEqual(2, read); + Assert.That(read, Is.EqualTo(2)); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); } - [TestMethod] + [Test] public void WriteInt16_ShouldWriteLittleEndian_GivenLittleEndian() { using var stream = new MemoryStream(); stream.Write((short)420, Endianness.LittleEndian); - Assert.AreEqual(2, stream.Position); + Assert.That(stream.Position, Is.EqualTo(2)); stream.Position = 0; Span actual = stackalloc byte[2]; ReadOnlySpan expected = stackalloc byte[] {0xA4, 0x01}; int read = stream.Read(actual); - Assert.AreEqual(2, read); + Assert.That(read, Is.EqualTo(2)); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); } } diff --git a/X10D.Tests/src/IO/StreamTests.WriteInt32.cs b/X10D.Tests/src/IO/StreamTests.WriteInt32.cs index dae3144..bb8c982 100644 --- a/X10D.Tests/src/IO/StreamTests.WriteInt32.cs +++ b/X10D.Tests/src/IO/StreamTests.WriteInt32.cs @@ -1,27 +1,27 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; public partial class StreamTests { - [TestMethod] + [Test] public void WriteInt32_ShouldThrowArgumentException_GivenNonWriteableStream() { Stream stream = new DummyStream(); - Assert.ThrowsException(() => stream.Write(420, Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.Write(420, Endianness.BigEndian)); + Assert.Throws(() => stream.Write(420, Endianness.LittleEndian)); + Assert.Throws(() => stream.Write(420, Endianness.BigEndian)); } - [TestMethod] + [Test] public void WriteInt32_ShouldThrowArgumentNullException_GivenNullStream() { Stream stream = null!; - Assert.ThrowsException(() => stream.Write(420, Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.Write(420, Endianness.BigEndian)); + Assert.Throws(() => stream.Write(420, Endianness.LittleEndian)); + Assert.Throws(() => stream.Write(420, Endianness.BigEndian)); } - [TestMethod] + [Test] public void WriteInt32_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() { // we don't need to enclose this stream in a using declaration, since disposing a @@ -30,39 +30,39 @@ public partial class StreamTests // analyser to trip up and think the stream is disposed by the time the local is captured in // assertion lambda - means this line is fine as it is. please do not change. Stream stream = Stream.Null; - Assert.ThrowsException(() => stream.Write(420, (Endianness)(-1))); - Assert.ThrowsException(() => stream.Write(420, (Endianness)(-1))); + Assert.Throws(() => stream.Write(420, (Endianness)(-1))); + Assert.Throws(() => stream.Write(420, (Endianness)(-1))); } - [TestMethod] + [Test] public void WriteInt32_ShouldWriteBigEndian_GivenBigEndian() { using var stream = new MemoryStream(); stream.Write(420, Endianness.BigEndian); - Assert.AreEqual(4, stream.Position); + Assert.That(stream.Position, Is.EqualTo(4)); stream.Position = 0; Span actual = stackalloc byte[4]; ReadOnlySpan expected = stackalloc byte[] {0x00, 0x00, 0x01, 0xA4}; int read = stream.Read(actual); - Assert.AreEqual(4, read); + Assert.That(read, Is.EqualTo(4)); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); } - [TestMethod] + [Test] public void WriteInt32_ShouldWriteLittleEndian_GivenLittleEndian() { using var stream = new MemoryStream(); stream.Write(420, Endianness.LittleEndian); - Assert.AreEqual(4, stream.Position); + Assert.That(stream.Position, Is.EqualTo(4)); stream.Position = 0; Span actual = stackalloc byte[4]; ReadOnlySpan expected = stackalloc byte[] {0xA4, 0x01, 0x00, 0x00}; int read = stream.Read(actual); - Assert.AreEqual(4, read); + Assert.That(read, Is.EqualTo(4)); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); } } diff --git a/X10D.Tests/src/IO/StreamTests.WriteInt64.cs b/X10D.Tests/src/IO/StreamTests.WriteInt64.cs index 0f5e6d0..e0fda01 100644 --- a/X10D.Tests/src/IO/StreamTests.WriteInt64.cs +++ b/X10D.Tests/src/IO/StreamTests.WriteInt64.cs @@ -1,27 +1,27 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; public partial class StreamTests { - [TestMethod] + [Test] public void WriteInt64_ShouldThrowArgumentException_GivenNonWriteableStream() { Stream stream = new DummyStream(); - Assert.ThrowsException(() => stream.Write(420L, Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.Write(420L, Endianness.BigEndian)); + Assert.Throws(() => stream.Write(420L, Endianness.LittleEndian)); + Assert.Throws(() => stream.Write(420L, Endianness.BigEndian)); } - [TestMethod] + [Test] public void WriteInt64_ShouldThrowArgumentNullException_GivenNullStream() { Stream stream = null!; - Assert.ThrowsException(() => stream.Write(420L, Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.Write(420L, Endianness.BigEndian)); + Assert.Throws(() => stream.Write(420L, Endianness.LittleEndian)); + Assert.Throws(() => stream.Write(420L, Endianness.BigEndian)); } - [TestMethod] + [Test] public void WriteInt64_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() { // we don't need to enclose this stream in a using declaration, since disposing a @@ -30,39 +30,39 @@ public partial class StreamTests // analyser to trip up and think the stream is disposed by the time the local is captured in // assertion lambda - means this line is fine as it is. please do not change. Stream stream = Stream.Null; - Assert.ThrowsException(() => stream.Write(420L, (Endianness)(-1))); - Assert.ThrowsException(() => stream.Write(420L, (Endianness)(-1))); + Assert.Throws(() => stream.Write(420L, (Endianness)(-1))); + Assert.Throws(() => stream.Write(420L, (Endianness)(-1))); } - [TestMethod] + [Test] public void WriteInt64_ShouldWriteBigEndian_GivenBigEndian() { using var stream = new MemoryStream(); stream.Write(420L, Endianness.BigEndian); - Assert.AreEqual(8, stream.Position); + Assert.That(stream.Position, Is.EqualTo(8)); stream.Position = 0; Span actual = stackalloc byte[8]; ReadOnlySpan expected = stackalloc byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xA4}; int read = stream.Read(actual); - Assert.AreEqual(8, read); + Assert.That(read, Is.EqualTo(8)); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); } - [TestMethod] + [Test] public void WriteInt64_ShouldWriteLittleEndian_GivenLittleEndian() { using var stream = new MemoryStream(); stream.Write(420L, Endianness.LittleEndian); - Assert.AreEqual(8, stream.Position); + Assert.That(stream.Position, Is.EqualTo(8)); stream.Position = 0; Span actual = stackalloc byte[8]; ReadOnlySpan expected = stackalloc byte[] {0xA4, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; int read = stream.Read(actual); - Assert.AreEqual(8, read); + Assert.That(read, Is.EqualTo(8)); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); } } diff --git a/X10D.Tests/src/IO/StreamTests.WriteSingle.cs b/X10D.Tests/src/IO/StreamTests.WriteSingle.cs index 5da14c0..69d491b 100644 --- a/X10D.Tests/src/IO/StreamTests.WriteSingle.cs +++ b/X10D.Tests/src/IO/StreamTests.WriteSingle.cs @@ -1,27 +1,27 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; public partial class StreamTests { - [TestMethod] + [Test] public void WriteSingle_ShouldThrowArgumentException_GivenNonWriteableStream() { Stream stream = new DummyStream(); - Assert.ThrowsException(() => stream.Write(420.0f, Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.Write(420.0f, Endianness.BigEndian)); + Assert.Throws(() => stream.Write(420.0f, Endianness.LittleEndian)); + Assert.Throws(() => stream.Write(420.0f, Endianness.BigEndian)); } - [TestMethod] + [Test] public void WriteSingle_ShouldThrowArgumentNullException_GivenNullStream() { Stream stream = null!; - Assert.ThrowsException(() => stream.Write(420.0f, Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.Write(420.0f, Endianness.BigEndian)); + Assert.Throws(() => stream.Write(420.0f, Endianness.LittleEndian)); + Assert.Throws(() => stream.Write(420.0f, Endianness.BigEndian)); } - [TestMethod] + [Test] public void WriteSingle_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() { // we don't need to enclose this stream in a using declaration, since disposing a @@ -30,39 +30,39 @@ public partial class StreamTests // analyser to trip up and think the stream is disposed by the time the local is captured in // assertion lambda - means this line is fine as it is. please do not change. Stream stream = Stream.Null; - Assert.ThrowsException(() => stream.Write(420.0f, (Endianness)(-1))); - Assert.ThrowsException(() => stream.Write(420.0f, (Endianness)(-1))); + Assert.Throws(() => stream.Write(420.0f, (Endianness)(-1))); + Assert.Throws(() => stream.Write(420.0f, (Endianness)(-1))); } - [TestMethod] + [Test] public void WriteSingle_ShouldWriteBigEndian_GivenBigEndian() { using var stream = new MemoryStream(); stream.Write(420.0f, Endianness.BigEndian); - Assert.AreEqual(4, stream.Position); + Assert.That(stream.Position, Is.EqualTo(4)); stream.Position = 0; Span actual = stackalloc byte[4]; ReadOnlySpan expected = stackalloc byte[] {0x43, 0xD2, 0x00, 0x00}; int read = stream.Read(actual); - Assert.AreEqual(4, read); + Assert.That(read, Is.EqualTo(4)); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); } - [TestMethod] + [Test] public void WriteSingle_ShouldWriteLittleEndian_GivenLittleEndian() { using var stream = new MemoryStream(); stream.Write(420.0f, Endianness.LittleEndian); - Assert.AreEqual(4, stream.Position); + Assert.That(stream.Position, Is.EqualTo(4)); stream.Position = 0; Span actual = stackalloc byte[4]; ReadOnlySpan expected = stackalloc byte[] {0x00, 0x00, 0xD2, 0x43}; int read = stream.Read(actual); - Assert.AreEqual(4, read); + Assert.That(read, Is.EqualTo(4)); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); } } diff --git a/X10D.Tests/src/IO/StreamTests.WriteUInt16.cs b/X10D.Tests/src/IO/StreamTests.WriteUInt16.cs index fe73ec7..9747ca8 100644 --- a/X10D.Tests/src/IO/StreamTests.WriteUInt16.cs +++ b/X10D.Tests/src/IO/StreamTests.WriteUInt16.cs @@ -1,29 +1,29 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; public partial class StreamTests { - [TestMethod] + [Test] [CLSCompliant(false)] public void WriteUInt16_ShouldThrowArgumentException_GivenNonWriteableStream() { Stream stream = new DummyStream(); - Assert.ThrowsException(() => stream.Write((ushort)420, Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.Write((ushort)420, Endianness.BigEndian)); + Assert.Throws(() => stream.Write((ushort)420, Endianness.LittleEndian)); + Assert.Throws(() => stream.Write((ushort)420, Endianness.BigEndian)); } - [TestMethod] + [Test] [CLSCompliant(false)] public void WriteUInt16_ShouldThrowArgumentNullException_GivenNullStream() { Stream stream = null!; - Assert.ThrowsException(() => stream.Write((ushort)420, Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.Write((ushort)420, Endianness.BigEndian)); + Assert.Throws(() => stream.Write((ushort)420, Endianness.LittleEndian)); + Assert.Throws(() => stream.Write((ushort)420, Endianness.BigEndian)); } - [TestMethod] + [Test] [CLSCompliant(false)] public void WriteUInt16_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() { @@ -33,41 +33,41 @@ public partial class StreamTests // analyser to trip up and think the stream is disposed by the time the local is captured in // assertion lambda - means this line is fine as it is. please do not change. Stream stream = Stream.Null; - Assert.ThrowsException(() => stream.Write((ushort)420, (Endianness)(-1))); - Assert.ThrowsException(() => stream.Write((ushort)420, (Endianness)(-1))); + Assert.Throws(() => stream.Write((ushort)420, (Endianness)(-1))); + Assert.Throws(() => stream.Write((ushort)420, (Endianness)(-1))); } - [TestMethod] + [Test] [CLSCompliant(false)] public void WriteUInt16_ShouldWriteBigEndian_GivenBigEndian() { using var stream = new MemoryStream(); stream.Write((ushort)420, Endianness.BigEndian); - Assert.AreEqual(2, stream.Position); + Assert.That(stream.Position, Is.EqualTo(2)); stream.Position = 0; Span actual = stackalloc byte[2]; ReadOnlySpan expected = stackalloc byte[] {0x01, 0xA4}; int read = stream.Read(actual); - Assert.AreEqual(2, read); + Assert.That(read, Is.EqualTo(2)); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); } - [TestMethod] + [Test] [CLSCompliant(false)] public void WriteUInt16_ShouldWriteLittleEndian_GivenLittleEndian() { using var stream = new MemoryStream(); stream.Write((ushort)420, Endianness.LittleEndian); - Assert.AreEqual(2, stream.Position); + Assert.That(stream.Position, Is.EqualTo(2)); stream.Position = 0; Span actual = stackalloc byte[2]; ReadOnlySpan expected = stackalloc byte[] {0xA4, 0x01}; int read = stream.Read(actual); - Assert.AreEqual(2, read); + Assert.That(read, Is.EqualTo(2)); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); } } diff --git a/X10D.Tests/src/IO/StreamTests.WriteUInt32.cs b/X10D.Tests/src/IO/StreamTests.WriteUInt32.cs index e28e946..41d77a9 100644 --- a/X10D.Tests/src/IO/StreamTests.WriteUInt32.cs +++ b/X10D.Tests/src/IO/StreamTests.WriteUInt32.cs @@ -1,29 +1,29 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; public partial class StreamTests { - [TestMethod] + [Test] [CLSCompliant(false)] public void WriteUInt32_ShouldThrowArgumentException_GivenNonWriteableStream() { Stream stream = new DummyStream(); - Assert.ThrowsException(() => stream.Write(420U, Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.Write(420U, Endianness.BigEndian)); + Assert.Throws(() => stream.Write(420U, Endianness.LittleEndian)); + Assert.Throws(() => stream.Write(420U, Endianness.BigEndian)); } - [TestMethod] + [Test] [CLSCompliant(false)] public void WriteUInt32_ShouldThrowArgumentNullException_GivenNullStream() { Stream stream = null!; - Assert.ThrowsException(() => stream.Write(420U, Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.Write(420U, Endianness.BigEndian)); + Assert.Throws(() => stream.Write(420U, Endianness.LittleEndian)); + Assert.Throws(() => stream.Write(420U, Endianness.BigEndian)); } - [TestMethod] + [Test] [CLSCompliant(false)] public void WriteUInt32_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() { @@ -33,41 +33,41 @@ public partial class StreamTests // analyser to trip up and think the stream is disposed by the time the local is captured in // assertion lambda - means this line is fine as it is. please do not change. Stream stream = Stream.Null; - Assert.ThrowsException(() => stream.Write(420U, (Endianness)(-1))); - Assert.ThrowsException(() => stream.Write(420U, (Endianness)(-1))); + Assert.Throws(() => stream.Write(420U, (Endianness)(-1))); + Assert.Throws(() => stream.Write(420U, (Endianness)(-1))); } - [TestMethod] + [Test] [CLSCompliant(false)] public void WriteUInt32_ShouldWriteBigEndian_GivenBigEndian() { using var stream = new MemoryStream(); stream.Write(420U, Endianness.BigEndian); - Assert.AreEqual(4, stream.Position); + Assert.That(stream.Position, Is.EqualTo(4)); stream.Position = 0; Span actual = stackalloc byte[4]; ReadOnlySpan expected = stackalloc byte[] {0x00, 0x00, 0x01, 0xA4}; int read = stream.Read(actual); - Assert.AreEqual(4, read); + Assert.That(read, Is.EqualTo(4)); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); } - [TestMethod] + [Test] [CLSCompliant(false)] public void WriteUInt32_ShouldWriteLittleEndian_GivenLittleEndian() { using var stream = new MemoryStream(); stream.Write(420U, Endianness.LittleEndian); - Assert.AreEqual(4, stream.Position); + Assert.That(stream.Position, Is.EqualTo(4)); stream.Position = 0; Span actual = stackalloc byte[4]; ReadOnlySpan expected = stackalloc byte[] {0xA4, 0x01, 0x00, 0x00}; int read = stream.Read(actual); - Assert.AreEqual(4, read); + Assert.That(read, Is.EqualTo(4)); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); } } diff --git a/X10D.Tests/src/IO/StreamTests.WriteUInt64.cs b/X10D.Tests/src/IO/StreamTests.WriteUInt64.cs index ef8065b..51a44f5 100644 --- a/X10D.Tests/src/IO/StreamTests.WriteUInt64.cs +++ b/X10D.Tests/src/IO/StreamTests.WriteUInt64.cs @@ -1,29 +1,29 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; public partial class StreamTests { - [TestMethod] + [Test] [CLSCompliant(false)] public void WriteUInt64_ShouldThrowArgumentException_GivenNonWriteableStream() { Stream stream = new DummyStream(); - Assert.ThrowsException(() => stream.Write(420UL, Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.Write(420UL, Endianness.BigEndian)); + Assert.Throws(() => stream.Write(420UL, Endianness.LittleEndian)); + Assert.Throws(() => stream.Write(420UL, Endianness.BigEndian)); } - [TestMethod] + [Test] [CLSCompliant(false)] public void WriteUInt64_ShouldThrowArgumentNullException_GivenNullStream() { Stream stream = null!; - Assert.ThrowsException(() => stream.Write(420UL, Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.Write(420UL, Endianness.BigEndian)); + Assert.Throws(() => stream.Write(420UL, Endianness.LittleEndian)); + Assert.Throws(() => stream.Write(420UL, Endianness.BigEndian)); } - [TestMethod] + [Test] [CLSCompliant(false)] public void WriteUInt64_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() { @@ -33,41 +33,41 @@ public partial class StreamTests // analyser to trip up and think the stream is disposed by the time the local is captured in // assertion lambda - means this line is fine as it is. please do not change. Stream stream = Stream.Null; - Assert.ThrowsException(() => stream.Write(420UL, (Endianness)(-1))); - Assert.ThrowsException(() => stream.Write(420UL, (Endianness)(-1))); + Assert.Throws(() => stream.Write(420UL, (Endianness)(-1))); + Assert.Throws(() => stream.Write(420UL, (Endianness)(-1))); } - [TestMethod] + [Test] [CLSCompliant(false)] public void WriteUInt64_ShouldWriteBigEndian_GivenBigEndian() { using var stream = new MemoryStream(); stream.Write(420UL, Endianness.BigEndian); - Assert.AreEqual(8, stream.Position); + Assert.That(stream.Position, Is.EqualTo(8)); stream.Position = 0; Span actual = stackalloc byte[8]; ReadOnlySpan expected = stackalloc byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xA4}; int read = stream.Read(actual); - Assert.AreEqual(8, read); + Assert.That(read, Is.EqualTo(8)); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); } - [TestMethod] + [Test] [CLSCompliant(false)] public void WriteUInt64_ShouldWriteLittleEndian_GivenLittleEndian() { using var stream = new MemoryStream(); stream.Write(420UL, Endianness.LittleEndian); - Assert.AreEqual(8, stream.Position); + Assert.That(stream.Position, Is.EqualTo(8)); stream.Position = 0; Span actual = stackalloc byte[8]; ReadOnlySpan expected = stackalloc byte[] {0xA4, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; int read = stream.Read(actual); - Assert.AreEqual(8, read); + Assert.That(read, Is.EqualTo(8)); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); } } diff --git a/X10D.Tests/src/IO/StreamTests.cs b/X10D.Tests/src/IO/StreamTests.cs index 2bb5d3c..01e4684 100644 --- a/X10D.Tests/src/IO/StreamTests.cs +++ b/X10D.Tests/src/IO/StreamTests.cs @@ -1,15 +1,15 @@ using System.Diagnostics; using System.Security.Cryptography; using System.Text; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; -[TestClass] +[TestFixture] public partial class StreamTests { - [TestMethod] + [Test] public void GetHashSha1ShouldBeCorrect() { // SHA-1 @@ -29,15 +29,15 @@ public partial class StreamTests CollectionAssert.AreEqual(expectedHash, hash); } - [TestMethod] + [Test] public void GetHashNullShouldThrow() { // any HashAlgorithm will do, but SHA1 is used above. so to remain consistent, we use it here - Assert.ThrowsException(() => ((Stream?)null)!.GetHash()); - Assert.ThrowsException(() => ((Stream?)null)!.TryWriteHash(Span.Empty, out _)); + Assert.Throws(() => ((Stream?)null)!.GetHash()); + Assert.Throws(() => ((Stream?)null)!.TryWriteHash(Span.Empty, out _)); } - [TestMethod] + [Test] public void TryWriteHashSha1_ShouldBeCorrect() { // SHA-1 @@ -53,49 +53,49 @@ public partial class StreamTests Span hash = stackalloc byte[20]; stream.TryWriteHash(hash, out int bytesWritten); - Assert.AreEqual(expectedHash.Length, bytesWritten); + Assert.That(bytesWritten, Is.EqualTo(expectedHash.Length)); CollectionAssert.AreEqual(expectedHash, hash.ToArray()); } - [TestMethod] + [Test] public void GetHash_TryWriteHash_ShouldThrow_GivenNonReadableStream() { - Assert.ThrowsException(() => + Assert.Throws(() => { using var stream = new DummyStream(); stream.GetHash(); }); - Assert.ThrowsException(() => + Assert.Throws(() => { using var stream = new DummyStream(); stream.TryWriteHash(Span.Empty, out _); }); } - [TestMethod] + [Test] public void LargeStreamShouldThrow() { - Assert.ThrowsException(() => + Assert.Throws(() => { using var stream = new DummyStream(true); stream.TryWriteHash(Span.Empty, out _); }); } - [TestMethod] + [Test] public void NullCreateMethodShouldThrow() { - Assert.ThrowsException(() => Stream.Null.GetHash()); - Assert.ThrowsException(() => + Assert.Throws(() => Stream.Null.GetHash()); + Assert.Throws(() => Stream.Null.TryWriteHash(Span.Empty, out _)); } - [TestMethod] + [Test] public void NoCreateMethodShouldThrow() { - Assert.ThrowsException(() => Stream.Null.GetHash()); - Assert.ThrowsException(() => + Assert.Throws(() => Stream.Null.GetHash()); + Assert.Throws(() => Stream.Null.TryWriteHash(Span.Empty, out _)); } diff --git a/X10D.Tests/src/IO/TextReaderTests.cs b/X10D.Tests/src/IO/TextReaderTests.cs index 6e10ef4..a2bafbc 100644 --- a/X10D.Tests/src/IO/TextReaderTests.cs +++ b/X10D.Tests/src/IO/TextReaderTests.cs @@ -1,13 +1,13 @@ using System.Text; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; -[TestClass] +[TestFixture] public class TextReaderTests { - [TestMethod] + [Test] public void EnumerateLines_ShouldYield10Lines_Given10LineString() { using var stream = new MemoryStream(); @@ -28,10 +28,10 @@ public class TextReaderTests lineCount++; } - Assert.AreEqual(10, lineCount); + Assert.That(lineCount, Is.EqualTo(10)); } - [TestMethod] + [Test] public async Task EnumerateLinesAsync_ShouldYield10Lines_Given10LineString() { using var stream = new MemoryStream(); @@ -52,14 +52,14 @@ public class TextReaderTests lineCount++; } - Assert.AreEqual(10, lineCount); + Assert.That(lineCount, Is.EqualTo(10)); } - [TestMethod] + [Test] public void EnumerateLines_ShouldThrowArgumentNullException_GivenNullSource() { TextReader reader = null!; - Assert.ThrowsException(() => + Assert.Throws(() => { foreach (string _ in reader.EnumerateLines()) { @@ -68,16 +68,16 @@ public class TextReaderTests }); } - [TestMethod] - public async Task EnumerateLinesAsync_ShouldThrowArgumentNullException_GivenNullSource() + [Test] + public void EnumerateLinesAsync_ShouldThrowArgumentNullException_GivenNullSource() { TextReader reader = null!; - await Assert.ThrowsExceptionAsync(async () => + Assert.ThrowsAsync(async () => { await foreach (string _ in reader.EnumerateLinesAsync().ConfigureAwait(false)) { // loop body is intentionally empty } - }).ConfigureAwait(false); + }); } } diff --git a/X10D.Tests/src/IO/UInt16Tests.cs b/X10D.Tests/src/IO/UInt16Tests.cs index 08c0e61..4e0e4bc 100644 --- a/X10D.Tests/src/IO/UInt16Tests.cs +++ b/X10D.Tests/src/IO/UInt16Tests.cs @@ -1,13 +1,13 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; -[TestClass] +[TestFixture] [CLSCompliant(false)] public class UInt16Tests { - [TestMethod] + [Test] public void GetBytes_ReturnsCorrectValue() { const ushort value = 0x0F; @@ -15,7 +15,7 @@ public class UInt16Tests CollectionAssert.AreEqual(bytes, value.GetBytes()); } - [TestMethod] + [Test] public void GetBytes_ReturnsCorrectValue_WithEndianness() { const ushort value = 0x0F; @@ -26,18 +26,18 @@ public class UInt16Tests CollectionAssert.AreEqual(bigEndian, value.GetBytes(Endianness.BigEndian)); } - [TestMethod] + [Test] public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan() { const ushort value = 0x0F; byte[] bytes = BitConverter.IsLittleEndian ? new byte[] {0x0F, 0} : new byte[] {0, 0x0F}; Span buffer = stackalloc byte[2]; - Assert.IsTrue(value.TryWriteBytes(buffer)); + Assert.That(value.TryWriteBytes(buffer)); CollectionAssert.AreEqual(bytes, buffer.ToArray()); } - [TestMethod] + [Test] public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan_WithEndianness() { const ushort value = 0x0F; @@ -46,18 +46,18 @@ public class UInt16Tests Span buffer = stackalloc byte[2]; - Assert.IsTrue(value.TryWriteBytes(buffer, Endianness.LittleEndian)); + Assert.That(value.TryWriteBytes(buffer, Endianness.LittleEndian)); CollectionAssert.AreEqual(littleEndian, buffer.ToArray()); - Assert.IsTrue(value.TryWriteBytes(buffer, Endianness.BigEndian)); + Assert.That(value.TryWriteBytes(buffer, Endianness.BigEndian)); CollectionAssert.AreEqual(bigEndian, buffer.ToArray()); } - [TestMethod] + [Test] public void TryWriteBytes_ReturnsFalse_GivenSmallSpan() { const ushort value = 0x0F; Span buffer = stackalloc byte[0]; - Assert.IsFalse(value.TryWriteBytes(buffer)); + Assert.That(value.TryWriteBytes(buffer), Is.False); } } diff --git a/X10D.Tests/src/IO/UInt32Tests.cs b/X10D.Tests/src/IO/UInt32Tests.cs index a9b3cc9..910aa50 100644 --- a/X10D.Tests/src/IO/UInt32Tests.cs +++ b/X10D.Tests/src/IO/UInt32Tests.cs @@ -1,13 +1,13 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; -[TestClass] +[TestFixture] [CLSCompliant(false)] public class UInt32Tests { - [TestMethod] + [Test] public void GetBytes_ReturnsCorrectValue() { const uint value = 0x0F; @@ -15,7 +15,7 @@ public class UInt32Tests CollectionAssert.AreEqual(bytes, value.GetBytes()); } - [TestMethod] + [Test] public void GetBytes_ReturnsCorrectValue_WithEndianness() { const uint value = 0x0F; @@ -26,18 +26,18 @@ public class UInt32Tests CollectionAssert.AreEqual(bigEndian, value.GetBytes(Endianness.BigEndian)); } - [TestMethod] + [Test] public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan() { const uint value = 0x0F; byte[] bytes = BitConverter.IsLittleEndian ? new byte[] {0x0F, 0, 0, 0} : new byte[] {0, 0, 0, 0x0F}; Span buffer = stackalloc byte[4]; - Assert.IsTrue(value.TryWriteBytes(buffer)); + Assert.That(value.TryWriteBytes(buffer)); CollectionAssert.AreEqual(bytes, buffer.ToArray()); } - [TestMethod] + [Test] public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan_WithEndianness() { const uint value = 0x0F; @@ -46,18 +46,18 @@ public class UInt32Tests Span buffer = stackalloc byte[4]; - Assert.IsTrue(value.TryWriteBytes(buffer, Endianness.LittleEndian)); + Assert.That(value.TryWriteBytes(buffer, Endianness.LittleEndian)); CollectionAssert.AreEqual(littleEndian, buffer.ToArray()); - Assert.IsTrue(value.TryWriteBytes(buffer, Endianness.BigEndian)); + Assert.That(value.TryWriteBytes(buffer, Endianness.BigEndian)); CollectionAssert.AreEqual(bigEndian, buffer.ToArray()); } - [TestMethod] + [Test] public void TryWriteBytes_ReturnsFalse_GivenSmallSpan() { const uint value = 0x0F; Span buffer = stackalloc byte[0]; - Assert.IsFalse(value.TryWriteBytes(buffer)); + Assert.That(value.TryWriteBytes(buffer), Is.False); } } diff --git a/X10D.Tests/src/IO/UInt64Tests.cs b/X10D.Tests/src/IO/UInt64Tests.cs index d31a209..374444f 100644 --- a/X10D.Tests/src/IO/UInt64Tests.cs +++ b/X10D.Tests/src/IO/UInt64Tests.cs @@ -1,13 +1,13 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; -[TestClass] +[TestFixture] [CLSCompliant(false)] public class UInt64Tests { - [TestMethod] + [Test] public void GetBytes_ReturnsCorrectValue() { const ulong value = 0x0F; @@ -17,7 +17,7 @@ public class UInt64Tests CollectionAssert.AreEqual(bytes, value.GetBytes()); } - [TestMethod] + [Test] public void GetBytes_ReturnsCorrectValue_WithEndianness() { const ulong value = 0x0F; @@ -28,7 +28,7 @@ public class UInt64Tests CollectionAssert.AreEqual(bigEndian, value.GetBytes(Endianness.BigEndian)); } - [TestMethod] + [Test] public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan() { const ulong value = 0x0F; @@ -37,11 +37,11 @@ public class UInt64Tests : new byte[] {0, 0, 0, 0, 0, 0, 0, 0x0F}; Span buffer = stackalloc byte[8]; - Assert.IsTrue(value.TryWriteBytes(buffer)); + Assert.That(value.TryWriteBytes(buffer)); CollectionAssert.AreEqual(bytes, buffer.ToArray()); } - [TestMethod] + [Test] public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan_WithEndianness() { const ulong value = 0x0F; @@ -50,18 +50,18 @@ public class UInt64Tests Span buffer = stackalloc byte[8]; - Assert.IsTrue(value.TryWriteBytes(buffer, Endianness.LittleEndian)); + Assert.That(value.TryWriteBytes(buffer, Endianness.LittleEndian)); CollectionAssert.AreEqual(littleEndian, buffer.ToArray()); - Assert.IsTrue(value.TryWriteBytes(buffer, Endianness.BigEndian)); + Assert.That(value.TryWriteBytes(buffer, Endianness.BigEndian)); CollectionAssert.AreEqual(bigEndian, buffer.ToArray()); } - [TestMethod] + [Test] public void TryWriteBytes_ReturnsFalse_GivenSmallSpan() { const ulong value = 0x0F; Span buffer = stackalloc byte[0]; - Assert.IsFalse(value.TryWriteBytes(buffer)); + Assert.That(value.TryWriteBytes(buffer), Is.False); } } diff --git a/X10D.Tests/src/Linq/ByteTests.cs b/X10D.Tests/src/Linq/ByteTests.cs index e98fe31..de2faca 100644 --- a/X10D.Tests/src/Linq/ByteTests.cs +++ b/X10D.Tests/src/Linq/ByteTests.cs @@ -1,48 +1,48 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Linq; namespace X10D.Tests.Linq; -[TestClass] +[TestFixture] public class ByteTests { - [TestMethod] + [Test] public void ProductShouldBeCorrect() { byte Cast(int i) => (byte)i; - Assert.AreEqual(0, Enumerable.Range(0, 10).Select(Cast).Product()); - Assert.AreEqual(1, Enumerable.Range(1, 1).Select(Cast).Product()); - Assert.AreEqual(2, Enumerable.Range(1, 2).Select(Cast).Product()); - Assert.AreEqual(6, Enumerable.Range(1, 3).Select(Cast).Product()); - Assert.AreEqual(24, Enumerable.Range(1, 4).Select(Cast).Product()); - Assert.AreEqual(120, Enumerable.Range(1, 5).Select(Cast).Product()); + Assert.That(Enumerable.Range(0, 10).Select(Cast).Product(), Is.Zero); + Assert.That(Enumerable.Range(1, 1).Select(Cast).Product(), Is.EqualTo(1)); + Assert.That(Enumerable.Range(1, 2).Select(Cast).Product(), Is.EqualTo(2)); + Assert.That(Enumerable.Range(1, 3).Select(Cast).Product(), Is.EqualTo(6)); + Assert.That(Enumerable.Range(1, 4).Select(Cast).Product(), Is.EqualTo(24)); + Assert.That(Enumerable.Range(1, 5).Select(Cast).Product(), Is.EqualTo(120)); // 6! will overflow for byte } - [TestMethod] + [Test] public void ProductOfDoublesShouldBeCorrect() { byte Double(int i) => (byte)(i * 2); - Assert.AreEqual(0, Enumerable.Range(0, 10).Product(Double)); - Assert.AreEqual(2, Enumerable.Range(1, 1).Product(Double)); - Assert.AreEqual(8, Enumerable.Range(1, 2).Product(Double)); - Assert.AreEqual(48, Enumerable.Range(1, 3).Product(Double)); + Assert.That(Enumerable.Range(0, 10).Product(Double), Is.Zero); + Assert.That(Enumerable.Range(1, 1).Product(Double), Is.EqualTo(2)); + Assert.That(Enumerable.Range(1, 2).Product(Double), Is.EqualTo(8)); + Assert.That(Enumerable.Range(1, 3).Product(Double), Is.EqualTo(48)); // Π_(i=1)^n (2i) will overflow at i=4 for byte } - [TestMethod] + [Test] public void Product_ShouldThrowArgumentNullException_GivenNullSource() { IEnumerable source = null!; - Assert.ThrowsException(() => source.Product()); - Assert.ThrowsException(() => source.Product(v => v)); + Assert.Throws(() => source.Product()); + Assert.Throws(() => source.Product(v => v)); } - [TestMethod] + [Test] public void RangeTo_Byte_ShouldYieldCorrectValues() { const byte start = 1; @@ -51,13 +51,13 @@ public class ByteTests byte current = 1; foreach (byte value in start.RangeTo(end)) { - Assert.AreEqual(current++, value); + Assert.That(value, Is.EqualTo(current++)); } - Assert.AreEqual(current, end); + Assert.That(end, Is.EqualTo(current)); } - [TestMethod] + [Test] public void RangeTo_Int16_ShouldYieldCorrectValues() { const byte start = 1; @@ -66,13 +66,13 @@ public class ByteTests short current = 1; foreach (short value in start.RangeTo(end)) { - Assert.AreEqual(current++, value); + Assert.That(value, Is.EqualTo(current++)); } - Assert.AreEqual(current, end); + Assert.That(end, Is.EqualTo(current)); } - [TestMethod] + [Test] public void RangeTo_Int32_ShouldYieldCorrectValues() { const byte start = 1; @@ -81,13 +81,13 @@ public class ByteTests int current = 1; foreach (int value in start.RangeTo(end)) { - Assert.AreEqual(current++, value); + Assert.That(value, Is.EqualTo(current++)); } - Assert.AreEqual(current, end); + Assert.That(end, Is.EqualTo(current)); } - [TestMethod] + [Test] public void RangeTo_Int64_ShouldYieldCorrectValues() { const byte start = 1; @@ -96,9 +96,9 @@ public class ByteTests long current = 1; foreach (long value in start.RangeTo(end)) { - Assert.AreEqual(current++, value); + Assert.That(value, Is.EqualTo(current++)); } - Assert.AreEqual(current, end); + Assert.That(end, Is.EqualTo(current)); } } diff --git a/X10D.Tests/src/Linq/DecimalTests.cs b/X10D.Tests/src/Linq/DecimalTests.cs index 6fd9da4..93a73b5 100644 --- a/X10D.Tests/src/Linq/DecimalTests.cs +++ b/X10D.Tests/src/Linq/DecimalTests.cs @@ -1,52 +1,58 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Linq; namespace X10D.Tests.Linq; -[TestClass] +[TestFixture] public class DecimalTests { - [TestMethod] + [Test] public void ProductShouldBeCorrect() { decimal Cast(int i) => i; - Assert.AreEqual(0m, Enumerable.Range(0, 10).Select(Cast).Product()); - Assert.AreEqual(1m, Enumerable.Range(1, 1).Select(Cast).Product()); - Assert.AreEqual(2m, Enumerable.Range(1, 2).Select(Cast).Product()); - Assert.AreEqual(6m, Enumerable.Range(1, 3).Select(Cast).Product()); - Assert.AreEqual(24m, Enumerable.Range(1, 4).Select(Cast).Product()); - Assert.AreEqual(120m, Enumerable.Range(1, 5).Select(Cast).Product()); - Assert.AreEqual(720m, Enumerable.Range(1, 6).Select(Cast).Product()); - Assert.AreEqual(5040m, Enumerable.Range(1, 7).Select(Cast).Product()); - Assert.AreEqual(40320m, Enumerable.Range(1, 8).Select(Cast).Product()); - Assert.AreEqual(362880m, Enumerable.Range(1, 9).Select(Cast).Product()); - Assert.AreEqual(3628800m, Enumerable.Range(1, 10).Select(Cast).Product()); + Assert.Multiple(() => + { + Assert.That(Enumerable.Range(0, 10).Select(Cast).Product(), Is.EqualTo(0m)); + Assert.That(Enumerable.Range(1, 1).Select(Cast).Product(), Is.EqualTo(1m)); + Assert.That(Enumerable.Range(1, 2).Select(Cast).Product(), Is.EqualTo(2m)); + Assert.That(Enumerable.Range(1, 3).Select(Cast).Product(), Is.EqualTo(6m)); + Assert.That(Enumerable.Range(1, 4).Select(Cast).Product(), Is.EqualTo(24m)); + Assert.That(Enumerable.Range(1, 5).Select(Cast).Product(), Is.EqualTo(120m)); + Assert.That(Enumerable.Range(1, 6).Select(Cast).Product(), Is.EqualTo(720m)); + Assert.That(Enumerable.Range(1, 7).Select(Cast).Product(), Is.EqualTo(5040m)); + Assert.That(Enumerable.Range(1, 8).Select(Cast).Product(), Is.EqualTo(40320m)); + Assert.That(Enumerable.Range(1, 9).Select(Cast).Product(), Is.EqualTo(362880m)); + Assert.That(Enumerable.Range(1, 10).Select(Cast).Product(), Is.EqualTo(3628800m)); + }); } - [TestMethod] + [Test] public void ProductOfDoublesShouldBeCorrect() { decimal Double(int i) => i * 2m; - Assert.AreEqual(0m, Enumerable.Range(0, 10).Product(Double)); - Assert.AreEqual(2m, Enumerable.Range(1, 1).Product(Double)); - Assert.AreEqual(8m, Enumerable.Range(1, 2).Product(Double)); - Assert.AreEqual(48m, Enumerable.Range(1, 3).Product(Double)); - Assert.AreEqual(384m, Enumerable.Range(1, 4).Product(Double)); - Assert.AreEqual(3840m, Enumerable.Range(1, 5).Product(Double)); - Assert.AreEqual(46080m, Enumerable.Range(1, 6).Product(Double)); - Assert.AreEqual(645120m, Enumerable.Range(1, 7).Product(Double)); - Assert.AreEqual(10321920m, Enumerable.Range(1, 8).Product(Double)); - Assert.AreEqual(185794560m, Enumerable.Range(1, 9).Product(Double)); - Assert.AreEqual(3715891200m, Enumerable.Range(1, 10).Product(Double)); + Assert.Multiple(() => + { + Assert.That(Enumerable.Range(0, 10).Product(Double), Is.EqualTo(0m)); + Assert.That(Enumerable.Range(1, 1).Product(Double), Is.EqualTo(2m)); + Assert.That(Enumerable.Range(1, 2).Product(Double), Is.EqualTo(8m)); + Assert.That(Enumerable.Range(1, 3).Product(Double), Is.EqualTo(48m)); + Assert.That(Enumerable.Range(1, 4).Product(Double), Is.EqualTo(384m)); + Assert.That(Enumerable.Range(1, 5).Product(Double), Is.EqualTo(3840m)); + Assert.That(Enumerable.Range(1, 6).Product(Double), Is.EqualTo(46080m)); + Assert.That(Enumerable.Range(1, 7).Product(Double), Is.EqualTo(645120m)); + Assert.That(Enumerable.Range(1, 8).Product(Double), Is.EqualTo(10321920m)); + Assert.That(Enumerable.Range(1, 9).Product(Double), Is.EqualTo(185794560m)); + Assert.That(Enumerable.Range(1, 10).Product(Double), Is.EqualTo(3715891200m)); + }); } - [TestMethod] + [Test] public void Product_ShouldThrowArgumentNullException_GivenNullSource() { IEnumerable source = null!; - Assert.ThrowsException(() => source.Product()); - Assert.ThrowsException(() => source.Product(v => v)); + Assert.Throws(() => source.Product()); + Assert.Throws(() => source.Product(v => v)); } } diff --git a/X10D.Tests/src/Linq/DoubleTests.cs b/X10D.Tests/src/Linq/DoubleTests.cs index 1a54fbd..b5234c2 100644 --- a/X10D.Tests/src/Linq/DoubleTests.cs +++ b/X10D.Tests/src/Linq/DoubleTests.cs @@ -1,52 +1,58 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Linq; namespace X10D.Tests.Linq; -[TestClass] +[TestFixture] public class DoubleTests { - [TestMethod] + [Test] public void ProductShouldBeCorrect() { double Cast(int i) => i; - Assert.AreEqual(0.0, Enumerable.Range(0, 10).Select(Cast).Product()); - Assert.AreEqual(1.0, Enumerable.Range(1, 1).Select(Cast).Product()); - Assert.AreEqual(2.0, Enumerable.Range(1, 2).Select(Cast).Product()); - Assert.AreEqual(6.0, Enumerable.Range(1, 3).Select(Cast).Product()); - Assert.AreEqual(24.0, Enumerable.Range(1, 4).Select(Cast).Product()); - Assert.AreEqual(120.0, Enumerable.Range(1, 5).Select(Cast).Product()); - Assert.AreEqual(720.0, Enumerable.Range(1, 6).Select(Cast).Product()); - Assert.AreEqual(5040.0, Enumerable.Range(1, 7).Select(Cast).Product()); - Assert.AreEqual(40320.0, Enumerable.Range(1, 8).Select(Cast).Product()); - Assert.AreEqual(362880.0, Enumerable.Range(1, 9).Select(Cast).Product()); - Assert.AreEqual(3628800.0, Enumerable.Range(1, 10).Select(Cast).Product()); + Assert.Multiple(() => + { + Assert.That(Enumerable.Range(0, 10).Select(Cast).Product(), Is.EqualTo(0.0)); + Assert.That(Enumerable.Range(1, 1).Select(Cast).Product(), Is.EqualTo(1.0)); + Assert.That(Enumerable.Range(1, 2).Select(Cast).Product(), Is.EqualTo(2.0)); + Assert.That(Enumerable.Range(1, 3).Select(Cast).Product(), Is.EqualTo(6.0)); + Assert.That(Enumerable.Range(1, 4).Select(Cast).Product(), Is.EqualTo(24.0)); + Assert.That(Enumerable.Range(1, 5).Select(Cast).Product(), Is.EqualTo(120.0)); + Assert.That(Enumerable.Range(1, 6).Select(Cast).Product(), Is.EqualTo(720.0)); + Assert.That(Enumerable.Range(1, 7).Select(Cast).Product(), Is.EqualTo(5040.0)); + Assert.That(Enumerable.Range(1, 8).Select(Cast).Product(), Is.EqualTo(40320.0)); + Assert.That(Enumerable.Range(1, 9).Select(Cast).Product(), Is.EqualTo(362880.0)); + Assert.That(Enumerable.Range(1, 10).Select(Cast).Product(), Is.EqualTo(3628800.0)); + }); } - [TestMethod] + [Test] public void ProductOfDoublesShouldBeCorrect() { double Double(int i) => i * 2.0; - Assert.AreEqual(0.0, Enumerable.Range(0, 10).Product(Double)); - Assert.AreEqual(2.0, Enumerable.Range(1, 1).Product(Double)); - Assert.AreEqual(8.0, Enumerable.Range(1, 2).Product(Double)); - Assert.AreEqual(48.0, Enumerable.Range(1, 3).Product(Double)); - Assert.AreEqual(384.0, Enumerable.Range(1, 4).Product(Double)); - Assert.AreEqual(3840.0, Enumerable.Range(1, 5).Product(Double)); - Assert.AreEqual(46080.0, Enumerable.Range(1, 6).Product(Double)); - Assert.AreEqual(645120.0, Enumerable.Range(1, 7).Product(Double)); - Assert.AreEqual(10321920.0, Enumerable.Range(1, 8).Product(Double)); - Assert.AreEqual(185794560.0, Enumerable.Range(1, 9).Product(Double)); - Assert.AreEqual(3715891200.0, Enumerable.Range(1, 10).Product(Double)); + Assert.Multiple(() => + { + Assert.That(Enumerable.Range(0, 10).Product(Double), Is.EqualTo(0.0)); + Assert.That(Enumerable.Range(1, 1).Product(Double), Is.EqualTo(2.0)); + Assert.That(Enumerable.Range(1, 2).Product(Double), Is.EqualTo(8.0)); + Assert.That(Enumerable.Range(1, 3).Product(Double), Is.EqualTo(48.0)); + Assert.That(Enumerable.Range(1, 4).Product(Double), Is.EqualTo(384.0)); + Assert.That(Enumerable.Range(1, 5).Product(Double), Is.EqualTo(3840.0)); + Assert.That(Enumerable.Range(1, 6).Product(Double), Is.EqualTo(46080.0)); + Assert.That(Enumerable.Range(1, 7).Product(Double), Is.EqualTo(645120.0)); + Assert.That(Enumerable.Range(1, 8).Product(Double), Is.EqualTo(10321920.0)); + Assert.That(Enumerable.Range(1, 9).Product(Double), Is.EqualTo(185794560.0)); + Assert.That(Enumerable.Range(1, 10).Product(Double), Is.EqualTo(3715891200.0)); + }); } - [TestMethod] + [Test] public void Product_ShouldThrowArgumentNullException_GivenNullSource() { IEnumerable source = null!; - Assert.ThrowsException(() => source.Product()); - Assert.ThrowsException(() => source.Product(v => v)); + Assert.Throws(() => source.Product()); + Assert.Throws(() => source.Product(v => v)); } } diff --git a/X10D.Tests/src/Linq/EnumerableTests.cs b/X10D.Tests/src/Linq/EnumerableTests.cs index 5318d4b..6d0a2e4 100644 --- a/X10D.Tests/src/Linq/EnumerableTests.cs +++ b/X10D.Tests/src/Linq/EnumerableTests.cs @@ -1,12 +1,12 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Linq; namespace X10D.Tests.Linq; -[TestClass] +[TestFixture] public class EnumerableTests { - [TestMethod] + [Test] public void ConcatOne_ShouldReturnConcatenatedSequence_GivenValidSequenceAndValue() { IEnumerable source = new[] {"Hello"}; @@ -14,11 +14,11 @@ public class EnumerableTests string[] actual = source.ConcatOne("World").ToArray(); - Assert.AreEqual(2, actual.Length); + Assert.That(actual, Has.Length.EqualTo(2)); CollectionAssert.AreEqual(expected, actual); } - [TestMethod] + [Test] public void ConcatOne_ShouldReturnSingletonSequence_GivenEmptySequenceAndValidValue() { IEnumerable source = Enumerable.Empty(); @@ -26,159 +26,195 @@ public class EnumerableTests string[] actual = source.ConcatOne("Foobar").ToArray(); - Assert.AreEqual(1, actual.Length); + Assert.That(actual, Has.Length.EqualTo(1)); CollectionAssert.AreEqual(expected, actual); } - [TestMethod] + [Test] public void ConcatOne_ShouldThrowArgumentNullException_GivenNullSource() { IEnumerable? source = null; - Assert.ThrowsException(() => source!.ConcatOne("Foobar").ToArray()); + Assert.Throws(() => source!.ConcatOne("Foobar").ToArray()); } - [TestMethod] + [Test] public void MinMax_ShouldReturnCorrectValues_UsingDefaultComparer() { IEnumerable source = Enumerable.Range(1, 10); (int minimum, int maximum) = source.MinMax(); - Assert.AreEqual(1, minimum); - Assert.AreEqual(10, maximum); + Assert.Multiple(() => + { + Assert.That(minimum, Is.EqualTo(1)); + Assert.That(maximum, Is.EqualTo(10)); + }); source = Enumerable.Range(1, 10).ToArray(); (minimum, maximum) = source.MinMax(); - Assert.AreEqual(1, minimum); - Assert.AreEqual(10, maximum); + Assert.Multiple(() => + { + Assert.That(minimum, Is.EqualTo(1)); + Assert.That(maximum, Is.EqualTo(10)); + }); } - [TestMethod] + [Test] public void MinMax_ShouldReturnCorrectSelectedValues_UsingDefaultComparer() { IEnumerable source = Enumerable.Range(1, 10).Select(i => new Person {Age = i}); (int minimum, int maximum) = source.MinMax(p => p.Age); - Assert.AreEqual(1, minimum); - Assert.AreEqual(10, maximum); + Assert.Multiple(() => + { + Assert.That(minimum, Is.EqualTo(1)); + Assert.That(maximum, Is.EqualTo(10)); + }); source = Enumerable.Range(1, 10).Select(i => new Person {Age = i}).ToArray(); (minimum, maximum) = source.MinMax(p => p.Age); - Assert.AreEqual(1, minimum); - Assert.AreEqual(10, maximum); + Assert.Multiple(() => + { + Assert.That(minimum, Is.EqualTo(1)); + Assert.That(maximum, Is.EqualTo(10)); + }); } - [TestMethod] + [Test] public void MinMax_ShouldReturnOppositeSelectedValues_UsingInverseComparer() { IEnumerable source = Enumerable.Range(1, 10).Select(i => new Person {Age = i}); (int minimum, int maximum) = source.MinMax(p => p.Age, new InverseComparer()); - Assert.AreEqual(10, minimum); - Assert.AreEqual(1, maximum); + Assert.Multiple(() => + { + Assert.That(minimum, Is.EqualTo(10)); + Assert.That(maximum, Is.EqualTo(1)); + }); source = Enumerable.Range(1, 10).Select(i => new Person {Age = i}).ToArray(); (minimum, maximum) = source.MinMax(p => p.Age, new InverseComparer()); - Assert.AreEqual(10, minimum); - Assert.AreEqual(1, maximum); + Assert.Multiple(() => + { + Assert.That(minimum, Is.EqualTo(10)); + Assert.That(maximum, Is.EqualTo(1)); + }); } - [TestMethod] + [Test] public void MinMax_ShouldReturnOppositeValues_UsingInverseComparer() { (int minimum, int maximum) = Enumerable.Range(1, 10).MinMax(new InverseComparer()); - Assert.AreEqual(10, minimum); - Assert.AreEqual(1, maximum); + Assert.Multiple(() => + { + Assert.That(minimum, Is.EqualTo(10)); + Assert.That(maximum, Is.EqualTo(1)); + }); (minimum, maximum) = Enumerable.Range(1, 10).ToArray().MinMax(new InverseComparer()); - Assert.AreEqual(10, minimum); - Assert.AreEqual(1, maximum); + Assert.Multiple(() => + { + Assert.That(minimum, Is.EqualTo(10)); + Assert.That(maximum, Is.EqualTo(1)); + }); } - [TestMethod] + [Test] public void MinMax_ShouldThrowArgumentNullException_GivenNullSelector() { IEnumerable source = Enumerable.Empty(); - Assert.ThrowsException(() => source.MinMax((Func)(null!))); - Assert.ThrowsException(() => source.MinMax((Func)(null!), null)); + Assert.Throws(() => source.MinMax((Func)(null!))); + Assert.Throws(() => source.MinMax((Func)(null!), null)); } - [TestMethod] + [Test] public void MinMax_ShouldThrowArgumentNullException_GivenNullSource() { IEnumerable? source = null; - Assert.ThrowsException(() => source!.MinMax()); - Assert.ThrowsException(() => source!.MinMax(v => v)); - Assert.ThrowsException(() => source!.MinMax(null)); - Assert.ThrowsException(() => source!.MinMax(v => v, null)); + Assert.Throws(() => source!.MinMax()); + Assert.Throws(() => source!.MinMax(v => v)); + Assert.Throws(() => source!.MinMax(null)); + Assert.Throws(() => source!.MinMax(v => v, null)); } - [TestMethod] + [Test] public void MinMax_ShouldThrowInvalidOperationException_GivenEmptySource() { - Assert.ThrowsException(() => Enumerable.Empty().MinMax()); - Assert.ThrowsException(() => Array.Empty().MinMax()); - Assert.ThrowsException(() => new List().MinMax()); + Assert.Throws(() => Enumerable.Empty().MinMax()); + Assert.Throws(() => Array.Empty().MinMax()); + Assert.Throws(() => new List().MinMax()); - Assert.ThrowsException(() => Enumerable.Empty().MinMax(i => i * 2)); - Assert.ThrowsException(() => Array.Empty().MinMax(i => i * 2)); - Assert.ThrowsException(() => new List().MinMax(i => i * 2)); + Assert.Throws(() => Enumerable.Empty().MinMax(i => i * 2)); + Assert.Throws(() => Array.Empty().MinMax(i => i * 2)); + Assert.Throws(() => new List().MinMax(i => i * 2)); } - [TestMethod] + [Test] public void MinMaxBy_ShouldReturnCorrectSelectedValues_UsingDefaultComparer() { IEnumerable source = Enumerable.Range(1, 10).Select(i => new Person {Age = i}); (Person minimum, Person maximum) = source.MinMaxBy(p => p.Age); - Assert.AreEqual(1, minimum.Age); - Assert.AreEqual(10, maximum.Age); + Assert.Multiple(() => + { + Assert.That(minimum.Age, Is.EqualTo(1)); + Assert.That(maximum.Age, Is.EqualTo(10)); + }); source = Enumerable.Range(1, 10).Select(i => new Person {Age = i}).ToArray(); (minimum, maximum) = source.MinMaxBy(p => p.Age); - Assert.AreEqual(1, minimum.Age); - Assert.AreEqual(10, maximum.Age); + Assert.Multiple(() => + { + Assert.That(minimum.Age, Is.EqualTo(1)); + Assert.That(maximum.Age, Is.EqualTo(10)); + }); } - [TestMethod] + [Test] public void MinMaxBy_ShouldReturnOppositeSelectedValues_UsingInverseComparer() { IEnumerable source = Enumerable.Range(1, 10).Select(i => new Person {Age = i}); (Person minimum, Person maximum) = source.MinMaxBy(p => p.Age, new InverseComparer()); - Assert.AreEqual(10, minimum.Age); - Assert.AreEqual(1, maximum.Age); + Assert.Multiple(() => + { + Assert.That(minimum.Age, Is.EqualTo(10)); + Assert.That(maximum.Age, Is.EqualTo(1)); + }); source = Enumerable.Range(1, 10).Select(i => new Person {Age = i}).ToArray(); (minimum, maximum) = source.MinMaxBy(p => p.Age, new InverseComparer()); - Assert.AreEqual(10, minimum.Age); - Assert.AreEqual(1, maximum.Age); + Assert.Multiple(() => + { + Assert.That(minimum.Age, Is.EqualTo(10)); + Assert.That(maximum.Age, Is.EqualTo(1)); + }); } - [TestMethod] + [Test] public void MinMaxBy_ShouldThrowArgumentNullException_GivenNullSelector() { Person[] source = Enumerable.Range(1, 10).Select(i => new Person {Age = i}).ToArray(); - Assert.ThrowsException(() => source.MinMaxBy((Func)null!)); - Assert.ThrowsException(() => source.MinMaxBy((Func)null!, null)); + Assert.Throws(() => source.MinMaxBy((Func)null!)); + Assert.Throws(() => source.MinMaxBy((Func)null!, null)); } - [TestMethod] + [Test] public void MinMaxBy_ShouldThrowArgumentNullException_GivenNullSource() { IEnumerable? source = null; - Assert.ThrowsException(() => source!.MinMaxBy(p => p.Age)); - Assert.ThrowsException(() => source!.MinMaxBy(p => p.Age, null)); + Assert.Throws(() => source!.MinMaxBy(p => p.Age)); + Assert.Throws(() => source!.MinMaxBy(p => p.Age, null)); } - [TestMethod] + [Test] public void MinMaxBy_ShouldThrowInvalidOperationException_GivenEmptySource() { - Assert.ThrowsException(() => + Assert.Throws(() => { IEnumerable source = Enumerable.Empty(); - return source.MinMaxBy(p => p.Age); + _ = source.MinMaxBy(p => p.Age); }); - Assert.ThrowsException(() => + Assert.Throws(() => { Person[] source = Array.Empty(); - return source.MinMaxBy(p => p.Age); + _ = source.MinMaxBy(p => p.Age); }); } diff --git a/X10D.Tests/src/Linq/Int16Tests.cs b/X10D.Tests/src/Linq/Int16Tests.cs index aa23e62..2a8459d 100644 --- a/X10D.Tests/src/Linq/Int16Tests.cs +++ b/X10D.Tests/src/Linq/Int16Tests.cs @@ -1,92 +1,95 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Linq; namespace X10D.Tests.Linq; -[TestClass] +[TestFixture] public class Int16Tests { - [TestMethod] + [Test] public void ProductShouldBeCorrect() { short Cast(int i) => (short)i; - - Assert.AreEqual(0, Enumerable.Range(0, 10).Select(Cast).Product()); - Assert.AreEqual(1, Enumerable.Range(1, 1).Select(Cast).Product()); - Assert.AreEqual(2, Enumerable.Range(1, 2).Select(Cast).Product()); - Assert.AreEqual(6, Enumerable.Range(1, 3).Select(Cast).Product()); - Assert.AreEqual(24, Enumerable.Range(1, 4).Select(Cast).Product()); - Assert.AreEqual(120, Enumerable.Range(1, 5).Select(Cast).Product()); - Assert.AreEqual(720, Enumerable.Range(1, 6).Select(Cast).Product()); - Assert.AreEqual(5040, Enumerable.Range(1, 7).Select(Cast).Product()); - - // 8! will overflow for short + Assert.Multiple(() => + { + Assert.That(Enumerable.Range(0, 10).Select(Cast).Product(), Is.Zero); + Assert.That(Enumerable.Range(1, 1).Select(Cast).Product(), Is.EqualTo(1)); + Assert.That(Enumerable.Range(1, 2).Select(Cast).Product(), Is.EqualTo(2)); + Assert.That(Enumerable.Range(1, 3).Select(Cast).Product(), Is.EqualTo(6)); + Assert.That(Enumerable.Range(1, 4).Select(Cast).Product(), Is.EqualTo(24)); + Assert.That(Enumerable.Range(1, 5).Select(Cast).Product(), Is.EqualTo(120)); + Assert.That(Enumerable.Range(1, 6).Select(Cast).Product(), Is.EqualTo(720)); + Assert.That(Enumerable.Range(1, 7).Select(Cast).Product(), Is.EqualTo(5040)); + }); } - [TestMethod] + [Test] public void ProductOfDoublesShouldBeCorrect() { short Double(int i) => (short)(i * 2); - Assert.AreEqual(0, Enumerable.Range(0, 10).Product(Double)); - Assert.AreEqual(2, Enumerable.Range(1, 1).Product(Double)); - Assert.AreEqual(8, Enumerable.Range(1, 2).Product(Double)); - Assert.AreEqual(48, Enumerable.Range(1, 3).Product(Double)); - Assert.AreEqual(384, Enumerable.Range(1, 4).Product(Double)); - Assert.AreEqual(3840, Enumerable.Range(1, 5).Product(Double)); + Assert.That(Enumerable.Range(0, 10).Product(Double), Is.Zero); + Assert.That(Enumerable.Range(1, 1).Product(Double), Is.EqualTo(2)); + Assert.That(Enumerable.Range(1, 2).Product(Double), Is.EqualTo(8)); + Assert.That(Enumerable.Range(1, 3).Product(Double), Is.EqualTo(48)); + Assert.That(Enumerable.Range(1, 4).Product(Double), Is.EqualTo(384)); + Assert.That(Enumerable.Range(1, 5).Product(Double), Is.EqualTo(3840)); // Π_(i=1)^n (2i) will overflow at i=6 for short } - [TestMethod] + [Test] public void Product_ShouldThrowArgumentNullException_GivenNullSource() { IEnumerable source = null!; - Assert.ThrowsException(() => source.Product()); + Assert.Throws(() => source.Product()); } - [TestMethod] + [Test] public void RangeTo_Int16_ShouldYieldCorrectValues() { const short start = 1; const short end = 10; short current = 1; + foreach (short value in start.RangeTo(end)) { - Assert.AreEqual(current++, value); + Assert.That(value, Is.EqualTo(current++)); } - Assert.AreEqual(current, end); + Assert.That(current, Is.EqualTo(end)); } - [TestMethod] + [Test] public void RangeTo_Int32_ShouldYieldCorrectValues() { const short start = 1; const int end = 10; - int current = 1; + var current = 1; + foreach (int value in start.RangeTo(end)) { - Assert.AreEqual(current++, value); + Assert.That(value, Is.EqualTo(current++)); } - Assert.AreEqual(current, end); + Assert.That(current, Is.EqualTo(end)); } - [TestMethod] + [Test] public void RangeTo_Int64_ShouldYieldCorrectValues() { const short start = 1; const long end = 10; long current = 1; + foreach (long value in start.RangeTo(end)) { - Assert.AreEqual(current++, value); + Assert.That(value, Is.EqualTo(current++)); } - Assert.AreEqual(current, end); + Assert.That(current, Is.EqualTo(end)); } } diff --git a/X10D.Tests/src/Linq/Int32Tests.cs b/X10D.Tests/src/Linq/Int32Tests.cs index dc45267..0113712 100644 --- a/X10D.Tests/src/Linq/Int32Tests.cs +++ b/X10D.Tests/src/Linq/Int32Tests.cs @@ -1,55 +1,55 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Linq; namespace X10D.Tests.Linq; -[TestClass] +[TestFixture] public class Int32Tests { - [TestMethod] + [Test] public void ProductShouldBeCorrect() { - Assert.AreEqual(0, Enumerable.Range(0, 10).Product()); - Assert.AreEqual(1, Enumerable.Range(1, 1).Product()); - Assert.AreEqual(2, Enumerable.Range(1, 2).Product()); - Assert.AreEqual(6, Enumerable.Range(1, 3).Product()); - Assert.AreEqual(24, Enumerable.Range(1, 4).Product()); - Assert.AreEqual(120, Enumerable.Range(1, 5).Product()); - Assert.AreEqual(720, Enumerable.Range(1, 6).Product()); - Assert.AreEqual(5040, Enumerable.Range(1, 7).Product()); - Assert.AreEqual(40320, Enumerable.Range(1, 8).Product()); - Assert.AreEqual(362880, Enumerable.Range(1, 9).Product()); - Assert.AreEqual(3628800, Enumerable.Range(1, 10).Product()); + Assert.That(Enumerable.Range(0, 10).Product(), Is.Zero); + Assert.That(Enumerable.Range(1, 1).Product(), Is.EqualTo(1)); + Assert.That(Enumerable.Range(1, 2).Product(), Is.EqualTo(2)); + Assert.That(Enumerable.Range(1, 3).Product(), Is.EqualTo(6)); + Assert.That(Enumerable.Range(1, 4).Product(), Is.EqualTo(24)); + Assert.That(Enumerable.Range(1, 5).Product(), Is.EqualTo(120)); + Assert.That(Enumerable.Range(1, 6).Product(), Is.EqualTo(720)); + Assert.That(Enumerable.Range(1, 7).Product(), Is.EqualTo(5040)); + Assert.That(Enumerable.Range(1, 8).Product(), Is.EqualTo(40320)); + Assert.That(Enumerable.Range(1, 9).Product(), Is.EqualTo(362880)); + Assert.That(Enumerable.Range(1, 10).Product(), Is.EqualTo(3628800)); } - [TestMethod] + [Test] public void ProductOfDoublesShouldBeCorrect() { int Double(int i) => i * 2; - Assert.AreEqual(0, Enumerable.Range(0, 10).Product(Double)); - Assert.AreEqual(2, Enumerable.Range(1, 1).Product(Double)); - Assert.AreEqual(8, Enumerable.Range(1, 2).Product(Double)); - Assert.AreEqual(48, Enumerable.Range(1, 3).Product(Double)); - Assert.AreEqual(384, Enumerable.Range(1, 4).Product(Double)); - Assert.AreEqual(3840, Enumerable.Range(1, 5).Product(Double)); - Assert.AreEqual(46080, Enumerable.Range(1, 6).Product(Double)); - Assert.AreEqual(645120, Enumerable.Range(1, 7).Product(Double)); - Assert.AreEqual(10321920, Enumerable.Range(1, 8).Product(Double)); - Assert.AreEqual(185794560, Enumerable.Range(1, 9).Product(Double)); + Assert.That(Enumerable.Range(0, 10).Product(Double), Is.Zero); + Assert.That(Enumerable.Range(1, 1).Product(Double), Is.EqualTo(2)); + Assert.That(Enumerable.Range(1, 2).Product(Double), Is.EqualTo(8)); + Assert.That(Enumerable.Range(1, 3).Product(Double), Is.EqualTo(48)); + Assert.That(Enumerable.Range(1, 4).Product(Double), Is.EqualTo(384)); + Assert.That(Enumerable.Range(1, 5).Product(Double), Is.EqualTo(3840)); + Assert.That(Enumerable.Range(1, 6).Product(Double), Is.EqualTo(46080)); + Assert.That(Enumerable.Range(1, 7).Product(Double), Is.EqualTo(645120)); + Assert.That(Enumerable.Range(1, 8).Product(Double), Is.EqualTo(10321920)); + Assert.That(Enumerable.Range(1, 9).Product(Double), Is.EqualTo(185794560)); // Π_(i=1)^n (2i) will overflow at i=10 for int } - [TestMethod] + [Test] public void Product_ShouldThrowArgumentNullException_GivenNullSource() { IEnumerable source = null!; - Assert.ThrowsException(() => source.Product()); - Assert.ThrowsException(() => source.Product(v => v)); + Assert.Throws(() => source.Product()); + Assert.Throws(() => source.Product(v => v)); } - [TestMethod] + [Test] public void RangeTo_Int32_ShouldYieldCorrectValues() { const int start = 1; @@ -58,13 +58,13 @@ public class Int32Tests int current = 1; foreach (int value in start.RangeTo(end)) { - Assert.AreEqual(current++, value); + Assert.That(value, Is.EqualTo(current++)); } - Assert.AreEqual(current, end); + Assert.That(end, Is.EqualTo(current)); } - [TestMethod] + [Test] public void RangeTo_Int64_ShouldYieldCorrectValues() { const int start = 1; @@ -73,9 +73,9 @@ public class Int32Tests long current = 1; foreach (long value in start.RangeTo(end)) { - Assert.AreEqual(current++, value); + Assert.That(value, Is.EqualTo(current++)); } - Assert.AreEqual(current, end); + Assert.That(end, Is.EqualTo(current)); } } diff --git a/X10D.Tests/src/Linq/Int64Tests.cs b/X10D.Tests/src/Linq/Int64Tests.cs index ebbb1fa..946a86d 100644 --- a/X10D.Tests/src/Linq/Int64Tests.cs +++ b/X10D.Tests/src/Linq/Int64Tests.cs @@ -1,56 +1,56 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Linq; namespace X10D.Tests.Linq; -[TestClass] +[TestFixture] public class Int64Tests { - [TestMethod] + [Test] public void ProductShouldBeCorrect() { long Cast(int i) => i; - Assert.AreEqual(0, Enumerable.Range(0, 10).Select(Cast).Product()); - Assert.AreEqual(1, Enumerable.Range(1, 1).Select(Cast).Product()); - Assert.AreEqual(2, Enumerable.Range(1, 2).Select(Cast).Product()); - Assert.AreEqual(6, Enumerable.Range(1, 3).Select(Cast).Product()); - Assert.AreEqual(24, Enumerable.Range(1, 4).Select(Cast).Product()); - Assert.AreEqual(120, Enumerable.Range(1, 5).Select(Cast).Product()); - Assert.AreEqual(720, Enumerable.Range(1, 6).Select(Cast).Product()); - Assert.AreEqual(5040, Enumerable.Range(1, 7).Select(Cast).Product()); - Assert.AreEqual(40320, Enumerable.Range(1, 8).Select(Cast).Product()); - Assert.AreEqual(362880, Enumerable.Range(1, 9).Select(Cast).Product()); - Assert.AreEqual(3628800, Enumerable.Range(1, 10).Select(Cast).Product()); + Assert.That(Enumerable.Range(0, 10).Select(Cast).Product(), Is.Zero); + Assert.That(Enumerable.Range(1, 1).Select(Cast).Product(), Is.EqualTo(1)); + Assert.That(Enumerable.Range(1, 2).Select(Cast).Product(), Is.EqualTo(2)); + Assert.That(Enumerable.Range(1, 3).Select(Cast).Product(), Is.EqualTo(6)); + Assert.That(Enumerable.Range(1, 4).Select(Cast).Product(), Is.EqualTo(24)); + Assert.That(Enumerable.Range(1, 5).Select(Cast).Product(), Is.EqualTo(120)); + Assert.That(Enumerable.Range(1, 6).Select(Cast).Product(), Is.EqualTo(720)); + Assert.That(Enumerable.Range(1, 7).Select(Cast).Product(), Is.EqualTo(5040)); + Assert.That(Enumerable.Range(1, 8).Select(Cast).Product(), Is.EqualTo(40320)); + Assert.That(Enumerable.Range(1, 9).Select(Cast).Product(), Is.EqualTo(362880)); + Assert.That(Enumerable.Range(1, 10).Select(Cast).Product(), Is.EqualTo(3628800)); } - [TestMethod] + [Test] public void ProductOfDoublesShouldBeCorrect() { long Double(int i) => i * 2; - Assert.AreEqual(0, Enumerable.Range(0, 10).Product(Double)); - Assert.AreEqual(2, Enumerable.Range(1, 1).Product(Double)); - Assert.AreEqual(8, Enumerable.Range(1, 2).Product(Double)); - Assert.AreEqual(48, Enumerable.Range(1, 3).Product(Double)); - Assert.AreEqual(384, Enumerable.Range(1, 4).Product(Double)); - Assert.AreEqual(3840, Enumerable.Range(1, 5).Product(Double)); - Assert.AreEqual(46080, Enumerable.Range(1, 6).Product(Double)); - Assert.AreEqual(645120, Enumerable.Range(1, 7).Product(Double)); - Assert.AreEqual(10321920, Enumerable.Range(1, 8).Product(Double)); - Assert.AreEqual(185794560, Enumerable.Range(1, 9).Product(Double)); - Assert.AreEqual(3715891200, Enumerable.Range(1, 10).Product(Double)); + Assert.That(Enumerable.Range(0, 10).Product(Double), Is.Zero); + Assert.That(Enumerable.Range(1, 1).Product(Double), Is.EqualTo(2)); + Assert.That(Enumerable.Range(1, 2).Product(Double), Is.EqualTo(8)); + Assert.That(Enumerable.Range(1, 3).Product(Double), Is.EqualTo(48)); + Assert.That(Enumerable.Range(1, 4).Product(Double), Is.EqualTo(384)); + Assert.That(Enumerable.Range(1, 5).Product(Double), Is.EqualTo(3840)); + Assert.That(Enumerable.Range(1, 6).Product(Double), Is.EqualTo(46080)); + Assert.That(Enumerable.Range(1, 7).Product(Double), Is.EqualTo(645120)); + Assert.That(Enumerable.Range(1, 8).Product(Double), Is.EqualTo(10321920)); + Assert.That(Enumerable.Range(1, 9).Product(Double), Is.EqualTo(185794560)); + Assert.That(Enumerable.Range(1, 10).Product(Double), Is.EqualTo(3715891200)); } - [TestMethod] + [Test] public void Product_ShouldThrowArgumentNullException_GivenNullSource() { IEnumerable source = null!; - Assert.ThrowsException(() => source.Product()); - Assert.ThrowsException(() => source.Product(v => v)); + Assert.Throws(() => source.Product()); + Assert.Throws(() => source.Product(v => v)); } - [TestMethod] + [Test] public void RangeTo_Int64_ShouldYieldCorrectValues() { const long start = 1; @@ -59,9 +59,9 @@ public class Int64Tests long current = 1; foreach (long value in start.RangeTo(end)) { - Assert.AreEqual(current++, value); + Assert.That(value, Is.EqualTo(current++)); } - Assert.AreEqual(current, end); + Assert.That(end, Is.EqualTo(current)); } } diff --git a/X10D.Tests/src/Linq/ReadOnlySpanTests.cs b/X10D.Tests/src/Linq/ReadOnlySpanTests.cs index 4f2cbd9..05787b9 100644 --- a/X10D.Tests/src/Linq/ReadOnlySpanTests.cs +++ b/X10D.Tests/src/Linq/ReadOnlySpanTests.cs @@ -1,82 +1,82 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Linq; namespace X10D.Tests.Linq; -[TestClass] +[TestFixture] public class ReadOnlySpanTests { - [TestMethod] + [Test] public void AllShouldReturnTrueForEmptySpan() { var span = new ReadOnlySpan(); - Assert.IsTrue(span.All(x => x > 0)); + Assert.That(span.All(x => x > 0)); } - [TestMethod] + [Test] public void AllShouldBeCorrect() { var span = new ReadOnlySpan(new[] {2, 4, 6, 8, 10}); - Assert.IsTrue(span.All(x => x % 2 == 0)); - Assert.IsFalse(span.All(x => x % 2 == 1)); + Assert.That(span.All(x => x % 2 == 0)); + Assert.That(span.All(x => x % 2 == 1), Is.False); } - [TestMethod] + [Test] public void AnyShouldReturnFalseForEmptySpan() { var span = new ReadOnlySpan(); - Assert.IsFalse(span.Any(x => x > 0)); + Assert.That(span.Any(x => x > 0), Is.False); } - [TestMethod] + [Test] public void AnyShouldBeCorrect() { var span = new ReadOnlySpan(new[] {2, 4, 6, 8, 10}); - Assert.IsTrue(span.Any(x => x % 2 == 0)); - Assert.IsFalse(span.Any(x => x % 2 == 1)); + Assert.That(span.Any(x => x % 2 == 0)); + Assert.That(span.Any(x => x % 2 == 1), Is.False); } - [TestMethod] + [Test] public void AllNullPredicateShouldThrow() { - Assert.ThrowsException(() => + Assert.Throws(() => { var span = new ReadOnlySpan(); - return span.All(null!); + _ = span.All(null!); }); } - [TestMethod] + [Test] public void AnyNullPredicateShouldThrow() { - Assert.ThrowsException(() => + Assert.Throws(() => { var span = new ReadOnlySpan(); - return span.Any(null!); + _ = span.Any(null!); }); } - [TestMethod] + [Test] public void Count_ShouldReturn0_GivenEmptySpan() { var span = new ReadOnlySpan(); - Assert.AreEqual(0, span.Count(i => i % 2 == 0)); + Assert.That(span.Count(i => i % 2 == 0), Is.Zero); } - [TestMethod] + [Test] public void Count_ShouldReturn5_ForEvenNumbers_GivenNumbers1To10() { var span = new ReadOnlySpan(new[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}); - Assert.AreEqual(5, span.Count(i => i % 2 == 0)); + Assert.That(span.Count(i => i % 2 == 0), Is.EqualTo(5)); } - [TestMethod] + [Test] public void Count_ShouldThrow_GivenNullPredicate() { - Assert.ThrowsException(() => + Assert.Throws(() => { var span = new ReadOnlySpan(); - return span.Count(null!); + _ = span.Count(null!); }); } } diff --git a/X10D.Tests/src/Linq/SByteTests.cs b/X10D.Tests/src/Linq/SByteTests.cs index 826464c..5d5e0b8 100644 --- a/X10D.Tests/src/Linq/SByteTests.cs +++ b/X10D.Tests/src/Linq/SByteTests.cs @@ -1,45 +1,45 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Linq; namespace X10D.Tests.Linq; -[TestClass] +[TestFixture] [CLSCompliant(false)] public class SByteTests { - [TestMethod] + [Test] public void ProductShouldBeCorrect() { sbyte Cast(int i) => (sbyte)i; - Assert.AreEqual(0, Enumerable.Range(0, 10).Select(Cast).Product()); - Assert.AreEqual(1, Enumerable.Range(1, 1).Select(Cast).Product()); - Assert.AreEqual(2, Enumerable.Range(1, 2).Select(Cast).Product()); - Assert.AreEqual(6, Enumerable.Range(1, 3).Select(Cast).Product()); - Assert.AreEqual(24, Enumerable.Range(1, 4).Select(Cast).Product()); - Assert.AreEqual(120, Enumerable.Range(1, 5).Select(Cast).Product()); + Assert.That(Enumerable.Range(0, 10).Select(Cast).Product(), Is.Zero); + Assert.That(Enumerable.Range(1, 1).Select(Cast).Product(), Is.EqualTo(1)); + Assert.That(Enumerable.Range(1, 2).Select(Cast).Product(), Is.EqualTo(2)); + Assert.That(Enumerable.Range(1, 3).Select(Cast).Product(), Is.EqualTo(6)); + Assert.That(Enumerable.Range(1, 4).Select(Cast).Product(), Is.EqualTo(24)); + Assert.That(Enumerable.Range(1, 5).Select(Cast).Product(), Is.EqualTo(120)); // 6! will overflow for sbyte } - [TestMethod] + [Test] public void ProductOfDoublesShouldBeCorrect() { sbyte Double(int i) => (sbyte)(i * 2); - Assert.AreEqual(0, Enumerable.Range(0, 10).Product(Double)); - Assert.AreEqual(2, Enumerable.Range(1, 1).Product(Double)); - Assert.AreEqual(8, Enumerable.Range(1, 2).Product(Double)); - Assert.AreEqual(48, Enumerable.Range(1, 3).Product(Double)); + Assert.That(Enumerable.Range(0, 10).Product(Double), Is.Zero); + Assert.That(Enumerable.Range(1, 1).Product(Double), Is.EqualTo(2)); + Assert.That(Enumerable.Range(1, 2).Product(Double), Is.EqualTo(8)); + Assert.That(Enumerable.Range(1, 3).Product(Double), Is.EqualTo(48)); // Π_(i=1)^(n(i*2)) will overflow at i=4 for sbyte } - [TestMethod] + [Test] public void Product_ShouldThrowArgumentNullException_GivenNullSource() { IEnumerable source = null!; - Assert.ThrowsException(() => source.Product()); - Assert.ThrowsException(() => source.Product(v => v)); + Assert.Throws(() => source.Product()); + Assert.Throws(() => source.Product(v => v)); } } diff --git a/X10D.Tests/src/Linq/SingleTests.cs b/X10D.Tests/src/Linq/SingleTests.cs index 87cdb30..3a1a866 100644 --- a/X10D.Tests/src/Linq/SingleTests.cs +++ b/X10D.Tests/src/Linq/SingleTests.cs @@ -1,52 +1,52 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Linq; namespace X10D.Tests.Linq; -[TestClass] +[TestFixture] public class SingleTests { - [TestMethod] + [Test] public void ProductShouldBeCorrect() { float Cast(int i) => i; - Assert.AreEqual(0f, Enumerable.Range(0, 10).Select(Cast).Product()); - Assert.AreEqual(1f, Enumerable.Range(1, 1).Select(Cast).Product()); - Assert.AreEqual(2f, Enumerable.Range(1, 2).Select(Cast).Product()); - Assert.AreEqual(6f, Enumerable.Range(1, 3).Select(Cast).Product()); - Assert.AreEqual(24f, Enumerable.Range(1, 4).Select(Cast).Product()); - Assert.AreEqual(120f, Enumerable.Range(1, 5).Select(Cast).Product()); - Assert.AreEqual(720f, Enumerable.Range(1, 6).Select(Cast).Product()); - Assert.AreEqual(5040f, Enumerable.Range(1, 7).Select(Cast).Product()); - Assert.AreEqual(40320f, Enumerable.Range(1, 8).Select(Cast).Product()); - Assert.AreEqual(362880f, Enumerable.Range(1, 9).Select(Cast).Product()); - Assert.AreEqual(3628800f, Enumerable.Range(1, 10).Select(Cast).Product()); + Assert.That(Enumerable.Range(0, 10).Select(Cast).Product(), Is.EqualTo(0f)); + Assert.That(Enumerable.Range(1, 1).Select(Cast).Product(), Is.EqualTo(1f)); + Assert.That(Enumerable.Range(1, 2).Select(Cast).Product(), Is.EqualTo(2f)); + Assert.That(Enumerable.Range(1, 3).Select(Cast).Product(), Is.EqualTo(6f)); + Assert.That(Enumerable.Range(1, 4).Select(Cast).Product(), Is.EqualTo(24f)); + Assert.That(Enumerable.Range(1, 5).Select(Cast).Product(), Is.EqualTo(120f)); + Assert.That(Enumerable.Range(1, 6).Select(Cast).Product(), Is.EqualTo(720f)); + Assert.That(Enumerable.Range(1, 7).Select(Cast).Product(), Is.EqualTo(5040f)); + Assert.That(Enumerable.Range(1, 8).Select(Cast).Product(), Is.EqualTo(40320f)); + Assert.That(Enumerable.Range(1, 9).Select(Cast).Product(), Is.EqualTo(362880f)); + Assert.That(Enumerable.Range(1, 10).Select(Cast).Product(), Is.EqualTo(3628800f)); } - [TestMethod] + [Test] public void ProductOfDoublesShouldBeCorrect() { float Double(int i) => i * 2f; - Assert.AreEqual(0f, Enumerable.Range(0, 10).Product(Double)); - Assert.AreEqual(2f, Enumerable.Range(1, 1).Product(Double)); - Assert.AreEqual(8f, Enumerable.Range(1, 2).Product(Double)); - Assert.AreEqual(48f, Enumerable.Range(1, 3).Product(Double)); - Assert.AreEqual(384f, Enumerable.Range(1, 4).Product(Double)); - Assert.AreEqual(3840f, Enumerable.Range(1, 5).Product(Double)); - Assert.AreEqual(46080f, Enumerable.Range(1, 6).Product(Double)); - Assert.AreEqual(645120f, Enumerable.Range(1, 7).Product(Double)); - Assert.AreEqual(10321920f, Enumerable.Range(1, 8).Product(Double)); - Assert.AreEqual(185794560f, Enumerable.Range(1, 9).Product(Double)); - Assert.AreEqual(3715891200f, Enumerable.Range(1, 10).Product(Double)); + Assert.That(Enumerable.Range(0, 10).Product(Double), Is.EqualTo(0f)); + Assert.That(Enumerable.Range(1, 1).Product(Double), Is.EqualTo(2f)); + Assert.That(Enumerable.Range(1, 2).Product(Double), Is.EqualTo(8f)); + Assert.That(Enumerable.Range(1, 3).Product(Double), Is.EqualTo(48f)); + Assert.That(Enumerable.Range(1, 4).Product(Double), Is.EqualTo(384f)); + Assert.That(Enumerable.Range(1, 5).Product(Double), Is.EqualTo(3840f)); + Assert.That(Enumerable.Range(1, 6).Product(Double), Is.EqualTo(46080f)); + Assert.That(Enumerable.Range(1, 7).Product(Double), Is.EqualTo(645120f)); + Assert.That(Enumerable.Range(1, 8).Product(Double), Is.EqualTo(10321920f)); + Assert.That(Enumerable.Range(1, 9).Product(Double), Is.EqualTo(185794560f)); + Assert.That(Enumerable.Range(1, 10).Product(Double), Is.EqualTo(3715891200f)); } - [TestMethod] + [Test] public void Product_ShouldThrowArgumentNullException_GivenNullSource() { IEnumerable source = null!; - Assert.ThrowsException(() => source.Product()); - Assert.ThrowsException(() => source.Product(v => v)); + Assert.Throws(() => source.Product()); + Assert.Throws(() => source.Product(v => v)); } } diff --git a/X10D.Tests/src/Linq/SpanTests.cs b/X10D.Tests/src/Linq/SpanTests.cs index 60882f4..624a399 100644 --- a/X10D.Tests/src/Linq/SpanTests.cs +++ b/X10D.Tests/src/Linq/SpanTests.cs @@ -1,82 +1,82 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Linq; namespace X10D.Tests.Linq; -[TestClass] +[TestFixture] public class SpanTests { - [TestMethod] + [Test] public void AllShouldReturnTrueForEmptySpan() { var span = new Span(); - Assert.IsTrue(span.All(x => x > 0)); + Assert.That(span.All(x => x > 0)); } - [TestMethod] + [Test] public void AllShouldBeCorrect() { var span = new Span(new[] {2, 4, 6, 8, 10}); - Assert.IsTrue(span.All(x => x % 2 == 0)); - Assert.IsFalse(span.All(x => x % 2 == 1)); + Assert.That(span.All(x => x % 2 == 0)); + Assert.That(span.All(x => x % 2 == 1), Is.False); } - [TestMethod] + [Test] public void AnyShouldReturnFalseForEmptySpan() { var span = new Span(); - Assert.IsFalse(span.Any(x => x > 0)); + Assert.That(span.Any(x => x > 0), Is.False); } - [TestMethod] + [Test] public void AnyShouldBeCorrect() { var span = new Span(new[] {2, 4, 6, 8, 10}); - Assert.IsTrue(span.Any(x => x % 2 == 0)); - Assert.IsFalse(span.Any(x => x % 2 == 1)); + Assert.That(span.Any(x => x % 2 == 0)); + Assert.That(span.Any(x => x % 2 == 1), Is.False); } - [TestMethod] + [Test] public void AllNullPredicateShouldThrow() { - Assert.ThrowsException(() => + Assert.Throws(() => { var span = new Span(); - return span.All(null!); + _ = span.All(null!); }); } - [TestMethod] + [Test] public void AnyNullPredicateShouldThrow() { - Assert.ThrowsException(() => + Assert.Throws(() => { var span = new Span(); - return span.Any(null!); + _ = span.Any(null!); }); } - [TestMethod] + [Test] public void Count_ShouldReturn0_GivenEmptySpan() { var span = new Span(); - Assert.AreEqual(0, span.Count(i => i % 2 == 0)); + Assert.That(span.Count(i => i % 2 == 0), Is.Zero); } - [TestMethod] + [Test] public void Count_ShouldReturn5_ForEvenNumbers_GivenNumbers1To10() { var span = new Span(new[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}); - Assert.AreEqual(5, span.Count(i => i % 2 == 0)); + Assert.That(span.Count(i => i % 2 == 0), Is.EqualTo(5)); } - [TestMethod] + [Test] public void Count_ShouldThrow_GivenNullPredicate() { - Assert.ThrowsException(() => + Assert.Throws(() => { var span = new Span(); - return span.Count(null!); + _ = span.Count(null!); }); } } diff --git a/X10D.Tests/src/Linq/UInt16Tests.cs b/X10D.Tests/src/Linq/UInt16Tests.cs index a45eaa6..2742fc0 100644 --- a/X10D.Tests/src/Linq/UInt16Tests.cs +++ b/X10D.Tests/src/Linq/UInt16Tests.cs @@ -1,51 +1,51 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Linq; namespace X10D.Tests.Linq; -[TestClass] +[TestFixture] [CLSCompliant(false)] public class UInt16Tests { - [TestMethod] + [Test] public void ProductShouldBeCorrect() { ushort Cast(int i) => (ushort)i; - Assert.AreEqual(0U, Enumerable.Range(0, 10).Select(Cast).Product()); - Assert.AreEqual(1U, Enumerable.Range(1, 1).Select(Cast).Product()); - Assert.AreEqual(2U, Enumerable.Range(1, 2).Select(Cast).Product()); - Assert.AreEqual(6U, Enumerable.Range(1, 3).Select(Cast).Product()); - Assert.AreEqual(24U, Enumerable.Range(1, 4).Select(Cast).Product()); - Assert.AreEqual(120U, Enumerable.Range(1, 5).Select(Cast).Product()); - Assert.AreEqual(720U, Enumerable.Range(1, 6).Select(Cast).Product()); - Assert.AreEqual(5040U, Enumerable.Range(1, 7).Select(Cast).Product()); - Assert.AreEqual(40320U, Enumerable.Range(1, 8).Select(Cast).Product()); + Assert.That(Enumerable.Range(0, 10).Select(Cast).Product(), Is.EqualTo(0U)); + Assert.That(Enumerable.Range(1, 1).Select(Cast).Product(), Is.EqualTo(1U)); + Assert.That(Enumerable.Range(1, 2).Select(Cast).Product(), Is.EqualTo(2U)); + Assert.That(Enumerable.Range(1, 3).Select(Cast).Product(), Is.EqualTo(6U)); + Assert.That(Enumerable.Range(1, 4).Select(Cast).Product(), Is.EqualTo(24U)); + Assert.That(Enumerable.Range(1, 5).Select(Cast).Product(), Is.EqualTo(120U)); + Assert.That(Enumerable.Range(1, 6).Select(Cast).Product(), Is.EqualTo(720U)); + Assert.That(Enumerable.Range(1, 7).Select(Cast).Product(), Is.EqualTo(5040U)); + Assert.That(Enumerable.Range(1, 8).Select(Cast).Product(), Is.EqualTo(40320U)); // 9! will overflow for ushort } - [TestMethod] + [Test] public void ProductOfDoublesShouldBeCorrect() { ushort Double(int i) => (ushort)(i * 2); - Assert.AreEqual(0U, Enumerable.Range(0, 10).Product(Double)); - Assert.AreEqual(2U, Enumerable.Range(1, 1).Product(Double)); - Assert.AreEqual(8U, Enumerable.Range(1, 2).Product(Double)); - Assert.AreEqual(48U, Enumerable.Range(1, 3).Product(Double)); - Assert.AreEqual(384U, Enumerable.Range(1, 4).Product(Double)); - Assert.AreEqual(3840U, Enumerable.Range(1, 5).Product(Double)); - Assert.AreEqual(46080U, Enumerable.Range(1, 6).Product(Double)); + Assert.That(Enumerable.Range(0, 10).Product(Double), Is.EqualTo(0U)); + Assert.That(Enumerable.Range(1, 1).Product(Double), Is.EqualTo(2U)); + Assert.That(Enumerable.Range(1, 2).Product(Double), Is.EqualTo(8U)); + Assert.That(Enumerable.Range(1, 3).Product(Double), Is.EqualTo(48U)); + Assert.That(Enumerable.Range(1, 4).Product(Double), Is.EqualTo(384U)); + Assert.That(Enumerable.Range(1, 5).Product(Double), Is.EqualTo(3840U)); + Assert.That(Enumerable.Range(1, 6).Product(Double), Is.EqualTo(46080U)); // Π_(i=1)^n (2i) will overflow at i=7 for ushort } - [TestMethod] + [Test] public void Product_ShouldThrowArgumentNullException_GivenNullSource() { IEnumerable source = null!; - Assert.ThrowsException(() => source.Product()); - Assert.ThrowsException(() => source.Product(v => v)); + Assert.Throws(() => source.Product()); + Assert.Throws(() => source.Product(v => v)); } } diff --git a/X10D.Tests/src/Linq/UInt32Tests.cs b/X10D.Tests/src/Linq/UInt32Tests.cs index cfb0ad6..2435f17 100644 --- a/X10D.Tests/src/Linq/UInt32Tests.cs +++ b/X10D.Tests/src/Linq/UInt32Tests.cs @@ -1,53 +1,53 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Linq; namespace X10D.Tests.Linq; -[TestClass] +[TestFixture] [CLSCompliant(false)] public class UInt32Tests { - [TestMethod] + [Test] public void ProductShouldBeCorrect() { ulong Cast(int i) => (ulong)i; - Assert.AreEqual(0U, Enumerable.Range(0, 10).Select(Cast).Product()); - Assert.AreEqual(1U, Enumerable.Range(1, 1).Select(Cast).Product()); - Assert.AreEqual(2U, Enumerable.Range(1, 2).Select(Cast).Product()); - Assert.AreEqual(6U, Enumerable.Range(1, 3).Select(Cast).Product()); - Assert.AreEqual(24U, Enumerable.Range(1, 4).Select(Cast).Product()); - Assert.AreEqual(120U, Enumerable.Range(1, 5).Select(Cast).Product()); - Assert.AreEqual(720U, Enumerable.Range(1, 6).Select(Cast).Product()); - Assert.AreEqual(5040U, Enumerable.Range(1, 7).Select(Cast).Product()); - Assert.AreEqual(40320U, Enumerable.Range(1, 8).Select(Cast).Product()); - Assert.AreEqual(362880U, Enumerable.Range(1, 9).Select(Cast).Product()); - Assert.AreEqual(3628800U, Enumerable.Range(1, 10).Select(Cast).Product()); + Assert.That(Enumerable.Range(0, 10).Select(Cast).Product(), Is.EqualTo(0U)); + Assert.That(Enumerable.Range(1, 1).Select(Cast).Product(), Is.EqualTo(1U)); + Assert.That(Enumerable.Range(1, 2).Select(Cast).Product(), Is.EqualTo(2U)); + Assert.That(Enumerable.Range(1, 3).Select(Cast).Product(), Is.EqualTo(6U)); + Assert.That(Enumerable.Range(1, 4).Select(Cast).Product(), Is.EqualTo(24U)); + Assert.That(Enumerable.Range(1, 5).Select(Cast).Product(), Is.EqualTo(120U)); + Assert.That(Enumerable.Range(1, 6).Select(Cast).Product(), Is.EqualTo(720U)); + Assert.That(Enumerable.Range(1, 7).Select(Cast).Product(), Is.EqualTo(5040U)); + Assert.That(Enumerable.Range(1, 8).Select(Cast).Product(), Is.EqualTo(40320U)); + Assert.That(Enumerable.Range(1, 9).Select(Cast).Product(), Is.EqualTo(362880U)); + Assert.That(Enumerable.Range(1, 10).Select(Cast).Product(), Is.EqualTo(3628800U)); } - [TestMethod] + [Test] public void ProductOfDoublesShouldBeCorrect() { uint Double(int i) => (uint)i * 2; - Assert.AreEqual(0U, Enumerable.Range(0, 10).Product(Double)); - Assert.AreEqual(2U, Enumerable.Range(1, 1).Product(Double)); - Assert.AreEqual(8U, Enumerable.Range(1, 2).Product(Double)); - Assert.AreEqual(48U, Enumerable.Range(1, 3).Product(Double)); - Assert.AreEqual(384U, Enumerable.Range(1, 4).Product(Double)); - Assert.AreEqual(3840U, Enumerable.Range(1, 5).Product(Double)); - Assert.AreEqual(46080U, Enumerable.Range(1, 6).Product(Double)); - Assert.AreEqual(645120U, Enumerable.Range(1, 7).Product(Double)); - Assert.AreEqual(10321920U, Enumerable.Range(1, 8).Product(Double)); - Assert.AreEqual(185794560U, Enumerable.Range(1, 9).Product(Double)); - Assert.AreEqual(3715891200U, Enumerable.Range(1, 10).Product(Double)); + Assert.That(Enumerable.Range(0, 10).Product(Double), Is.EqualTo(0U)); + Assert.That(Enumerable.Range(1, 1).Product(Double), Is.EqualTo(2U)); + Assert.That(Enumerable.Range(1, 2).Product(Double), Is.EqualTo(8U)); + Assert.That(Enumerable.Range(1, 3).Product(Double), Is.EqualTo(48U)); + Assert.That(Enumerable.Range(1, 4).Product(Double), Is.EqualTo(384U)); + Assert.That(Enumerable.Range(1, 5).Product(Double), Is.EqualTo(3840U)); + Assert.That(Enumerable.Range(1, 6).Product(Double), Is.EqualTo(46080U)); + Assert.That(Enumerable.Range(1, 7).Product(Double), Is.EqualTo(645120U)); + Assert.That(Enumerable.Range(1, 8).Product(Double), Is.EqualTo(10321920U)); + Assert.That(Enumerable.Range(1, 9).Product(Double), Is.EqualTo(185794560U)); + Assert.That(Enumerable.Range(1, 10).Product(Double), Is.EqualTo(3715891200U)); } - [TestMethod] + [Test] public void Product_ShouldThrowArgumentNullException_GivenNullSource() { IEnumerable source = null!; - Assert.ThrowsException(() => source.Product()); - Assert.ThrowsException(() => source.Product(v => v)); + Assert.Throws(() => source.Product()); + Assert.Throws(() => source.Product(v => v)); } } diff --git a/X10D.Tests/src/Linq/UInt64Tests.cs b/X10D.Tests/src/Linq/UInt64Tests.cs index 3b1c585..bbaa2fc 100644 --- a/X10D.Tests/src/Linq/UInt64Tests.cs +++ b/X10D.Tests/src/Linq/UInt64Tests.cs @@ -1,53 +1,53 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Linq; namespace X10D.Tests.Linq; -[TestClass] +[TestFixture] [CLSCompliant(false)] public class UInt64Tests { - [TestMethod] + [Test] public void ProductShouldBeCorrect() { ulong Cast(int i) => (ulong)i; - Assert.AreEqual(0UL, Enumerable.Range(0, 10).Select(Cast).Product()); - Assert.AreEqual(1UL, Enumerable.Range(1, 1).Select(Cast).Product()); - Assert.AreEqual(2UL, Enumerable.Range(1, 2).Select(Cast).Product()); - Assert.AreEqual(6UL, Enumerable.Range(1, 3).Select(Cast).Product()); - Assert.AreEqual(24UL, Enumerable.Range(1, 4).Select(Cast).Product()); - Assert.AreEqual(120UL, Enumerable.Range(1, 5).Select(Cast).Product()); - Assert.AreEqual(720UL, Enumerable.Range(1, 6).Select(Cast).Product()); - Assert.AreEqual(5040UL, Enumerable.Range(1, 7).Select(Cast).Product()); - Assert.AreEqual(40320UL, Enumerable.Range(1, 8).Select(Cast).Product()); - Assert.AreEqual(362880UL, Enumerable.Range(1, 9).Select(Cast).Product()); - Assert.AreEqual(3628800UL, Enumerable.Range(1, 10).Select(Cast).Product()); + Assert.That(Enumerable.Range(0, 10).Select(Cast).Product(), Is.EqualTo(0UL)); + Assert.That(Enumerable.Range(1, 1).Select(Cast).Product(), Is.EqualTo(1UL)); + Assert.That(Enumerable.Range(1, 2).Select(Cast).Product(), Is.EqualTo(2UL)); + Assert.That(Enumerable.Range(1, 3).Select(Cast).Product(), Is.EqualTo(6UL)); + Assert.That(Enumerable.Range(1, 4).Select(Cast).Product(), Is.EqualTo(24UL)); + Assert.That(Enumerable.Range(1, 5).Select(Cast).Product(), Is.EqualTo(120UL)); + Assert.That(Enumerable.Range(1, 6).Select(Cast).Product(), Is.EqualTo(720UL)); + Assert.That(Enumerable.Range(1, 7).Select(Cast).Product(), Is.EqualTo(5040UL)); + Assert.That(Enumerable.Range(1, 8).Select(Cast).Product(), Is.EqualTo(40320UL)); + Assert.That(Enumerable.Range(1, 9).Select(Cast).Product(), Is.EqualTo(362880UL)); + Assert.That(Enumerable.Range(1, 10).Select(Cast).Product(), Is.EqualTo(3628800UL)); } - [TestMethod] + [Test] public void ProductOfDoublesShouldBeCorrect() { ulong Double(int i) => (ulong)i * 2; - Assert.AreEqual(0UL, Enumerable.Range(0, 10).Product(Double)); - Assert.AreEqual(2UL, Enumerable.Range(1, 1).Product(Double)); - Assert.AreEqual(8UL, Enumerable.Range(1, 2).Product(Double)); - Assert.AreEqual(48UL, Enumerable.Range(1, 3).Product(Double)); - Assert.AreEqual(384UL, Enumerable.Range(1, 4).Product(Double)); - Assert.AreEqual(3840UL, Enumerable.Range(1, 5).Product(Double)); - Assert.AreEqual(46080UL, Enumerable.Range(1, 6).Product(Double)); - Assert.AreEqual(645120UL, Enumerable.Range(1, 7).Product(Double)); - Assert.AreEqual(10321920UL, Enumerable.Range(1, 8).Product(Double)); - Assert.AreEqual(185794560UL, Enumerable.Range(1, 9).Product(Double)); - Assert.AreEqual(3715891200UL, Enumerable.Range(1, 10).Product(Double)); + Assert.That(Enumerable.Range(0, 10).Product(Double), Is.EqualTo(0UL)); + Assert.That(Enumerable.Range(1, 1).Product(Double), Is.EqualTo(2UL)); + Assert.That(Enumerable.Range(1, 2).Product(Double), Is.EqualTo(8UL)); + Assert.That(Enumerable.Range(1, 3).Product(Double), Is.EqualTo(48UL)); + Assert.That(Enumerable.Range(1, 4).Product(Double), Is.EqualTo(384UL)); + Assert.That(Enumerable.Range(1, 5).Product(Double), Is.EqualTo(3840UL)); + Assert.That(Enumerable.Range(1, 6).Product(Double), Is.EqualTo(46080UL)); + Assert.That(Enumerable.Range(1, 7).Product(Double), Is.EqualTo(645120UL)); + Assert.That(Enumerable.Range(1, 8).Product(Double), Is.EqualTo(10321920UL)); + Assert.That(Enumerable.Range(1, 9).Product(Double), Is.EqualTo(185794560UL)); + Assert.That(Enumerable.Range(1, 10).Product(Double), Is.EqualTo(3715891200UL)); } - [TestMethod] + [Test] public void Product_ShouldThrowArgumentNullException_GivenNullSource() { IEnumerable source = null!; - Assert.ThrowsException(() => source.Product()); - Assert.ThrowsException(() => source.Product(v => v)); + Assert.Throws(() => source.Product()); + Assert.Throws(() => source.Product(v => v)); } } diff --git a/X10D.Tests/src/Math/BigIntegerTests.Wrap.cs b/X10D.Tests/src/Math/BigIntegerTests.Wrap.cs index 63a661a..d3fff35 100644 --- a/X10D.Tests/src/Math/BigIntegerTests.Wrap.cs +++ b/X10D.Tests/src/Math/BigIntegerTests.Wrap.cs @@ -1,15 +1,15 @@ using System.Numerics; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Math; namespace X10D.Tests.Math; public partial class BigIntegerTests { - [TestClass] + [TestFixture] public class WrapTests { - [TestMethod] + [Test] public void Wrap_ShouldReturnLow_WhenValueIsEqualToLow() { BigInteger value = 10; @@ -18,10 +18,10 @@ public partial class BigIntegerTests BigInteger result = value.Wrap(low, high); - Assert.AreEqual(low, result); + Assert.That(result, Is.EqualTo(low)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnHigh_WhenValueIsEqualToHigh() { BigInteger value = 20; @@ -30,10 +30,10 @@ public partial class BigIntegerTests BigInteger result = value.Wrap(low, high); - Assert.AreEqual(low, result); + Assert.That(result, Is.EqualTo(low)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsGreaterThanHigh() { BigInteger value = 30; @@ -42,10 +42,10 @@ public partial class BigIntegerTests BigInteger result = value.Wrap(low, high); - Assert.AreEqual(low, result); + Assert.That(result, Is.EqualTo(low)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsLessThanLow() { BigInteger value = 5; @@ -54,10 +54,10 @@ public partial class BigIntegerTests BigInteger result = value.Wrap(low, high); - Assert.AreEqual(15L, result); + Assert.That(result, Is.EqualTo((BigInteger)15)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsInBetweenLowAndHigh() { BigInteger value = 15; @@ -66,10 +66,10 @@ public partial class BigIntegerTests BigInteger result = value.Wrap(low, high); - Assert.AreEqual(value, result); + Assert.That(result, Is.EqualTo(value)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnZero_WhenValueIsEqualToLength() { BigInteger value = 10; @@ -77,10 +77,10 @@ public partial class BigIntegerTests BigInteger result = value.Wrap(length); - Assert.AreEqual(0L, result); + Assert.That(result, Is.EqualTo((BigInteger)0)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnValue_WhenValueIsLessThanLength() { BigInteger value = 5; @@ -88,10 +88,10 @@ public partial class BigIntegerTests BigInteger result = value.Wrap(length); - Assert.AreEqual(value, result); + Assert.That(result, Is.EqualTo(value)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsGreaterThanLength() { BigInteger value = 15; @@ -99,7 +99,7 @@ public partial class BigIntegerTests BigInteger result = value.Wrap(length); - Assert.AreEqual(5L, result); + Assert.That(result, Is.EqualTo((BigInteger)5)); } } } diff --git a/X10D.Tests/src/Math/BigIntegerTests.cs b/X10D.Tests/src/Math/BigIntegerTests.cs index 304086c..bbe3b09 100644 --- a/X10D.Tests/src/Math/BigIntegerTests.cs +++ b/X10D.Tests/src/Math/BigIntegerTests.cs @@ -1,69 +1,74 @@ using System.Numerics; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Math; namespace X10D.Tests.Math; -[TestClass] +[TestFixture] public partial class BigIntegerTests { - [TestMethod] + [Test] public void DigitalRootShouldBeCorrect() { BigInteger value = 238; - Assert.AreEqual(4, value.DigitalRoot()); - Assert.AreEqual(4, (-value).DigitalRoot()); + Assert.That(value.DigitalRoot(), Is.EqualTo(4)); + Assert.That((-value).DigitalRoot(), Is.EqualTo(4)); } - [TestMethod] + [Test] public void FactorialShouldBeCorrect() { - Assert.AreEqual(1, ((BigInteger)0).Factorial()); - Assert.AreEqual(1, ((BigInteger)1).Factorial()); - Assert.AreEqual(2, ((BigInteger)2).Factorial()); - Assert.AreEqual(6, ((BigInteger)3).Factorial()); - Assert.AreEqual(24, ((BigInteger)4).Factorial()); - Assert.AreEqual(120, ((BigInteger)5).Factorial()); - Assert.AreEqual(720, ((BigInteger)6).Factorial()); - Assert.AreEqual(5040, ((BigInteger)7).Factorial()); - Assert.AreEqual(40320, ((BigInteger)8).Factorial()); - Assert.AreEqual(362880, ((BigInteger)9).Factorial()); - Assert.AreEqual(3628800, ((BigInteger)10).Factorial()); + Assert.Multiple(() => + { + Assert.That(((BigInteger)0).Factorial(), Is.EqualTo((BigInteger)1)); + Assert.That(((BigInteger)1).Factorial(), Is.EqualTo((BigInteger)1)); + Assert.That(((BigInteger)2).Factorial(), Is.EqualTo((BigInteger)2)); + Assert.That(((BigInteger)3).Factorial(), Is.EqualTo((BigInteger)6)); + Assert.That(((BigInteger)4).Factorial(), Is.EqualTo((BigInteger)24)); + Assert.That(((BigInteger)5).Factorial(), Is.EqualTo((BigInteger)120)); + Assert.That(((BigInteger)6).Factorial(), Is.EqualTo((BigInteger)720)); + Assert.That(((BigInteger)7).Factorial(), Is.EqualTo((BigInteger)5040)); + Assert.That(((BigInteger)8).Factorial(), Is.EqualTo((BigInteger)40320)); + Assert.That(((BigInteger)9).Factorial(), Is.EqualTo((BigInteger)362880)); + Assert.That(((BigInteger)10).Factorial(), Is.EqualTo((BigInteger)3628800)); + }); } - [TestMethod] + [Test] public void GreatestCommonFactor_ShouldBe1_ForPrimeNumbers() { - BigInteger first = 5L; - BigInteger second = 7L; + BigInteger first = 5; + BigInteger second = 7; BigInteger multiple = first.GreatestCommonFactor(second); - Assert.AreEqual(1L, multiple); + Assert.That(multiple, Is.EqualTo((BigInteger)1)); } - [TestMethod] + [Test] public void GreatestCommonFactor_ShouldBe6_Given12And18() { - BigInteger first = 12L; - BigInteger second = 18L; + BigInteger first = 12; + BigInteger second = 18; BigInteger multiple = first.GreatestCommonFactor(second); - Assert.AreEqual(6L, multiple); + Assert.That(multiple, Is.EqualTo((BigInteger)6)); } - [TestMethod] + [Test] public void IsOddShouldBeCorrect() { BigInteger one = 1; BigInteger two = 2; - - Assert.IsTrue(one.IsOdd()); - Assert.IsFalse(two.IsOdd()); + Assert.Multiple(() => + { + Assert.That(one.IsOdd()); + Assert.That(two.IsOdd(), Is.False); + }); } - [TestMethod] + [Test] public void LowestCommonMultiple_ShouldReturnCorrectValue_WhenCalledWithValidInput() { BigInteger value1 = 2; @@ -72,10 +77,10 @@ public partial class BigIntegerTests BigInteger result = value1.LowestCommonMultiple(value2); - Assert.AreEqual(expected, result); + Assert.That(result, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void LowestCommonMultiple_ShouldReturnZero_WhenCalledWithZero() { BigInteger value1 = 0; @@ -84,10 +89,10 @@ public partial class BigIntegerTests BigInteger result = value1.LowestCommonMultiple(value2); - Assert.AreEqual(expected, result); + Assert.That(result, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void LowestCommonMultiple_ShouldReturnGreaterValue_WhenCalledWithOne() { BigInteger value1 = 1; @@ -97,11 +102,11 @@ public partial class BigIntegerTests BigInteger result1 = value1.LowestCommonMultiple(value2); BigInteger result2 = value2.LowestCommonMultiple(value1); - Assert.AreEqual(expected, result1); - Assert.AreEqual(expected, result2); + Assert.That(result1, Is.EqualTo(expected)); + Assert.That(result2, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void LowestCommonMultiple_ShouldReturnOtherValue_WhenCalledWithSameValue() { BigInteger value1 = 5; @@ -110,10 +115,10 @@ public partial class BigIntegerTests BigInteger result = value1.LowestCommonMultiple(value2); - Assert.AreEqual(expected, result); + Assert.That(result, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void LowestCommonMultiple_ShouldReturnCorrectValue_WhenCalledWithNegativeValues() { BigInteger value1 = -2; @@ -122,38 +127,44 @@ public partial class BigIntegerTests BigInteger result = value1.LowestCommonMultiple(value2); - Assert.AreEqual(expected, result); + Assert.That(result, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void MultiplicativePersistence_ShouldReturn1_ForAnyDigitBeing0() { - Assert.AreEqual(1, ((BigInteger)10).MultiplicativePersistence()); - Assert.AreEqual(1, ((BigInteger)201).MultiplicativePersistence()); - Assert.AreEqual(1, ((BigInteger)200).MultiplicativePersistence()); - Assert.AreEqual(1, ((BigInteger)20007).MultiplicativePersistence()); + Assert.Multiple(() => + { + Assert.That(((BigInteger)10).MultiplicativePersistence(), Is.EqualTo(1)); + Assert.That(((BigInteger)201).MultiplicativePersistence(), Is.EqualTo(1)); + Assert.That(((BigInteger)200).MultiplicativePersistence(), Is.EqualTo(1)); + Assert.That(((BigInteger)20007).MultiplicativePersistence(), Is.EqualTo(1)); + }); } - [TestMethod] + [Test] public void MultiplicativePersistence_ShouldBeCorrect_ForRecordHolders() { - Assert.AreEqual(0, ((BigInteger)0).MultiplicativePersistence()); - Assert.AreEqual(1, ((BigInteger)10).MultiplicativePersistence()); - Assert.AreEqual(2, ((BigInteger)25).MultiplicativePersistence()); - Assert.AreEqual(3, ((BigInteger)39).MultiplicativePersistence()); - Assert.AreEqual(4, ((BigInteger)77).MultiplicativePersistence()); - Assert.AreEqual(5, ((BigInteger)679).MultiplicativePersistence()); - Assert.AreEqual(6, ((BigInteger)6788).MultiplicativePersistence()); - Assert.AreEqual(7, ((BigInteger)68889).MultiplicativePersistence()); - Assert.AreEqual(8, ((BigInteger)2677889).MultiplicativePersistence()); - Assert.AreEqual(9, ((BigInteger)26888999).MultiplicativePersistence()); - Assert.AreEqual(10, ((BigInteger)3778888999).MultiplicativePersistence()); - Assert.AreEqual(11, ((BigInteger)277777788888899).MultiplicativePersistence()); + Assert.Multiple(() => + { + Assert.That(((BigInteger)0).MultiplicativePersistence(), Is.Zero); + Assert.That(((BigInteger)10).MultiplicativePersistence(), Is.EqualTo(1)); + Assert.That(((BigInteger)25).MultiplicativePersistence(), Is.EqualTo(2)); + Assert.That(((BigInteger)39).MultiplicativePersistence(), Is.EqualTo(3)); + Assert.That(((BigInteger)77).MultiplicativePersistence(), Is.EqualTo(4)); + Assert.That(((BigInteger)679).MultiplicativePersistence(), Is.EqualTo(5)); + Assert.That(((BigInteger)6788).MultiplicativePersistence(), Is.EqualTo(6)); + Assert.That(((BigInteger)68889).MultiplicativePersistence(), Is.EqualTo(7)); + Assert.That(((BigInteger)2677889).MultiplicativePersistence(), Is.EqualTo(8)); + Assert.That(((BigInteger)26888999).MultiplicativePersistence(), Is.EqualTo(9)); + Assert.That(((BigInteger)3778888999).MultiplicativePersistence(), Is.EqualTo(10)); + Assert.That(((BigInteger)277777788888899).MultiplicativePersistence(), Is.EqualTo(11)); + }); } - [TestMethod] + [Test] public void NegativeFactorialShouldThrow() { - Assert.ThrowsException(() => ((BigInteger)(-1)).Factorial()); + Assert.Throws(() => _ = ((BigInteger)(-1)).Factorial()); } } diff --git a/X10D.Tests/src/Math/ByteTests.Wrap.cs b/X10D.Tests/src/Math/ByteTests.Wrap.cs index 1713242..d7303e8 100644 --- a/X10D.Tests/src/Math/ByteTests.Wrap.cs +++ b/X10D.Tests/src/Math/ByteTests.Wrap.cs @@ -1,14 +1,14 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Math; namespace X10D.Tests.Math; public partial class ByteTests { - [TestClass] + [TestFixture] public class WrapTests { - [TestMethod] + [Test] public void Wrap_ShouldReturnLow_WhenValueIsEqualToLow() { const byte value = 10; @@ -17,10 +17,10 @@ public partial class ByteTests byte result = value.Wrap(low, high); - Assert.AreEqual(low, result); + Assert.That(result, Is.EqualTo(low)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnHigh_WhenValueIsEqualToHigh() { const byte value = 20; @@ -29,10 +29,10 @@ public partial class ByteTests byte result = value.Wrap(low, high); - Assert.AreEqual(low, result); + Assert.That(result, Is.EqualTo(low)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsGreaterThanHigh() { const byte value = 30; @@ -41,10 +41,10 @@ public partial class ByteTests byte result = value.Wrap(low, high); - Assert.AreEqual(low, result); + Assert.That(result, Is.EqualTo(low)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsLessThanLow() { const byte value = 5; @@ -53,10 +53,10 @@ public partial class ByteTests byte result = value.Wrap(low, high); - Assert.AreEqual(11, result); + Assert.That(result, Is.EqualTo(11)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsInBetweenLowAndHigh() { const byte value = 15; @@ -65,10 +65,10 @@ public partial class ByteTests byte result = value.Wrap(low, high); - Assert.AreEqual(value, result); + Assert.That(result, Is.EqualTo(value)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnZero_WhenValueIsEqualToLength() { const byte value = 10; @@ -76,10 +76,10 @@ public partial class ByteTests byte result = value.Wrap(length); - Assert.AreEqual(0, result); + Assert.That(result, Is.Zero); } - [TestMethod] + [Test] public void Wrap_ShouldReturnValue_WhenValueIsLessThanLength() { const byte value = 5; @@ -87,10 +87,10 @@ public partial class ByteTests byte result = value.Wrap(length); - Assert.AreEqual(value, result); + Assert.That(result, Is.EqualTo(value)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsGreaterThanLength() { const byte value = 15; @@ -98,7 +98,7 @@ public partial class ByteTests byte result = value.Wrap(length); - Assert.AreEqual(5, result); + Assert.That(result, Is.EqualTo(5)); } } } diff --git a/X10D.Tests/src/Math/ByteTests.cs b/X10D.Tests/src/Math/ByteTests.cs index 166754f..e139eb1 100644 --- a/X10D.Tests/src/Math/ByteTests.cs +++ b/X10D.Tests/src/Math/ByteTests.cs @@ -1,36 +1,36 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Math; namespace X10D.Tests.Math; -[TestClass] +[TestFixture] public partial class ByteTests { - [TestMethod] + [Test] public void DigitalRootShouldBeCorrect() { const byte value = 238; - Assert.AreEqual(4, value.DigitalRoot()); - Assert.AreEqual(4, (-value).DigitalRoot()); + Assert.That(value.DigitalRoot(), Is.EqualTo(4)); + Assert.That((-value).DigitalRoot(), Is.EqualTo(4)); } - [TestMethod] + [Test] public void FactorialShouldBeCorrect() { - Assert.AreEqual(1L, ((byte)0).Factorial()); - Assert.AreEqual(1L, ((byte)1).Factorial()); - Assert.AreEqual(2L, ((byte)2).Factorial()); - Assert.AreEqual(6L, ((byte)3).Factorial()); - Assert.AreEqual(24L, ((byte)4).Factorial()); - Assert.AreEqual(120L, ((byte)5).Factorial()); - Assert.AreEqual(720L, ((byte)6).Factorial()); - Assert.AreEqual(5040L, ((byte)7).Factorial()); - Assert.AreEqual(40320L, ((byte)8).Factorial()); - Assert.AreEqual(362880L, ((byte)9).Factorial()); - Assert.AreEqual(3628800L, ((byte)10).Factorial()); + Assert.That(((byte)0).Factorial(), Is.EqualTo(1L)); + Assert.That(((byte)1).Factorial(), Is.EqualTo(1L)); + Assert.That(((byte)2).Factorial(), Is.EqualTo(2L)); + Assert.That(((byte)3).Factorial(), Is.EqualTo(6L)); + Assert.That(((byte)4).Factorial(), Is.EqualTo(24L)); + Assert.That(((byte)5).Factorial(), Is.EqualTo(120L)); + Assert.That(((byte)6).Factorial(), Is.EqualTo(720L)); + Assert.That(((byte)7).Factorial(), Is.EqualTo(5040L)); + Assert.That(((byte)8).Factorial(), Is.EqualTo(40320L)); + Assert.That(((byte)9).Factorial(), Is.EqualTo(362880L)); + Assert.That(((byte)10).Factorial(), Is.EqualTo(3628800L)); } - [TestMethod] + [Test] public void GreatestCommonFactor_ShouldBe1_ForPrimeNumbers() { const byte first = 5; @@ -38,10 +38,10 @@ public partial class ByteTests byte multiple = first.GreatestCommonFactor(second); - Assert.AreEqual(1, multiple); + Assert.That(multiple, Is.EqualTo(1)); } - [TestMethod] + [Test] public void GreatestCommonFactor_ShouldBe6_Given12And18() { const byte first = 12; @@ -49,30 +49,30 @@ public partial class ByteTests byte multiple = first.GreatestCommonFactor(second); - Assert.AreEqual(6, multiple); + Assert.That(multiple, Is.EqualTo(6)); } - [TestMethod] + [Test] public void IsEvenShouldBeCorrect() { const byte one = 1; const byte two = 2; - Assert.IsFalse(one.IsEven()); - Assert.IsTrue(two.IsEven()); + Assert.That(one.IsEven(), Is.False); + Assert.That(two.IsEven()); } - [TestMethod] + [Test] public void IsOddShouldBeCorrect() { const byte one = 1; const byte two = 2; - Assert.IsTrue(one.IsOdd()); - Assert.IsFalse(two.IsOdd()); + Assert.That(one.IsOdd()); + Assert.That(two.IsOdd(), Is.False); } - [TestMethod] + [Test] public void LowestCommonMultiple_ShouldReturnCorrectValue_WhenCalledWithValidInput() { const byte value1 = 2; @@ -81,10 +81,10 @@ public partial class ByteTests byte result = value1.LowestCommonMultiple(value2); - Assert.AreEqual(expected, result); + Assert.That(result, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void LowestCommonMultiple_ShouldReturnZero_WhenCalledWithZero() { const byte value1 = 0; @@ -93,10 +93,10 @@ public partial class ByteTests byte result = value1.LowestCommonMultiple(value2); - Assert.AreEqual(expected, result); + Assert.That(result, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void LowestCommonMultiple_ShouldReturnGreaterValue_WhenCalledWithOne() { const byte value1 = 1; @@ -106,11 +106,11 @@ public partial class ByteTests byte result1 = value1.LowestCommonMultiple(value2); byte result2 = value2.LowestCommonMultiple(value1); - Assert.AreEqual(expected, result1); - Assert.AreEqual(expected, result2); + Assert.That(result1, Is.EqualTo(expected)); + Assert.That(result2, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void LowestCommonMultiple_ShouldReturnOtherValue_WhenCalledWithSameValue() { const byte value1 = 5; @@ -119,25 +119,25 @@ public partial class ByteTests byte result = value1.LowestCommonMultiple(value2); - Assert.AreEqual(expected, result); + Assert.That(result, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void MultiplicativePersistence_ShouldReturn1_ForAnyDigitBeing0() { - Assert.AreEqual(1, ((byte)10).MultiplicativePersistence()); - Assert.AreEqual(1, ((byte)201).MultiplicativePersistence()); - Assert.AreEqual(1, ((byte)200).MultiplicativePersistence()); - Assert.AreEqual(1, ((byte)207).MultiplicativePersistence()); + Assert.That(((byte)10).MultiplicativePersistence(), Is.EqualTo(1)); + Assert.That(((byte)201).MultiplicativePersistence(), Is.EqualTo(1)); + Assert.That(((byte)200).MultiplicativePersistence(), Is.EqualTo(1)); + Assert.That(((byte)207).MultiplicativePersistence(), Is.EqualTo(1)); } - [TestMethod] + [Test] public void MultiplicativePersistence_ShouldBeCorrect_ForRecordHolders() { - Assert.AreEqual(0, ((byte)0).MultiplicativePersistence()); - Assert.AreEqual(1, ((byte)10).MultiplicativePersistence()); - Assert.AreEqual(2, ((byte)25).MultiplicativePersistence()); - Assert.AreEqual(3, ((byte)39).MultiplicativePersistence()); - Assert.AreEqual(4, ((byte)77).MultiplicativePersistence()); + Assert.That(((byte)0).MultiplicativePersistence(), Is.Zero); + Assert.That(((byte)10).MultiplicativePersistence(), Is.EqualTo(1)); + Assert.That(((byte)25).MultiplicativePersistence(), Is.EqualTo(2)); + Assert.That(((byte)39).MultiplicativePersistence(), Is.EqualTo(3)); + Assert.That(((byte)77).MultiplicativePersistence(), Is.EqualTo(4)); } } diff --git a/X10D.Tests/src/Math/ComparableTests.cs b/X10D.Tests/src/Math/ComparableTests.cs index f0417f0..80ee06a 100644 --- a/X10D.Tests/src/Math/ComparableTests.cs +++ b/X10D.Tests/src/Math/ComparableTests.cs @@ -1,9 +1,9 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Math; namespace X10D.Tests.Math; -[TestClass] +[TestFixture] public class ComparableTests { private class ComparableTestClass : IComparable @@ -18,191 +18,191 @@ public class ComparableTests private readonly int _upper = 10; private readonly int _value = 5; - [TestMethod] + [Test] public void Between_5_1_10_ShouldBeTrue() { - Assert.IsTrue(_value.Between(_lower, _upper)); + Assert.That(_value.Between(_lower, _upper)); } - [TestMethod] + [Test] public void Between_1_1_10_ShouldBeFalse() { // default option is exclusive - Assert.IsFalse(_lower.Between(_lower, _upper)); + Assert.That(_lower.Between(_lower, _upper), Is.False); } - [TestMethod] + [Test] public void Between_1_1_10_Inclusive_ShouldBeTrue() { - Assert.IsTrue(_lower.Between(_lower, _upper, InclusiveOptions.Inclusive)); - Assert.IsTrue(_lower.Between(_lower, _upper, InclusiveOptions.LowerInclusive)); - Assert.IsFalse(_lower.Between(_lower, _upper, InclusiveOptions.UpperInclusive)); + Assert.That(_lower.Between(_lower, _upper, InclusiveOptions.Inclusive)); + Assert.That(_lower.Between(_lower, _upper, InclusiveOptions.LowerInclusive)); + Assert.That(_lower.Between(_lower, _upper, InclusiveOptions.UpperInclusive), Is.False); } - [TestMethod] + [Test] public void Between_10_1_10_ShouldBeFalse() { // default option is exclusive - Assert.IsFalse(_upper.Between(_lower, _upper)); + Assert.That(_upper.Between(_lower, _upper), Is.False); } - [TestMethod] + [Test] public void Between_10_1_10_Inclusive_ShouldBeTrue() { - Assert.IsTrue(_upper.Between(_lower, _upper, InclusiveOptions.Inclusive)); - Assert.IsTrue(_upper.Between(_lower, _upper, InclusiveOptions.UpperInclusive)); - Assert.IsFalse(_upper.Between(_lower, _upper, InclusiveOptions.LowerInclusive)); + Assert.That(_upper.Between(_lower, _upper, InclusiveOptions.Inclusive)); + Assert.That(_upper.Between(_lower, _upper, InclusiveOptions.UpperInclusive)); + Assert.That(_upper.Between(_lower, _upper, InclusiveOptions.LowerInclusive), Is.False); } - [TestMethod] + [Test] public void Between_1_10_5_ShouldThrow() { - Assert.ThrowsException(() => _lower.Between(_upper, _value)); + Assert.Throws(() => _lower.Between(_upper, _value)); } - [TestMethod] + [Test] public void Between_Null_ShouldThrow() { ComparableTestClass? nullPointer = null; - Assert.ThrowsException(() => ((ComparableTestClass?)null)!.Between(nullPointer!, nullPointer!)); + Assert.Throws(() => ((ComparableTestClass?)null)!.Between(nullPointer!, nullPointer!)); } - [TestMethod] + [Test] public void Clamp_3_1_5_ShouldBe3() { - Assert.AreEqual(3, 3.Clamp(1, 5)); + Assert.That(3.Clamp(1, 5), Is.EqualTo(3)); } - [TestMethod] + [Test] public void Clamp_10_1_5_ShouldBe5() { - Assert.AreEqual(5, 10.Clamp(1, 5)); + Assert.That(10.Clamp(1, 5), Is.EqualTo(5)); } - [TestMethod] + [Test] public void Clamp_n_6_5_ShouldThrow() { - Assert.ThrowsException(() => 0.Clamp(6, 5)); + Assert.Throws(() => 0.Clamp(6, 5)); } - [TestMethod] + [Test] public void Clamp_ShouldThrowArgumentNullException_GivenNullValue() { string comparable = null!; - Assert.ThrowsException(() => comparable.Clamp(string.Empty, string.Empty)); + Assert.Throws(() => comparable.Clamp(string.Empty, string.Empty)); } - [TestMethod] + [Test] public void GreaterThan_5_6_ShouldBeFalse() { - Assert.IsFalse(5.GreaterThan(6)); + Assert.That(5.GreaterThan(6), Is.False); } - [TestMethod] + [Test] public void GreaterThan_6_5_ShouldBeTrue() { - Assert.IsTrue(6.GreaterThan(5)); + Assert.That(6.GreaterThan(5)); } - [TestMethod] + [Test] public void GreaterThan_5_5_ShouldBeFalse() { - Assert.IsFalse(5.LessThan(5)); + Assert.That(5.LessThan(5), Is.False); } - [TestMethod] + [Test] public void GreaterThan_Null_ShouldThrow() { ComparableTestClass? nullPointer = null; - Assert.ThrowsException(() => nullPointer!.GreaterThan(nullPointer!)); + Assert.Throws(() => nullPointer!.GreaterThan(nullPointer!)); } - [TestMethod] + [Test] public void GreaterThanOrEqualTo_5_5_ShouldBeTrue() { - Assert.IsTrue(5.GreaterThanOrEqualTo(5)); + Assert.That(5.GreaterThanOrEqualTo(5)); } - [TestMethod] + [Test] public void GreaterThanOrEqualTo_6_5_ShouldBeTrue() { - Assert.IsTrue(6.GreaterThanOrEqualTo(5)); + Assert.That(6.GreaterThanOrEqualTo(5)); } - [TestMethod] + [Test] public void GreaterThanOrEqualTo_5_6_ShouldBeFalse() { - Assert.IsFalse(5.GreaterThanOrEqualTo(6)); + Assert.That(5.GreaterThanOrEqualTo(6), Is.False); } - [TestMethod] + [Test] public void GreaterThanOrEqualTo_Null_ShouldThrow() { ComparableTestClass? nullPointer = null; - Assert.ThrowsException(() => nullPointer!.GreaterThanOrEqualTo(nullPointer!)); + Assert.Throws(() => nullPointer!.GreaterThanOrEqualTo(nullPointer!)); } - [TestMethod] + [Test] public void LessThan_Null_ShouldThrow() { ComparableTestClass? nullPointer = null; - Assert.ThrowsException(() => nullPointer!.LessThan(nullPointer!)); + Assert.Throws(() => nullPointer!.LessThan(nullPointer!)); } - [TestMethod] + [Test] public void LessThan_6_5_ShouldBeFalse() { - Assert.IsFalse(6.LessThan(5)); + Assert.That(6.LessThan(5), Is.False); } - [TestMethod] + [Test] public void LessThan_5_6_ShouldBeTrue() { - Assert.IsTrue(5.LessThan(6)); + Assert.That(5.LessThan(6)); } - [TestMethod] + [Test] public void LessThan_5_5_ShouldBeFalse() { - Assert.IsFalse(5.LessThan(5)); + Assert.That(5.LessThan(5), Is.False); } - [TestMethod] + [Test] public void LessThanOrEqualTo_5_5_ShouldBeTrue() { - Assert.IsTrue(5.LessThanOrEqualTo(5)); + Assert.That(5.LessThanOrEqualTo(5)); } - [TestMethod] + [Test] public void LessThanOrEqualTo_5_6_ShouldBeTrue() { - Assert.IsTrue(5.LessThanOrEqualTo(6)); + Assert.That(5.LessThanOrEqualTo(6)); } - [TestMethod] + [Test] public void LessThanOrEqualTo_6_5_ShouldBeFalse() { - Assert.IsFalse(6.LessThanOrEqualTo(5)); + Assert.That(6.LessThanOrEqualTo(5), Is.False); } - [TestMethod] + [Test] public void LessThanOrEqualTo_Null_ShouldThrow() { ComparableTestClass? nullPointer = null; - Assert.ThrowsException(() => nullPointer!.LessThanOrEqualTo(nullPointer!)); + Assert.Throws(() => nullPointer!.LessThanOrEqualTo(nullPointer!)); } - [TestMethod] + [Test] public void Max_Null_ShouldThrow() { ComparableTestClass? nullPointer = null; - Assert.ThrowsException(() => nullPointer!.Max(nullPointer!)); + Assert.Throws(() => nullPointer!.Max(nullPointer!)); } - [TestMethod] + [Test] public void Min_Null_ShouldThrow() { ComparableTestClass? nullPointer = null; - Assert.ThrowsException(() => nullPointer!.Min(nullPointer!)); + Assert.Throws(() => nullPointer!.Min(nullPointer!)); } } diff --git a/X10D.Tests/src/Math/DecimalTests.Wrap.cs b/X10D.Tests/src/Math/DecimalTests.Wrap.cs index a49fd30..8b92e8c 100644 --- a/X10D.Tests/src/Math/DecimalTests.Wrap.cs +++ b/X10D.Tests/src/Math/DecimalTests.Wrap.cs @@ -1,14 +1,14 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Math; namespace X10D.Tests.Math; public partial class DecimalTests { - [TestClass] + [TestFixture] public class WrapTests { - [TestMethod] + [Test] public void Wrap_ShouldReturnLow_WhenValueIsEqualToLow() { const decimal value = 10; @@ -17,10 +17,10 @@ public partial class DecimalTests decimal result = value.Wrap(low, high); - Assert.AreEqual(low, result); + Assert.That(result, Is.EqualTo(low)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnHigh_WhenValueIsEqualToHigh() { const decimal value = 20; @@ -29,10 +29,10 @@ public partial class DecimalTests decimal result = value.Wrap(low, high); - Assert.AreEqual(low, result); + Assert.That(result, Is.EqualTo(low)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsGreaterThanHigh() { const decimal value = 30; @@ -41,10 +41,10 @@ public partial class DecimalTests decimal result = value.Wrap(low, high); - Assert.AreEqual(low, result); + Assert.That(result, Is.EqualTo(low)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsLessThanLow() { const decimal value = 5; @@ -53,10 +53,10 @@ public partial class DecimalTests decimal result = value.Wrap(low, high); - Assert.AreEqual(15.0m, result); + Assert.That(result, Is.EqualTo(15.0m)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsInBetweenLowAndHigh() { const decimal value = 15; @@ -65,10 +65,10 @@ public partial class DecimalTests decimal result = value.Wrap(low, high); - Assert.AreEqual(value, result); + Assert.That(result, Is.EqualTo(value)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnZero_WhenValueIsEqualToLength() { const decimal value = 10; @@ -76,10 +76,10 @@ public partial class DecimalTests decimal result = value.Wrap(length); - Assert.AreEqual(0.0m, result); + Assert.That(result, Is.EqualTo(0.0m)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnValue_WhenValueIsLessThanLength() { const decimal value = 5; @@ -87,10 +87,10 @@ public partial class DecimalTests decimal result = value.Wrap(length); - Assert.AreEqual(value, result); + Assert.That(result, Is.EqualTo(value)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsGreaterThanLength() { const decimal value = 15; @@ -98,7 +98,7 @@ public partial class DecimalTests decimal result = value.Wrap(length); - Assert.AreEqual(5.0m, result); + Assert.That(result, Is.EqualTo(5.0m)); } } } diff --git a/X10D.Tests/src/Math/DecimalTests.cs b/X10D.Tests/src/Math/DecimalTests.cs index a3df1c2..b93f415 100644 --- a/X10D.Tests/src/Math/DecimalTests.cs +++ b/X10D.Tests/src/Math/DecimalTests.cs @@ -1,140 +1,173 @@ using System.Numerics; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Math; namespace X10D.Tests.Math; -[TestClass] +[TestFixture] public partial class DecimalTests { - [TestMethod] + [Test] public void ComplexSqrt_ShouldBeCorrect_GivenReal() { - Assert.AreEqual(0.0, 0.0m.ComplexSqrt()); - Assert.AreEqual(1.4142135623730951, 2.0m.ComplexSqrt()); - Assert.AreEqual(3.0, 9.0m.ComplexSqrt()); - Assert.AreEqual(4.0, 16.0m.ComplexSqrt()); - Assert.AreEqual(100.0, 10000.0m.ComplexSqrt()); + Assert.Multiple(() => + { + Assert.That(0.0m.ComplexSqrt(), Is.EqualTo((Complex)0.0)); + Assert.That(2.0m.ComplexSqrt(), Is.EqualTo((Complex)1.4142135623730951)); + Assert.That(9.0m.ComplexSqrt(), Is.EqualTo((Complex)3.0)); + Assert.That(16.0m.ComplexSqrt(), Is.EqualTo((Complex)4.0)); + Assert.That(10000.0m.ComplexSqrt(), Is.EqualTo((Complex)100.0)); + }); } - [TestMethod] + [Test] public void ComplexSqrt_ShouldBeImaginary_GivenNegativeValue() { - Assert.AreEqual(new Complex(0, 1), (-1.0m).ComplexSqrt()); - Assert.AreEqual(new Complex(0, 1.4142135623730951), (-2.0m).ComplexSqrt()); - Assert.AreEqual(new Complex(0, 3.0), (-9.0m).ComplexSqrt()); - Assert.AreEqual(new Complex(0, 4.0), (-16.0m).ComplexSqrt()); + Assert.Multiple(() => + { + Assert.That((-1.0m).ComplexSqrt(), Is.EqualTo(new Complex(0, 1))); + Assert.That((-2.0m).ComplexSqrt(), Is.EqualTo(new Complex(0, 1.4142135623730951))); + Assert.That((-9.0m).ComplexSqrt(), Is.EqualTo(new Complex(0, 3.0))); + Assert.That((-16.0m).ComplexSqrt(), Is.EqualTo(new Complex(0, 4.0))); + }); } - [TestMethod] + [Test] public void IsEven_ShouldBeFalse_GivenOddNumber() { - Assert.IsFalse((-3.0m).IsEven()); - Assert.IsFalse((-1.0m).IsEven()); - Assert.IsFalse(1.0m.IsEven()); - Assert.IsFalse(3.0m.IsEven()); + Assert.Multiple(() => + { + Assert.That((-3.0m).IsEven(), Is.False); + Assert.That((-1.0m).IsEven(), Is.False); + Assert.That(1.0m.IsEven(), Is.False); + Assert.That(3.0m.IsEven(), Is.False); + }); } - [TestMethod] + [Test] public void IsEven_ShouldBeTrue_GivenOddNumber() { - Assert.IsTrue((-4.0m).IsEven()); - Assert.IsTrue((-2.0m).IsEven()); - Assert.IsTrue(0.0m.IsEven()); - Assert.IsTrue(2.0m.IsEven()); - Assert.IsTrue(4.0m.IsEven()); + Assert.Multiple(() => + { + Assert.That((-4.0m).IsEven()); + Assert.That((-2.0m).IsEven()); + Assert.That(0.0m.IsEven()); + Assert.That(2.0m.IsEven()); + Assert.That(4.0m.IsEven()); + }); } - [TestMethod] + [Test] public void IsOdd_ShouldBeFalse_GivenEvenNumber() { - Assert.IsFalse((-4.0m).IsOdd()); - Assert.IsFalse((-2.0m).IsOdd()); - Assert.IsFalse(0.0m.IsOdd()); - Assert.IsFalse(2.0m.IsOdd()); - Assert.IsFalse(4.0m.IsOdd()); + Assert.Multiple(() => + { + Assert.That((-4.0m).IsOdd(), Is.False); + Assert.That((-2.0m).IsOdd(), Is.False); + Assert.That(0.0m.IsOdd(), Is.False); + Assert.That(2.0m.IsOdd(), Is.False); + Assert.That(4.0m.IsOdd(), Is.False); + }); } - [TestMethod] + [Test] public void IsOdd_ShouldBeTrue_GivenOddNumber() { - Assert.IsTrue((-3.0m).IsOdd()); - Assert.IsTrue((-1.0m).IsOdd()); - Assert.IsTrue(1.0m.IsOdd()); - Assert.IsTrue(3.0m.IsOdd()); + Assert.Multiple(() => + { + Assert.That((-3.0m).IsOdd()); + Assert.That((-1.0m).IsOdd()); + Assert.That(1.0m.IsOdd()); + Assert.That(3.0m.IsOdd()); + }); } - [TestMethod] + [Test] public void Round_ShouldRoundToNearestInteger() { - Assert.AreEqual(4.0m, 3.5m.Round()); - Assert.AreEqual(7.0m, 6.8m.Round()); - Assert.AreEqual(7.0m, 7.2m.Round()); + Assert.Multiple(() => + { + Assert.That(3.5m.Round(), Is.EqualTo(4.0m)); + Assert.That(6.8m.Round(), Is.EqualTo(7.0m)); + Assert.That(7.2m.Round(), Is.EqualTo(7.0m)); + }); } - [TestMethod] + [Test] public void Round_ShouldRoundToNearestMultiple() { - Assert.AreEqual(5.0m, 3.5m.Round(5)); - Assert.AreEqual(5.0m, 7.0m.Round(5)); - Assert.AreEqual(10.0m, 7.5m.Round(5)); + Assert.Multiple(() => + { + Assert.That(3.5m.Round(5), Is.EqualTo(5.0m)); + Assert.That(7.0m.Round(5), Is.EqualTo(5.0m)); + Assert.That(7.5m.Round(5), Is.EqualTo(10.0m)); + }); } - [TestMethod] + [Test] public void Saturate_ShouldClampValueTo1_GivenGreaterThan1() { - Assert.AreEqual(1.0m, 1.5m.Saturate(), 1e-6m); + Assert.That(1.5m.Saturate(), Is.EqualTo(1.0m)); } - [TestMethod] + [Test] public void Saturate_ShouldClampValueTo0_GivenLessThan0() { - Assert.AreEqual(0.0m, (-0.5m).Saturate(), 1e-6m); + Assert.That((-0.5m).Saturate(), Is.EqualTo(0.0m)); } - [TestMethod] + [Test] public void Saturate_ShouldReturnValue_GivenValueBetween0And1() { - Assert.AreEqual(0.5m, 0.5m.Saturate(), 1e-6m); + Assert.That(0.5m.Saturate(), Is.EqualTo(0.5m)); } - [TestMethod] + [Test] public void Sign_ShouldBeMinus1_GivenNegative() { - Assert.AreEqual(-1, -1.0m.Sign()); - Assert.AreEqual(-1, -2.0m.Sign()); - Assert.AreEqual(-1, -3.0m.Sign()); + Assert.Multiple(() => + { + Assert.That(-1.0m.Sign(), Is.EqualTo(-1)); + Assert.That(-2.0m.Sign(), Is.EqualTo(-1)); + Assert.That(-3.0m.Sign(), Is.EqualTo(-1)); + }); } - [TestMethod] + [Test] public void Sign_ShouldBe0_Given0() { - Assert.AreEqual(0, 0.0m.Sign()); + Assert.That(0.0m.Sign(), Is.Zero); } - [TestMethod] + [Test] public void Sign_ShouldBe1_GivenPositive() { - Assert.AreEqual(1, 1.0m.Sign()); - Assert.AreEqual(1, 2.0m.Sign()); - Assert.AreEqual(1, 3.0m.Sign()); + Assert.Multiple(() => + { + Assert.That(1.0m.Sign(), Is.EqualTo(1)); + Assert.That(2.0m.Sign(), Is.EqualTo(1)); + Assert.That(3.0m.Sign(), Is.EqualTo(1)); + }); } - [TestMethod] + [Test] public void Sqrt_ShouldBeCorrect_GivenValue() { - Assert.AreEqual(0.0m, 0.0m.Sqrt()); - Assert.AreEqual(1.4142135623730950488016887242m, 2.0m.Sqrt()); - Assert.AreEqual(3.0m, 9.0m.Sqrt()); - Assert.AreEqual(4.0m, 16.0m.Sqrt()); - Assert.AreEqual(100.0m, 10000.0m.Sqrt()); + Assert.Multiple(() => + { + Assert.That(0.0m.Sqrt(), Is.EqualTo(0.0m)); + Assert.That(2.0m.Sqrt(), Is.EqualTo(1.4142135623730950488016887242m)); + Assert.That(9.0m.Sqrt(), Is.EqualTo(3.0m)); + Assert.That(16.0m.Sqrt(), Is.EqualTo(4.0m)); + Assert.That(10000.0m.Sqrt(), Is.EqualTo(100.0m)); + }); } - [TestMethod] + [Test] public void Sqrt_ShouldThrow_GivenNegativeValue() { - Assert.ThrowsException(() => (-1.0m).Sqrt()); - Assert.ThrowsException(() => (-2.0m).Sqrt()); - Assert.ThrowsException(() => (-3.0m).Sqrt()); + Assert.Throws(() => _ = (-1.0m).Sqrt()); + Assert.Throws(() => _ = (-2.0m).Sqrt()); + Assert.Throws(() => _ = (-3.0m).Sqrt()); } } diff --git a/X10D.Tests/src/Math/DoubleTests.Wrap.cs b/X10D.Tests/src/Math/DoubleTests.Wrap.cs index ff53476..b6c15f8 100644 --- a/X10D.Tests/src/Math/DoubleTests.Wrap.cs +++ b/X10D.Tests/src/Math/DoubleTests.Wrap.cs @@ -1,14 +1,14 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Math; namespace X10D.Tests.Math; public partial class DoubleTests { - [TestClass] + [TestFixture] public class WrapTests { - [TestMethod] + [Test] public void Wrap_ShouldReturnLow_WhenValueIsEqualToLow() { const double value = 10; @@ -17,10 +17,10 @@ public partial class DoubleTests double result = value.Wrap(low, high); - Assert.AreEqual(low, result); + Assert.That(result, Is.EqualTo(low)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnHigh_WhenValueIsEqualToHigh() { const double value = 20; @@ -29,10 +29,10 @@ public partial class DoubleTests double result = value.Wrap(low, high); - Assert.AreEqual(low, result); + Assert.That(result, Is.EqualTo(low)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsGreaterThanHigh() { const double value = 30; @@ -41,10 +41,10 @@ public partial class DoubleTests double result = value.Wrap(low, high); - Assert.AreEqual(low, result); + Assert.That(result, Is.EqualTo(low)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsLessThanLow() { const double value = 5; @@ -53,10 +53,10 @@ public partial class DoubleTests double result = value.Wrap(low, high); - Assert.AreEqual(15.0, result); + Assert.That(result, Is.EqualTo(15.0)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsInBetweenLowAndHigh() { const double value = 15; @@ -65,10 +65,10 @@ public partial class DoubleTests double result = value.Wrap(low, high); - Assert.AreEqual(value, result); + Assert.That(result, Is.EqualTo(value)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnZero_WhenValueIsEqualToLength() { const double value = 10; @@ -76,10 +76,10 @@ public partial class DoubleTests double result = value.Wrap(length); - Assert.AreEqual(0.0, result); + Assert.That(result, Is.EqualTo(0.0)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnValue_WhenValueIsLessThanLength() { const double value = 5; @@ -87,10 +87,10 @@ public partial class DoubleTests double result = value.Wrap(length); - Assert.AreEqual(value, result); + Assert.That(result, Is.EqualTo(value)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsGreaterThanLength() { const double value = 15; @@ -98,7 +98,7 @@ public partial class DoubleTests double result = value.Wrap(length); - Assert.AreEqual(5.0, result); + Assert.That(result, Is.EqualTo(5.0)); } } } diff --git a/X10D.Tests/src/Math/DoubleTests.cs b/X10D.Tests/src/Math/DoubleTests.cs index dc5e838..07a7bff 100644 --- a/X10D.Tests/src/Math/DoubleTests.cs +++ b/X10D.Tests/src/Math/DoubleTests.cs @@ -1,260 +1,300 @@ using System.Numerics; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Math; namespace X10D.Tests.Math; -[TestClass] +[TestFixture] public partial class DoubleTests { - [TestMethod] + [Test] public void DegreesToRadians_ShouldBeCorrect() { - Assert.AreEqual(System.Math.PI, 180.0.DegreesToRadians(), 1e-6); - Assert.AreEqual(System.Math.PI * 1.5, 270.0.DegreesToRadians(), 1e-6); - Assert.AreEqual(0.0, 0.0.DegreesToRadians(), 1e-6); - Assert.AreEqual(0.017453292519943295, 1.0.DegreesToRadians(), 1e-6); - Assert.AreEqual(0.10471975511965978, 6.0.DegreesToRadians(), 1e-6); - Assert.AreEqual(0.20943951023931956, 12.0.DegreesToRadians(), 1e-6); + Assert.Multiple(() => + { + Assert.That(180.0.DegreesToRadians(), Is.EqualTo(System.Math.PI).Within(1e-6)); + Assert.That(270.0.DegreesToRadians(), Is.EqualTo(System.Math.PI * 1.5).Within(1e-6)); + Assert.That(0.0.DegreesToRadians(), Is.EqualTo(0.0).Within(1e-6)); + Assert.That(1.0.DegreesToRadians(), Is.EqualTo(0.017453292519943295).Within(1e-6)); + Assert.That(6.0.DegreesToRadians(), Is.EqualTo(0.10471975511965978).Within(1e-6)); + Assert.That(12.0.DegreesToRadians(), Is.EqualTo(0.20943951023931956).Within(1e-6)); + }); } - [TestMethod] + [Test] public void RadiansToDegrees_ShouldBeCorrect() { - Assert.AreEqual(180.0, System.Math.PI.RadiansToDegrees(), 1e-6); - Assert.AreEqual(360.0, (2.0 * System.Math.PI).RadiansToDegrees(), 1e-6); - Assert.AreEqual(0.0, 0.0.RadiansToDegrees(), 1e-6); - Assert.AreEqual(1.0, 0.017453292519943295.RadiansToDegrees(), 1e-6); - Assert.AreEqual(6.000000000000001, 0.10471975511965978.RadiansToDegrees(), 1e-6); // rounding errors are fun - Assert.AreEqual(12.0, 0.20943951023931953.RadiansToDegrees(), 1e-6); + Assert.Multiple(() => + { + Assert.That(System.Math.PI.RadiansToDegrees(), Is.EqualTo(180.0).Within(1e-6)); + Assert.That((2.0 * System.Math.PI).RadiansToDegrees(), Is.EqualTo(360.0).Within(1e-6)); + Assert.That(0.0.RadiansToDegrees(), Is.EqualTo(0.0).Within(1e-6)); + Assert.That(0.017453292519943295.RadiansToDegrees(), Is.EqualTo(1.0).Within(1e-6)); + // rounding errors are fun + Assert.That(0.10471975511965978.RadiansToDegrees(), Is.EqualTo(6.000000000000001).Within(1e-6)); + Assert.That(0.20943951023931953.RadiansToDegrees(), Is.EqualTo(12.0).Within(1e-6)); + }); } - [TestMethod] + [Test] public void ComplexSqrt_ShouldBeCorrect_GivenReal() { - Assert.AreEqual(0.0, 0.0.ComplexSqrt()); - Assert.AreEqual(1.4142135623730951, 2.0.ComplexSqrt()); - Assert.AreEqual(3.0, 9.0.ComplexSqrt()); - Assert.AreEqual(4.0, 16.0.ComplexSqrt()); - Assert.AreEqual(100.0, 10000.0.ComplexSqrt()); + Assert.Multiple(() => + { + Assert.That(0.0.ComplexSqrt(), Is.EqualTo((Complex)0.0)); + Assert.That(2.0.ComplexSqrt(), Is.EqualTo((Complex)1.4142135623730951)); + Assert.That(9.0.ComplexSqrt(), Is.EqualTo((Complex)3.0)); + Assert.That(16.0.ComplexSqrt(), Is.EqualTo((Complex)4.0)); + Assert.That(10000.0.ComplexSqrt(), Is.EqualTo((Complex)100.0)); + }); } - [TestMethod] + [Test] public void ComplexSqrt_ShouldBeImaginary_GivenNegativeValue() { - Assert.AreEqual(new Complex(0, 1), (-1.0).ComplexSqrt()); - Assert.AreEqual(new Complex(0, 1.4142135623730951), (-2.0).ComplexSqrt()); - Assert.AreEqual(new Complex(0, 3.0), (-9.0).ComplexSqrt()); - Assert.AreEqual(new Complex(0, 4.0), (-16.0).ComplexSqrt()); + Assert.Multiple(() => + { + Assert.That((-1.0).ComplexSqrt(), Is.EqualTo(new Complex(0, 1))); + Assert.That((-2.0).ComplexSqrt(), Is.EqualTo(new Complex(0, 1.4142135623730951))); + Assert.That((-9.0).ComplexSqrt(), Is.EqualTo(new Complex(0, 3.0))); + Assert.That((-16.0).ComplexSqrt(), Is.EqualTo(new Complex(0, 4.0))); + }); } - [TestMethod] + [Test] public void ComplexSqrt_ShouldBeComplexInfinity_GivenInfinity() { - Assert.AreEqual(Complex.Infinity, double.NegativeInfinity.ComplexSqrt()); - Assert.AreEqual(Complex.Infinity, double.PositiveInfinity.ComplexSqrt()); + Assert.Multiple(() => + { + Assert.That(double.NegativeInfinity.ComplexSqrt(), Is.EqualTo(Complex.Infinity)); + Assert.That(double.PositiveInfinity.ComplexSqrt(), Is.EqualTo(Complex.Infinity)); + }); } - [TestMethod] + [Test] public void ComplexSqrt_ShouldBeNaN_GivenNaN() { - Assert.AreEqual(Complex.NaN, double.NaN.ComplexSqrt()); + Assert.That(double.NaN.ComplexSqrt(), Is.EqualTo(Complex.NaN)); } - [TestMethod] + [Test] public void IsEven_ShouldBeFalse_GivenOddNumber() { - Assert.IsFalse((-3.0).IsEven()); - Assert.IsFalse((-1.0).IsEven()); - Assert.IsFalse(1.0.IsEven()); - Assert.IsFalse(3.0.IsEven()); + Assert.Multiple(() => + { + Assert.That((-3.0).IsEven(), Is.False); + Assert.That((-1.0).IsEven(), Is.False); + Assert.That(1.0.IsEven(), Is.False); + Assert.That(3.0.IsEven(), Is.False); + }); } - [TestMethod] + [Test] public void IsEven_ShouldBeTrue_GivenOddNumber() { - Assert.IsTrue((-4.0).IsEven()); - Assert.IsTrue((-2.0).IsEven()); - Assert.IsTrue(0.0.IsEven()); - Assert.IsTrue(2.0.IsEven()); - Assert.IsTrue(4.0.IsEven()); + Assert.Multiple(() => + { + Assert.That((-4.0).IsEven()); + Assert.That((-2.0).IsEven()); + Assert.That(0.0.IsEven()); + Assert.That(2.0.IsEven()); + Assert.That(4.0.IsEven()); + }); } - [TestMethod] + [Test] public void IsOdd_ShouldBeFalse_GivenEvenNumber() { - Assert.IsFalse((-4.0).IsOdd()); - Assert.IsFalse((-2.0).IsOdd()); - Assert.IsFalse(0.0.IsOdd()); - Assert.IsFalse(2.0.IsOdd()); - Assert.IsFalse(4.0.IsOdd()); + Assert.Multiple(() => + { + Assert.That((-4.0).IsOdd(), Is.False); + Assert.That((-2.0).IsOdd(), Is.False); + Assert.That(0.0.IsOdd(), Is.False); + Assert.That(2.0.IsOdd(), Is.False); + Assert.That(4.0.IsOdd(), Is.False); + }); } - [TestMethod] + [Test] public void IsOdd_ShouldBeTrue_GivenOddNumber() { - Assert.IsTrue((-3.0).IsOdd()); - Assert.IsTrue((-1.0).IsOdd()); - Assert.IsTrue(1.0.IsOdd()); - Assert.IsTrue(3.0.IsOdd()); + Assert.Multiple(() => + { + Assert.That((-3.0).IsOdd()); + Assert.That((-1.0).IsOdd()); + Assert.That(1.0.IsOdd()); + Assert.That(3.0.IsOdd()); + }); } - [TestMethod] + [Test] public void Round_ShouldRoundToNearestInteger() { - Assert.AreEqual(4.0, 3.5.Round(), 1e-6); - Assert.AreEqual(7.0, 6.8.Round(), 1e-6); - Assert.AreEqual(7.0, 7.2.Round(), 1e-6); + Assert.That(3.5.Round(), Is.EqualTo(4.0).Within(1e-6)); + Assert.That(6.8.Round(), Is.EqualTo(7.0).Within(1e-6)); + Assert.That(7.2.Round(), Is.EqualTo(7.0).Within(1e-6)); } - [TestMethod] + [Test] public void Round_ShouldRoundToNearestMultiple() { - Assert.AreEqual(5.0, 3.5.Round(5), 1e-6); - Assert.AreEqual(5.0, 7.0.Round(5), 1e-6); - Assert.AreEqual(10.0, 7.5.Round(5), 1e-6); + Assert.That(3.5.Round(5), Is.EqualTo(5.0).Within(1e-6)); + Assert.That(7.0.Round(5), Is.EqualTo(5.0).Within(1e-6)); + Assert.That(7.5.Round(5), Is.EqualTo(10.0).Within(1e-6)); } - [TestMethod] + [Test] public void Saturate_ShouldClampValueTo1_GivenGreaterThan1() { - Assert.AreEqual(1.0, 1.5.Saturate(), 1e-6); + Assert.That(1.5.Saturate(), Is.EqualTo(1.0).Within(1e-6)); } - [TestMethod] + [Test] public void Saturate_ShouldClampValueTo0_GivenLessThan0() { - Assert.AreEqual(0.0, (-0.5).Saturate(), 1e-6); + Assert.That((-0.5).Saturate(), Is.EqualTo(0.0).Within(1e-6)); } - [TestMethod] + [Test] public void Saturate_ShouldReturnValue_GivenValueBetween0And1() { - Assert.AreEqual(0.5, 0.5.Saturate(), 1e-6); + Assert.That(0.5.Saturate(), Is.EqualTo(0.5).Within(1e-6)); } - [TestMethod] + [Test] public void Sign_ShouldBeMinus1_GivenNegative() { - Assert.AreEqual(-1, -1.0.Sign()); - Assert.AreEqual(-1, -2.0.Sign()); - Assert.AreEqual(-1, -3.0.Sign()); + Assert.Multiple(() => + { + Assert.That(-1.0.Sign(), Is.EqualTo(-1)); + Assert.That(-2.0.Sign(), Is.EqualTo(-1)); + Assert.That(-3.0.Sign(), Is.EqualTo(-1)); + }); } - [TestMethod] + [Test] public void Sign_ShouldBe0_Given0() { - Assert.AreEqual(0, 0.0.Sign()); + Assert.That(0.0.Sign(), Is.Zero); } - [TestMethod] + [Test] public void Sign_ShouldBe1_GivenPositive() { - Assert.AreEqual(1, 1.0.Sign()); - Assert.AreEqual(1, 2.0.Sign()); - Assert.AreEqual(1, 3.0.Sign()); + Assert.Multiple(() => + { + Assert.That(1.0.Sign(), Is.EqualTo(1)); + Assert.That(2.0.Sign(), Is.EqualTo(1)); + Assert.That(3.0.Sign(), Is.EqualTo(1)); + }); } - [TestMethod] + [Test] public void Sqrt_ShouldBeCorrect_GivenValue() { - Assert.AreEqual(0.0, 0.0.Sqrt(), 1e-6); - Assert.AreEqual(1.414213562373095, 2.0.Sqrt(), 1e-6); - Assert.AreEqual(3.0, 9.0.Sqrt(), 1e-6); - Assert.AreEqual(4.0, 16.0.Sqrt(), 1e-6); - Assert.AreEqual(100.0, 10000.0.Sqrt(), 1e-6); + Assert.Multiple(() => + { + Assert.That(0.0.Sqrt(), Is.EqualTo(0.0).Within(1e-6)); + Assert.That(2.0.Sqrt(), Is.EqualTo(1.414213562373095).Within(1e-6)); + Assert.That(9.0.Sqrt(), Is.EqualTo(3.0).Within(1e-6)); + Assert.That(16.0.Sqrt(), Is.EqualTo(4.0).Within(1e-6)); + Assert.That(10000.0.Sqrt(), Is.EqualTo(100.0).Within(1e-6)); + }); } - [TestMethod] + [Test] public void Sqrt_ShouldBeNaN_GivenNaN() { - Assert.AreEqual(double.NaN, double.NaN.Sqrt()); + Assert.That(double.NaN.Sqrt(), Is.EqualTo(double.NaN)); } - [TestMethod] + [Test] public void Sqrt_ShouldBeNaN_GivenNegativeValue() { - Assert.AreEqual(double.NaN, (-1.0).Sqrt()); - Assert.AreEqual(double.NaN, (-2.0).Sqrt()); - Assert.AreEqual(double.NaN, (-3.0).Sqrt()); - Assert.AreEqual(double.NaN, double.NegativeInfinity.Sqrt()); + Assert.Multiple(() => + { + Assert.That((-1.0).Sqrt(), Is.EqualTo(double.NaN)); + Assert.That((-2.0).Sqrt(), Is.EqualTo(double.NaN)); + Assert.That((-3.0).Sqrt(), Is.EqualTo(double.NaN)); + Assert.That(double.NegativeInfinity.Sqrt(), Is.EqualTo(double.NaN)); + }); } - [TestMethod] + [Test] public void Sqrt_ShouldBePositiveInfinity_GivenPositiveInfinity() { - Assert.AreEqual(double.PositiveInfinity, double.PositiveInfinity.Sqrt()); + Assert.That(double.PositiveInfinity.Sqrt(), Is.EqualTo(double.PositiveInfinity)); } - [TestMethod] + [Test] public void Acos_ShouldBeCorrect() { - Assert.AreEqual(1.0471975511965979, 0.5.Acos(), 1e-6); + Assert.That(0.5.Acos(), Is.EqualTo(1.0471975511965979).Within(1e-6)); } - [TestMethod] + [Test] public void Acosh_ShouldBeCorrect() { - Assert.AreEqual(0.9624236501192069, 1.5.Acosh(), 1e-6); + Assert.That(1.5.Acosh(), Is.EqualTo(0.9624236501192069).Within(1e-6)); } - [TestMethod] + [Test] public void Asin_ShouldBeCorrect() { - Assert.AreEqual(0.5235987755982989, 0.5.Asin(), 1e-6); + Assert.That(0.5.Asin(), Is.EqualTo(0.5235987755982989).Within(1e-6)); } - [TestMethod] + [Test] public void Asinh_ShouldBeCorrect() { - Assert.AreEqual(1.1947632172871094, 1.5.Asinh(), 1e-6); + Assert.That(1.5.Asinh(), Is.EqualTo(1.1947632172871094).Within(1e-6)); } - [TestMethod] + [Test] public void Atan_ShouldBeCorrect() { - Assert.AreEqual(0.4636476090008061, 0.5.Atan(), 1e-6); + Assert.That(0.5.Atan(), Is.EqualTo(0.4636476090008061).Within(1e-6)); } - [TestMethod] + [Test] public void Atanh_ShouldBeCorrect() { - Assert.AreEqual(0.5493061443340549, 0.5.Atanh(), 1e-6); + Assert.That(0.5.Atanh(), Is.EqualTo(0.5493061443340549).Within(1e-6)); } - [TestMethod] + [Test] public void Cos_ShouldBeCorrect() { - Assert.AreEqual(0.8775825618903728, 0.5.Cos(), 1e-6); + Assert.That(0.5.Cos(), Is.EqualTo(0.8775825618903728).Within(1e-6)); } - [TestMethod] + [Test] public void Cosh_ShouldBeCorrect() { - Assert.AreEqual(2.352409615243247, 1.5.Cosh(), 1e-6); + Assert.That(1.5.Cosh(), Is.EqualTo(2.352409615243247).Within(1e-6)); } - [TestMethod] + [Test] public void Sin_ShouldBeCorrect() { - Assert.AreEqual(0.479425538604203, 0.5.Sin(), 1e-6); + Assert.That(0.5.Sin(), Is.EqualTo(0.479425538604203).Within(1e-6)); } - [TestMethod] + [Test] public void Sinh_ShouldBeCorrect() { - Assert.AreEqual(2.1292794550948173, 1.5.Sinh(), 1e-6); + Assert.That(1.5.Sinh(), Is.EqualTo(2.1292794550948173).Within(1e-6)); } - [TestMethod] + [Test] public void Tan_ShouldBeCorrect() { - Assert.AreEqual(0.5463024898437905, 0.5.Tan(), 1e-6); + Assert.That(0.5.Tan(), Is.EqualTo(0.5463024898437905).Within(1e-6)); } - [TestMethod] + [Test] public void Tanh_ShouldBeCorrect() { - Assert.AreEqual(0.46211715726000974, 0.5.Tanh(), 1e-6); + Assert.That(0.5.Tanh(), Is.EqualTo(0.46211715726000974).Within(1e-6)); } } diff --git a/X10D.Tests/src/Math/Int16Tests.Wrap.cs b/X10D.Tests/src/Math/Int16Tests.Wrap.cs index 31054f4..bdd290a 100644 --- a/X10D.Tests/src/Math/Int16Tests.Wrap.cs +++ b/X10D.Tests/src/Math/Int16Tests.Wrap.cs @@ -1,14 +1,14 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Math; namespace X10D.Tests.Math; public partial class Int16Tests { - [TestClass] + [TestFixture] public class WrapTests { - [TestMethod] + [Test] public void Wrap_ShouldReturnLow_WhenValueIsEqualToLow() { const short value = 10; @@ -17,10 +17,10 @@ public partial class Int16Tests short result = value.Wrap(low, high); - Assert.AreEqual(low, result); + Assert.That(result, Is.EqualTo(low)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnHigh_WhenValueIsEqualToHigh() { const short value = 20; @@ -29,10 +29,10 @@ public partial class Int16Tests short result = value.Wrap(low, high); - Assert.AreEqual(low, result); + Assert.That(result, Is.EqualTo(low)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsGreaterThanHigh() { const short value = 30; @@ -41,10 +41,10 @@ public partial class Int16Tests short result = value.Wrap(low, high); - Assert.AreEqual(low, result); + Assert.That(result, Is.EqualTo(low)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsLessThanLow() { const short value = 5; @@ -53,10 +53,10 @@ public partial class Int16Tests short result = value.Wrap(low, high); - Assert.AreEqual(15, result); + Assert.That(result, Is.EqualTo(15)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsInBetweenLowAndHigh() { const short value = 15; @@ -65,10 +65,10 @@ public partial class Int16Tests short result = value.Wrap(low, high); - Assert.AreEqual(value, result); + Assert.That(result, Is.EqualTo(value)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnZero_WhenValueIsEqualToLength() { const short value = 10; @@ -76,10 +76,10 @@ public partial class Int16Tests short result = value.Wrap(length); - Assert.AreEqual(0, result); + Assert.That(result, Is.Zero); } - [TestMethod] + [Test] public void Wrap_ShouldReturnValue_WhenValueIsLessThanLength() { const short value = 5; @@ -87,10 +87,10 @@ public partial class Int16Tests short result = value.Wrap(length); - Assert.AreEqual(value, result); + Assert.That(result, Is.EqualTo(value)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsGreaterThanLength() { const short value = 15; @@ -98,7 +98,7 @@ public partial class Int16Tests short result = value.Wrap(length); - Assert.AreEqual(5, result); + Assert.That(result, Is.EqualTo(5)); } } } diff --git a/X10D.Tests/src/Math/Int16Tests.cs b/X10D.Tests/src/Math/Int16Tests.cs index 1cfac50..50591cc 100644 --- a/X10D.Tests/src/Math/Int16Tests.cs +++ b/X10D.Tests/src/Math/Int16Tests.cs @@ -1,36 +1,36 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Math; namespace X10D.Tests.Math; -[TestClass] +[TestFixture] public partial class Int16Tests { - [TestMethod] + [Test] public void DigitalRootShouldBeCorrect() { const short value = 238; - Assert.AreEqual(4, value.DigitalRoot()); - Assert.AreEqual(4, (-value).DigitalRoot()); + Assert.That(value.DigitalRoot(), Is.EqualTo(4)); + Assert.That((-value).DigitalRoot(), Is.EqualTo(4)); } - [TestMethod] + [Test] public void FactorialShouldBeCorrect() { - Assert.AreEqual(1L, ((short)0).Factorial()); - Assert.AreEqual(1L, ((short)1).Factorial()); - Assert.AreEqual(2L, ((short)2).Factorial()); - Assert.AreEqual(6L, ((short)3).Factorial()); - Assert.AreEqual(24L, ((short)4).Factorial()); - Assert.AreEqual(120L, ((short)5).Factorial()); - Assert.AreEqual(720L, ((short)6).Factorial()); - Assert.AreEqual(5040L, ((short)7).Factorial()); - Assert.AreEqual(40320L, ((short)8).Factorial()); - Assert.AreEqual(362880L, ((short)9).Factorial()); - Assert.AreEqual(3628800L, ((short)10).Factorial()); + Assert.That(((short)0).Factorial(), Is.EqualTo(1L)); + Assert.That(((short)1).Factorial(), Is.EqualTo(1L)); + Assert.That(((short)2).Factorial(), Is.EqualTo(2L)); + Assert.That(((short)3).Factorial(), Is.EqualTo(6L)); + Assert.That(((short)4).Factorial(), Is.EqualTo(24L)); + Assert.That(((short)5).Factorial(), Is.EqualTo(120L)); + Assert.That(((short)6).Factorial(), Is.EqualTo(720L)); + Assert.That(((short)7).Factorial(), Is.EqualTo(5040L)); + Assert.That(((short)8).Factorial(), Is.EqualTo(40320L)); + Assert.That(((short)9).Factorial(), Is.EqualTo(362880L)); + Assert.That(((short)10).Factorial(), Is.EqualTo(3628800L)); } - [TestMethod] + [Test] public void GreatestCommonFactor_ShouldBe1_ForPrimeNumbers() { const short first = 5; @@ -38,10 +38,10 @@ public partial class Int16Tests short multiple = first.GreatestCommonFactor(second); - Assert.AreEqual(1, multiple); + Assert.That(multiple, Is.EqualTo(1)); } - [TestMethod] + [Test] public void GreatestCommonFactor_ShouldBe6_Given12And18() { const short first = 12; @@ -49,30 +49,30 @@ public partial class Int16Tests short multiple = first.GreatestCommonFactor(second); - Assert.AreEqual(6, multiple); + Assert.That(multiple, Is.EqualTo(6)); } - [TestMethod] + [Test] public void IsEvenShouldBeCorrect() { const short one = 1; const short two = 2; - Assert.IsFalse(one.IsEven()); - Assert.IsTrue(two.IsEven()); + Assert.That(one.IsEven(), Is.False); + Assert.That(two.IsEven()); } - [TestMethod] + [Test] public void IsOddShouldBeCorrect() { const short one = 1; const short two = 2; - Assert.IsTrue(one.IsOdd()); - Assert.IsFalse(two.IsOdd()); + Assert.That(one.IsOdd()); + Assert.That(two.IsOdd(), Is.False); } - [TestMethod] + [Test] public void LowestCommonMultiple_ShouldReturnCorrectValue_WhenCalledWithValidInput() { const short value1 = 2; @@ -81,10 +81,10 @@ public partial class Int16Tests short result = value1.LowestCommonMultiple(value2); - Assert.AreEqual(expected, result); + Assert.That(result, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void LowestCommonMultiple_ShouldReturnZero_WhenCalledWithZero() { const short value1 = 0; @@ -93,10 +93,10 @@ public partial class Int16Tests short result = value1.LowestCommonMultiple(value2); - Assert.AreEqual(expected, result); + Assert.That(result, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void LowestCommonMultiple_ShouldReturnGreaterValue_WhenCalledWithOne() { const short value1 = 1; @@ -106,11 +106,11 @@ public partial class Int16Tests short result1 = value1.LowestCommonMultiple(value2); short result2 = value2.LowestCommonMultiple(value1); - Assert.AreEqual(expected, result1); - Assert.AreEqual(expected, result2); + Assert.That(result1, Is.EqualTo(expected)); + Assert.That(result2, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void LowestCommonMultiple_ShouldReturnOtherValue_WhenCalledWithSameValue() { const short value1 = 5; @@ -119,10 +119,10 @@ public partial class Int16Tests short result = value1.LowestCommonMultiple(value2); - Assert.AreEqual(expected, result); + Assert.That(result, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void LowestCommonMultiple_ShouldReturnCorrectValue_WhenCalledWithNegativeValues() { const short value1 = -2; @@ -131,43 +131,43 @@ public partial class Int16Tests short result = value1.LowestCommonMultiple(value2); - Assert.AreEqual(expected, result); + Assert.That(result, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void MultiplicativePersistence_ShouldReturn1_ForAnyDigitBeing0() { - Assert.AreEqual(1, ((short)10).MultiplicativePersistence()); - Assert.AreEqual(1, ((short)201).MultiplicativePersistence()); - Assert.AreEqual(1, ((short)200).MultiplicativePersistence()); - Assert.AreEqual(1, ((short)20007).MultiplicativePersistence()); + Assert.That(((short)10).MultiplicativePersistence(), Is.EqualTo(1)); + Assert.That(((short)201).MultiplicativePersistence(), Is.EqualTo(1)); + Assert.That(((short)200).MultiplicativePersistence(), Is.EqualTo(1)); + Assert.That(((short)20007).MultiplicativePersistence(), Is.EqualTo(1)); } - [TestMethod] + [Test] public void MultiplicativePersistence_ShouldBeCorrect_ForRecordHolders() { - Assert.AreEqual(0, ((short)0).MultiplicativePersistence()); - Assert.AreEqual(1, ((short)10).MultiplicativePersistence()); - Assert.AreEqual(2, ((short)25).MultiplicativePersistence()); - Assert.AreEqual(3, ((short)39).MultiplicativePersistence()); - Assert.AreEqual(4, ((short)77).MultiplicativePersistence()); - Assert.AreEqual(5, ((short)679).MultiplicativePersistence()); - Assert.AreEqual(6, ((short)6788).MultiplicativePersistence()); + Assert.That(((short)0).MultiplicativePersistence(), Is.Zero); + Assert.That(((short)10).MultiplicativePersistence(), Is.EqualTo(1)); + Assert.That(((short)25).MultiplicativePersistence(), Is.EqualTo(2)); + Assert.That(((short)39).MultiplicativePersistence(), Is.EqualTo(3)); + Assert.That(((short)77).MultiplicativePersistence(), Is.EqualTo(4)); + Assert.That(((short)679).MultiplicativePersistence(), Is.EqualTo(5)); + Assert.That(((short)6788).MultiplicativePersistence(), Is.EqualTo(6)); } - [TestMethod] + [Test] public void NegativeFactorialShouldThrow() { - Assert.ThrowsException(() => ((short)-1).Factorial()); + Assert.Throws(() => ((short)-1).Factorial()); } - [TestMethod] + [Test] public void SignShouldBeCorrect() { const short one = 1; const short zero = 0; - Assert.AreEqual(one, one.Sign()); - Assert.AreEqual(zero, zero.Sign()); - Assert.AreEqual(-one, (-one).Sign()); + Assert.That(one.Sign(), Is.EqualTo(one)); + Assert.That(zero.Sign(), Is.EqualTo(zero)); + Assert.That((-one).Sign(), Is.EqualTo(-one)); } } diff --git a/X10D.Tests/src/Math/Int32Tests.Wrap.cs b/X10D.Tests/src/Math/Int32Tests.Wrap.cs index ef8a29b..306ac09 100644 --- a/X10D.Tests/src/Math/Int32Tests.Wrap.cs +++ b/X10D.Tests/src/Math/Int32Tests.Wrap.cs @@ -1,14 +1,14 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Math; namespace X10D.Tests.Math; public partial class Int32Tests { - [TestClass] + [TestFixture] public class WrapTests { - [TestMethod] + [Test] public void Wrap_ShouldReturnLow_WhenValueIsEqualToLow() { const int value = 10; @@ -17,10 +17,10 @@ public partial class Int32Tests int result = value.Wrap(low, high); - Assert.AreEqual(low, result); + Assert.That(result, Is.EqualTo(low)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnHigh_WhenValueIsEqualToHigh() { const int value = 20; @@ -29,10 +29,10 @@ public partial class Int32Tests int result = value.Wrap(low, high); - Assert.AreEqual(low, result); + Assert.That(result, Is.EqualTo(low)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsGreaterThanHigh() { const int value = 30; @@ -41,10 +41,10 @@ public partial class Int32Tests int result = value.Wrap(low, high); - Assert.AreEqual(low, result); + Assert.That(result, Is.EqualTo(low)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsLessThanLow() { const int value = 5; @@ -53,10 +53,10 @@ public partial class Int32Tests int result = value.Wrap(low, high); - Assert.AreEqual(15, result); + Assert.That(result, Is.EqualTo(15)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsInBetweenLowAndHigh() { const int value = 15; @@ -65,10 +65,10 @@ public partial class Int32Tests int result = value.Wrap(low, high); - Assert.AreEqual(value, result); + Assert.That(result, Is.EqualTo(value)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnZero_WhenValueIsEqualToLength() { const int value = 10; @@ -76,10 +76,10 @@ public partial class Int32Tests int result = value.Wrap(length); - Assert.AreEqual(0, result); + Assert.That(result, Is.Zero); } - [TestMethod] + [Test] public void Wrap_ShouldReturnValue_WhenValueIsLessThanLength() { const int value = 5; @@ -87,10 +87,10 @@ public partial class Int32Tests int result = value.Wrap(length); - Assert.AreEqual(value, result); + Assert.That(result, Is.EqualTo(value)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsGreaterThanLength() { const int value = 15; @@ -98,7 +98,7 @@ public partial class Int32Tests int result = value.Wrap(length); - Assert.AreEqual(5, result); + Assert.That(result, Is.EqualTo(5)); } } } diff --git a/X10D.Tests/src/Math/Int32Tests.cs b/X10D.Tests/src/Math/Int32Tests.cs index 66246d3..e412200 100644 --- a/X10D.Tests/src/Math/Int32Tests.cs +++ b/X10D.Tests/src/Math/Int32Tests.cs @@ -1,36 +1,36 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Math; namespace X10D.Tests.Math; -[TestClass] +[TestFixture] public partial class Int32Tests { - [TestMethod] + [Test] public void DigitalRootShouldBeCorrect() { const int value = 238; - Assert.AreEqual(4, value.DigitalRoot()); - Assert.AreEqual(4, (-value).DigitalRoot()); + Assert.That(value.DigitalRoot(), Is.EqualTo(4)); + Assert.That((-value).DigitalRoot(), Is.EqualTo(4)); } - [TestMethod] + [Test] public void FactorialShouldBeCorrect() { - Assert.AreEqual(1L, 0.Factorial()); - Assert.AreEqual(1L, 1.Factorial()); - Assert.AreEqual(2L, 2.Factorial()); - Assert.AreEqual(6L, 3.Factorial()); - Assert.AreEqual(24L, 4.Factorial()); - Assert.AreEqual(120L, 5.Factorial()); - Assert.AreEqual(720L, 6.Factorial()); - Assert.AreEqual(5040L, 7.Factorial()); - Assert.AreEqual(40320L, 8.Factorial()); - Assert.AreEqual(362880L, 9.Factorial()); - Assert.AreEqual(3628800L, 10.Factorial()); + Assert.That(0.Factorial(), Is.EqualTo(1L)); + Assert.That(1.Factorial(), Is.EqualTo(1L)); + Assert.That(2.Factorial(), Is.EqualTo(2L)); + Assert.That(3.Factorial(), Is.EqualTo(6L)); + Assert.That(4.Factorial(), Is.EqualTo(24L)); + Assert.That(5.Factorial(), Is.EqualTo(120L)); + Assert.That(6.Factorial(), Is.EqualTo(720L)); + Assert.That(7.Factorial(), Is.EqualTo(5040L)); + Assert.That(8.Factorial(), Is.EqualTo(40320L)); + Assert.That(9.Factorial(), Is.EqualTo(362880L)); + Assert.That(10.Factorial(), Is.EqualTo(3628800L)); } - [TestMethod] + [Test] public void GreatestCommonFactor_ShouldBe1_ForPrimeNumbers() { const int first = 5; @@ -38,10 +38,10 @@ public partial class Int32Tests int multiple = first.GreatestCommonFactor(second); - Assert.AreEqual(1, multiple); + Assert.That(multiple, Is.EqualTo(1)); } - [TestMethod] + [Test] public void GreatestCommonFactor_ShouldBe6_Given12And18() { const int first = 12; @@ -49,30 +49,30 @@ public partial class Int32Tests int multiple = first.GreatestCommonFactor(second); - Assert.AreEqual(6, multiple); + Assert.That(multiple, Is.EqualTo(6)); } - [TestMethod] + [Test] public void IsEvenShouldBeCorrect() { const int one = 1; const int two = 2; - Assert.IsFalse(one.IsEven()); - Assert.IsTrue(two.IsEven()); + Assert.That(one.IsEven(), Is.False); + Assert.That(two.IsEven()); } - [TestMethod] + [Test] public void IsOddShouldBeCorrect() { const int one = 1; const int two = 2; - Assert.IsTrue(one.IsOdd()); - Assert.IsFalse(two.IsOdd()); + Assert.That(one.IsOdd()); + Assert.That(two.IsOdd(), Is.False); } - [TestMethod] + [Test] public void LowestCommonMultiple_ShouldReturnCorrectValue_WhenCalledWithValidInput() { const int value1 = 2; @@ -81,10 +81,10 @@ public partial class Int32Tests int result = value1.LowestCommonMultiple(value2); - Assert.AreEqual(expected, result); + Assert.That(result, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void LowestCommonMultiple_ShouldReturnZero_WhenCalledWithZero() { const int value1 = 0; @@ -93,10 +93,10 @@ public partial class Int32Tests int result = value1.LowestCommonMultiple(value2); - Assert.AreEqual(expected, result); + Assert.That(result, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void LowestCommonMultiple_ShouldReturnGreaterValue_WhenCalledWithOne() { const int value1 = 1; @@ -105,10 +105,10 @@ public partial class Int32Tests int result = value1.LowestCommonMultiple(value2); - Assert.AreEqual(expected, result); + Assert.That(result, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void LowestCommonMultiple_ShouldReturnOtherValue_WhenCalledWithSameValue() { const int value1 = 5; @@ -117,10 +117,10 @@ public partial class Int32Tests int result = value1.LowestCommonMultiple(value2); - Assert.AreEqual(expected, result); + Assert.That(result, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void LowestCommonMultiple_ShouldReturnCorrectValue_WhenCalledWithNegativeValues() { const int value1 = -2; @@ -130,47 +130,47 @@ public partial class Int32Tests int result1 = value1.LowestCommonMultiple(value2); int result2 = value2.LowestCommonMultiple(value1); - Assert.AreEqual(expected, result1); - Assert.AreEqual(expected, result2); + Assert.That(result1, Is.EqualTo(expected)); + Assert.That(result2, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void MultiplicativePersistence_ShouldReturn1_ForAnyDigitBeing0() { - Assert.AreEqual(1, 10.MultiplicativePersistence()); - Assert.AreEqual(1, 201.MultiplicativePersistence()); - Assert.AreEqual(1, 200.MultiplicativePersistence()); - Assert.AreEqual(1, 20007.MultiplicativePersistence()); + Assert.That(10.MultiplicativePersistence(), Is.EqualTo(1)); + Assert.That(201.MultiplicativePersistence(), Is.EqualTo(1)); + Assert.That(200.MultiplicativePersistence(), Is.EqualTo(1)); + Assert.That(20007.MultiplicativePersistence(), Is.EqualTo(1)); } - [TestMethod] + [Test] public void MultiplicativePersistence_ShouldBeCorrect_ForRecordHolders() { - Assert.AreEqual(0, 0.MultiplicativePersistence()); - Assert.AreEqual(1, 10.MultiplicativePersistence()); - Assert.AreEqual(2, 25.MultiplicativePersistence()); - Assert.AreEqual(3, 39.MultiplicativePersistence()); - Assert.AreEqual(4, 77.MultiplicativePersistence()); - Assert.AreEqual(5, 679.MultiplicativePersistence()); - Assert.AreEqual(6, 6788.MultiplicativePersistence()); - Assert.AreEqual(7, 68889.MultiplicativePersistence()); - Assert.AreEqual(8, 2677889.MultiplicativePersistence()); - Assert.AreEqual(9, 26888999.MultiplicativePersistence()); + Assert.That(0.MultiplicativePersistence(), Is.Zero); + Assert.That(10.MultiplicativePersistence(), Is.EqualTo(1)); + Assert.That(25.MultiplicativePersistence(), Is.EqualTo(2)); + Assert.That(39.MultiplicativePersistence(), Is.EqualTo(3)); + Assert.That(77.MultiplicativePersistence(), Is.EqualTo(4)); + Assert.That(679.MultiplicativePersistence(), Is.EqualTo(5)); + Assert.That(6788.MultiplicativePersistence(), Is.EqualTo(6)); + Assert.That(68889.MultiplicativePersistence(), Is.EqualTo(7)); + Assert.That(2677889.MultiplicativePersistence(), Is.EqualTo(8)); + Assert.That(26888999.MultiplicativePersistence(), Is.EqualTo(9)); } - [TestMethod] + [Test] public void NegativeFactorialShouldThrow() { - Assert.ThrowsException(() => (-1).Factorial()); + Assert.Throws(() => (-1).Factorial()); } - [TestMethod] + [Test] public void SignShouldBeCorrect() { const int one = 1; const int zero = 0; - Assert.AreEqual(one, one.Sign()); - Assert.AreEqual(zero, zero.Sign()); - Assert.AreEqual(-one, (-one).Sign()); + Assert.That(one.Sign(), Is.EqualTo(one)); + Assert.That(zero.Sign(), Is.EqualTo(zero)); + Assert.That((-one).Sign(), Is.EqualTo(-one)); } } diff --git a/X10D.Tests/src/Math/Int64Tests.Wrap.cs b/X10D.Tests/src/Math/Int64Tests.Wrap.cs index dd2a27d..c8985d3 100644 --- a/X10D.Tests/src/Math/Int64Tests.Wrap.cs +++ b/X10D.Tests/src/Math/Int64Tests.Wrap.cs @@ -1,14 +1,14 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Math; namespace X10D.Tests.Math; public partial class Int64Tests { - [TestClass] + [TestFixture] public class WrapTests { - [TestMethod] + [Test] public void Wrap_ShouldReturnLow_WhenValueIsEqualToLow() { const long value = 10; @@ -17,10 +17,10 @@ public partial class Int64Tests long result = value.Wrap(low, high); - Assert.AreEqual(low, result); + Assert.That(result, Is.EqualTo(low)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnHigh_WhenValueIsEqualToHigh() { const long value = 20; @@ -29,10 +29,10 @@ public partial class Int64Tests long result = value.Wrap(low, high); - Assert.AreEqual(low, result); + Assert.That(result, Is.EqualTo(low)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsGreaterThanHigh() { const long value = 30; @@ -41,10 +41,10 @@ public partial class Int64Tests long result = value.Wrap(low, high); - Assert.AreEqual(low, result); + Assert.That(result, Is.EqualTo(low)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsLessThanLow() { const long value = 5; @@ -53,10 +53,10 @@ public partial class Int64Tests long result = value.Wrap(low, high); - Assert.AreEqual(15L, result); + Assert.That(result, Is.EqualTo(15L)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsInBetweenLowAndHigh() { const long value = 15; @@ -65,10 +65,10 @@ public partial class Int64Tests long result = value.Wrap(low, high); - Assert.AreEqual(value, result); + Assert.That(result, Is.EqualTo(value)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnZero_WhenValueIsEqualToLength() { const long value = 10; @@ -76,10 +76,10 @@ public partial class Int64Tests long result = value.Wrap(length); - Assert.AreEqual(0L, result); + Assert.That(result, Is.EqualTo(0L)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnValue_WhenValueIsLessThanLength() { const long value = 5; @@ -87,10 +87,10 @@ public partial class Int64Tests long result = value.Wrap(length); - Assert.AreEqual(value, result); + Assert.That(result, Is.EqualTo(value)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsGreaterThanLength() { const long value = 15; @@ -98,7 +98,7 @@ public partial class Int64Tests long result = value.Wrap(length); - Assert.AreEqual(5L, result); + Assert.That(result, Is.EqualTo(5L)); } } } diff --git a/X10D.Tests/src/Math/Int64Tests.cs b/X10D.Tests/src/Math/Int64Tests.cs index cf6d345..de56cd9 100644 --- a/X10D.Tests/src/Math/Int64Tests.cs +++ b/X10D.Tests/src/Math/Int64Tests.cs @@ -1,36 +1,36 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Math; namespace X10D.Tests.Math; -[TestClass] +[TestFixture] public partial class Int64Tests { - [TestMethod] + [Test] public void DigitalRootShouldBeCorrect() { const long value = 238; - Assert.AreEqual(4, value.DigitalRoot()); - Assert.AreEqual(4, (-value).DigitalRoot()); + Assert.That(value.DigitalRoot(), Is.EqualTo(4)); + Assert.That((-value).DigitalRoot(), Is.EqualTo(4)); } - [TestMethod] + [Test] public void FactorialShouldBeCorrect() { - Assert.AreEqual(1L, 0L.Factorial()); - Assert.AreEqual(1L, 1L.Factorial()); - Assert.AreEqual(2L, 2L.Factorial()); - Assert.AreEqual(6L, 3L.Factorial()); - Assert.AreEqual(24L, 4L.Factorial()); - Assert.AreEqual(120L, 5L.Factorial()); - Assert.AreEqual(720L, 6L.Factorial()); - Assert.AreEqual(5040L, 7L.Factorial()); - Assert.AreEqual(40320L, 8L.Factorial()); - Assert.AreEqual(362880L, 9L.Factorial()); - Assert.AreEqual(3628800L, 10L.Factorial()); + Assert.That(0L.Factorial(), Is.EqualTo(1L)); + Assert.That(1L.Factorial(), Is.EqualTo(1L)); + Assert.That(2L.Factorial(), Is.EqualTo(2L)); + Assert.That(3L.Factorial(), Is.EqualTo(6L)); + Assert.That(4L.Factorial(), Is.EqualTo(24L)); + Assert.That(5L.Factorial(), Is.EqualTo(120L)); + Assert.That(6L.Factorial(), Is.EqualTo(720L)); + Assert.That(7L.Factorial(), Is.EqualTo(5040L)); + Assert.That(8L.Factorial(), Is.EqualTo(40320L)); + Assert.That(9L.Factorial(), Is.EqualTo(362880L)); + Assert.That(10L.Factorial(), Is.EqualTo(3628800L)); } - [TestMethod] + [Test] public void GreatestCommonFactor_ShouldBe1_ForPrimeNumbers() { const long first = 5L; @@ -38,10 +38,10 @@ public partial class Int64Tests long multiple = first.GreatestCommonFactor(second); - Assert.AreEqual(1L, multiple); + Assert.That(multiple, Is.EqualTo(1L)); } - [TestMethod] + [Test] public void GreatestCommonFactor_ShouldBe6_Given12And18() { const long first = 12L; @@ -49,30 +49,30 @@ public partial class Int64Tests long multiple = first.GreatestCommonFactor(second); - Assert.AreEqual(6L, multiple); + Assert.That(multiple, Is.EqualTo(6L)); } - [TestMethod] + [Test] public void IsEvenShouldBeCorrect() { const long one = 1; const long two = 2; - Assert.IsFalse(one.IsEven()); - Assert.IsTrue(two.IsEven()); + Assert.That(one.IsEven(), Is.False); + Assert.That(two.IsEven()); } - [TestMethod] + [Test] public void IsOddShouldBeCorrect() { const long one = 1; const long two = 2; - Assert.IsTrue(one.IsOdd()); - Assert.IsFalse(two.IsOdd()); + Assert.That(one.IsOdd()); + Assert.That(two.IsOdd(), Is.False); } - [TestMethod] + [Test] public void LowestCommonMultiple_ShouldReturnCorrectValue_WhenCalledWithValidInput() { const long value1 = 2; @@ -81,10 +81,10 @@ public partial class Int64Tests long result = value1.LowestCommonMultiple(value2); - Assert.AreEqual(expected, result); + Assert.That(result, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void LowestCommonMultiple_ShouldReturnZero_WhenCalledWithZero() { const long value1 = 0; @@ -93,10 +93,10 @@ public partial class Int64Tests long result = value1.LowestCommonMultiple(value2); - Assert.AreEqual(expected, result); + Assert.That(result, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void LowestCommonMultiple_ShouldReturnGreaterValue_WhenCalledWithOne() { const long value1 = 1; @@ -106,11 +106,11 @@ public partial class Int64Tests long result1 = value1.LowestCommonMultiple(value2); long result2 = value2.LowestCommonMultiple(value1); - Assert.AreEqual(expected, result1); - Assert.AreEqual(expected, result2); + Assert.That(result1, Is.EqualTo(expected)); + Assert.That(result2, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void LowestCommonMultiple_ShouldReturnOtherValue_WhenCalledWithSameValue() { const long value1 = 5; @@ -119,10 +119,10 @@ public partial class Int64Tests long result = value1.LowestCommonMultiple(value2); - Assert.AreEqual(expected, result); + Assert.That(result, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void LowestCommonMultiple_ShouldReturnCorrectValue_WhenCalledWithNegativeValues() { const long value1 = -2; @@ -131,48 +131,48 @@ public partial class Int64Tests long result = value1.LowestCommonMultiple(value2); - Assert.AreEqual(expected, result); + Assert.That(result, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void MultiplicativePersistence_ShouldReturn1_ForAnyDigitBeing0() { - Assert.AreEqual(1, 10L.MultiplicativePersistence()); - Assert.AreEqual(1, 201L.MultiplicativePersistence()); - Assert.AreEqual(1, 200L.MultiplicativePersistence()); - Assert.AreEqual(1, 20007L.MultiplicativePersistence()); + Assert.That(10L.MultiplicativePersistence(), Is.EqualTo(1)); + Assert.That(201L.MultiplicativePersistence(), Is.EqualTo(1)); + Assert.That(200L.MultiplicativePersistence(), Is.EqualTo(1)); + Assert.That(20007L.MultiplicativePersistence(), Is.EqualTo(1)); } - [TestMethod] + [Test] public void MultiplicativePersistence_ShouldBeCorrect_ForRecordHolders() { - Assert.AreEqual(0, 0L.MultiplicativePersistence()); - Assert.AreEqual(1, 10L.MultiplicativePersistence()); - Assert.AreEqual(2, 25L.MultiplicativePersistence()); - Assert.AreEqual(3, 39L.MultiplicativePersistence()); - Assert.AreEqual(4, 77L.MultiplicativePersistence()); - Assert.AreEqual(5, 679L.MultiplicativePersistence()); - Assert.AreEqual(6, 6788L.MultiplicativePersistence()); - Assert.AreEqual(7, 68889L.MultiplicativePersistence()); - Assert.AreEqual(8, 2677889L.MultiplicativePersistence()); - Assert.AreEqual(9, 26888999L.MultiplicativePersistence()); - Assert.AreEqual(10, 3778888999L.MultiplicativePersistence()); - Assert.AreEqual(11, 277777788888899L.MultiplicativePersistence()); + Assert.That(0L.MultiplicativePersistence(), Is.Zero); + Assert.That(10L.MultiplicativePersistence(), Is.EqualTo(1)); + Assert.That(25L.MultiplicativePersistence(), Is.EqualTo(2)); + Assert.That(39L.MultiplicativePersistence(), Is.EqualTo(3)); + Assert.That(77L.MultiplicativePersistence(), Is.EqualTo(4)); + Assert.That(679L.MultiplicativePersistence(), Is.EqualTo(5)); + Assert.That(6788L.MultiplicativePersistence(), Is.EqualTo(6)); + Assert.That(68889L.MultiplicativePersistence(), Is.EqualTo(7)); + Assert.That(2677889L.MultiplicativePersistence(), Is.EqualTo(8)); + Assert.That(26888999L.MultiplicativePersistence(), Is.EqualTo(9)); + Assert.That(3778888999L.MultiplicativePersistence(), Is.EqualTo(10)); + Assert.That(277777788888899L.MultiplicativePersistence(), Is.EqualTo(11)); } - [TestMethod] + [Test] public void NegativeFactorialShouldThrow() { - Assert.ThrowsException(() => (-1L).Factorial()); + Assert.Throws(() => (-1L).Factorial()); } - [TestMethod] + [Test] public void SignShouldBeCorrect() { const long one = 1; const long zero = 0; - Assert.AreEqual(one, one.Sign()); - Assert.AreEqual(zero, zero.Sign()); - Assert.AreEqual(-one, (-one).Sign()); + Assert.That(one.Sign(), Is.EqualTo(one)); + Assert.That(zero.Sign(), Is.EqualTo(zero)); + Assert.That((-one).Sign(), Is.EqualTo(-one)); } } diff --git a/X10D.Tests/src/Math/IsPrimeTests.cs b/X10D.Tests/src/Math/IsPrimeTests.cs index 11c336a..3af4499 100644 --- a/X10D.Tests/src/Math/IsPrimeTests.cs +++ b/X10D.Tests/src/Math/IsPrimeTests.cs @@ -1,140 +1,140 @@ using System.Numerics; using System.Reflection; using System.Text; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Math; namespace X10D.Tests.Math; -[TestClass] +[TestFixture] public class IsPrimeTests { private IReadOnlyList _primeNumbers = ArraySegment.Empty; - [TestInitialize] + [SetUp] public void Initialize() { _primeNumbers = LoadPrimes(); - Assert.AreEqual(1000, _primeNumbers.Count); + Assert.That(_primeNumbers.Count, Is.EqualTo(1000)); } - [TestMethod] + [Test] public void First1000Primes() { for (var index = 0; index < _primeNumbers.Count; index++) { int value = _primeNumbers[index]; - Assert.IsTrue(value.IsPrime()); - Assert.IsTrue(((long)value).IsPrime()); - Assert.IsTrue(((BigInteger)value).IsPrime()); + Assert.That(value.IsPrime()); + Assert.That(((long)value).IsPrime()); + Assert.That(((BigInteger)value).IsPrime()); if (value is >= byte.MinValue and <= byte.MaxValue) { - Assert.IsTrue(((byte)value).IsPrime()); + Assert.That(((byte)value).IsPrime()); } if (value is >= short.MinValue and <= short.MaxValue) { - Assert.IsTrue(((short)value).IsPrime()); + Assert.That(((short)value).IsPrime()); } if (value is >= byte.MinValue and <= byte.MaxValue) { - Assert.IsTrue(((byte)value).IsPrime()); + Assert.That(((byte)value).IsPrime()); } if (value is >= ushort.MinValue and <= ushort.MaxValue) { - Assert.IsTrue(((ushort)value).IsPrime()); + Assert.That(((ushort)value).IsPrime()); } if (value is >= sbyte.MinValue and <= sbyte.MaxValue) { - Assert.IsTrue(((sbyte)value).IsPrime()); + Assert.That(((sbyte)value).IsPrime()); } if (value >= 0) { - Assert.IsTrue(((uint)value).IsPrime()); - Assert.IsTrue(((ulong)value).IsPrime()); + Assert.That(((uint)value).IsPrime()); + Assert.That(((ulong)value).IsPrime()); } } } - [TestMethod] + [Test] public void Negatives() { for (var value = short.MinValue; value < 0; value++) { - Assert.IsFalse(value.IsPrime()); - Assert.IsFalse(((int)value).IsPrime()); - Assert.IsFalse(((long)value).IsPrime()); - Assert.IsFalse(((BigInteger)value).IsPrime()); + Assert.That(value.IsPrime(), Is.False); + Assert.That(((int)value).IsPrime(), Is.False); + Assert.That(((long)value).IsPrime(), Is.False); + Assert.That(((BigInteger)value).IsPrime(), Is.False); if (value is >= sbyte.MinValue and <= sbyte.MaxValue) { - Assert.IsFalse(((sbyte)value).IsPrime()); + Assert.That(((sbyte)value).IsPrime(), Is.False); } } } - [TestMethod] + [Test] public void LessThan2() { for (var value = 0; value < 2; value++) { - Assert.IsFalse(value.IsPrime()); - Assert.IsFalse(((byte)value).IsPrime()); - Assert.IsFalse(((short)value).IsPrime()); - Assert.IsFalse(((long)value).IsPrime()); - Assert.IsFalse(((BigInteger)value).IsPrime()); + Assert.That(value.IsPrime(), Is.False); + Assert.That(((byte)value).IsPrime(), Is.False); + Assert.That(((short)value).IsPrime(), Is.False); + Assert.That(((long)value).IsPrime(), Is.False); + Assert.That(((BigInteger)value).IsPrime(), Is.False); - Assert.IsFalse(((sbyte)value).IsPrime()); - Assert.IsFalse(((ushort)value).IsPrime()); - Assert.IsFalse(((uint)value).IsPrime()); - Assert.IsFalse(((ulong)value).IsPrime()); + Assert.That(((sbyte)value).IsPrime(), Is.False); + Assert.That(((ushort)value).IsPrime(), Is.False); + Assert.That(((uint)value).IsPrime(), Is.False); + Assert.That(((ulong)value).IsPrime(), Is.False); } } - [TestMethod] + [Test] public void ZeroTo7919() { for (var value = 0; value < 7920; value++) { bool expected = _primeNumbers.Contains(value); - Assert.AreEqual(expected, ((short)value).IsPrime()); - Assert.AreEqual(expected, value.IsPrime()); - Assert.AreEqual(expected, ((long)value).IsPrime()); - Assert.AreEqual(expected, ((BigInteger)value).IsPrime()); + Assert.That(((short)value).IsPrime(), Is.EqualTo(expected)); + Assert.That(value.IsPrime(), Is.EqualTo(expected)); + Assert.That(((long)value).IsPrime(), Is.EqualTo(expected)); + Assert.That(((BigInteger)value).IsPrime(), Is.EqualTo(expected)); - Assert.AreEqual(expected, ((ushort)value).IsPrime()); - Assert.AreEqual(expected, ((uint)value).IsPrime()); - Assert.AreEqual(expected, ((ulong)value).IsPrime()); + Assert.That(((ushort)value).IsPrime(), Is.EqualTo(expected)); + Assert.That(((uint)value).IsPrime(), Is.EqualTo(expected)); + Assert.That(((ulong)value).IsPrime(), Is.EqualTo(expected)); } } - [TestMethod] + [Test] public void ZeroToByteMaxValue() { for (byte value = 0; value < byte.MaxValue; value++) { bool expected = _primeNumbers.Contains(value); - Assert.AreEqual(expected, value.IsPrime()); - Assert.AreEqual(expected, ((short)value).IsPrime()); - Assert.AreEqual(expected, ((int)value).IsPrime()); - Assert.AreEqual(expected, ((long)value).IsPrime()); - Assert.AreEqual(expected, ((BigInteger)value).IsPrime()); + Assert.That(value.IsPrime(), Is.EqualTo(expected)); + Assert.That(((short)value).IsPrime(), Is.EqualTo(expected)); + Assert.That(((int)value).IsPrime(), Is.EqualTo(expected)); + Assert.That(((long)value).IsPrime(), Is.EqualTo(expected)); + Assert.That(((BigInteger)value).IsPrime(), Is.EqualTo(expected)); - Assert.AreEqual(expected, ((ushort)value).IsPrime()); - Assert.AreEqual(expected, ((uint)value).IsPrime()); - Assert.AreEqual(expected, ((ulong)value).IsPrime()); + Assert.That(((ushort)value).IsPrime(), Is.EqualTo(expected)); + Assert.That(((uint)value).IsPrime(), Is.EqualTo(expected)); + Assert.That(((ulong)value).IsPrime(), Is.EqualTo(expected)); if (value < sbyte.MaxValue) { - Assert.AreEqual(expected, ((sbyte)value).IsPrime()); + Assert.That(((sbyte)value).IsPrime(), Is.EqualTo(expected)); } } } diff --git a/X10D.Tests/src/Math/MathUtilityTests.cs b/X10D.Tests/src/Math/MathUtilityTests.cs index a40f18c..0989e44 100644 --- a/X10D.Tests/src/Math/MathUtilityTests.cs +++ b/X10D.Tests/src/Math/MathUtilityTests.cs @@ -1,4 +1,4 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; #if !NET6_0_OR_GREATER using X10D.Core; #endif @@ -6,40 +6,49 @@ using X10D.Math; namespace X10D.Tests.Math; -[TestClass] +[TestFixture] public class MathUtilityTests { - [TestMethod] + [Test] public void Bias_ReturnsCorrectResult_WhenBiasIsLessThanPointFive() { double doubleResult = MathUtility.Bias(0.5, 0.3); float floatResult = MathUtility.Bias(0.5f, 0.3f); - Assert.AreEqual(0.3, doubleResult, 1e-4); - Assert.AreEqual(0.3f, floatResult, 1e-4f); + Assert.Multiple(() => + { + Assert.That(doubleResult, Is.EqualTo(0.3).Within(1e-4)); + Assert.That(floatResult, Is.EqualTo(0.3f).Within(1e-4f)); + }); } - [TestMethod] + [Test] public void Bias_ReturnsCorrectResult_WhenBiasIsEqualToPointFive() { double doubleResult = MathUtility.Bias(0.5, 0.5); float floatResult = MathUtility.Bias(0.5f, 0.5f); - Assert.AreEqual(0.5, doubleResult, 1e-4); - Assert.AreEqual(0.5f, floatResult, 1e-4f); + Assert.Multiple(() => + { + Assert.That(doubleResult, Is.EqualTo(0.5).Within(1e-4)); + Assert.That(floatResult, Is.EqualTo(0.5f).Within(1e-4f)); + }); } - [TestMethod] + [Test] public void Bias_ReturnsCorrectResult_WhenBiasIsGreaterThanPointFive() { double doubleResult = MathUtility.Bias(0.5, 0.8); float floatResult = MathUtility.Bias(0.5f, 0.8f); - Assert.AreEqual(0.8, doubleResult, 1e-4); - Assert.AreEqual(0.8f, floatResult, 1e-4f); + Assert.Multiple(() => + { + Assert.That(doubleResult, Is.EqualTo(0.8).Within(1e-4)); + Assert.That(floatResult, Is.EqualTo(0.8f).Within(1e-4f)); + }); } - [TestMethod] + [Test] public void ExponentialDecay_ShouldReturnCorrectValue_GivenDouble() { const double value = 100.0; @@ -49,10 +58,10 @@ public class MathUtilityTests const double expected = 95.122942; double actual = MathUtility.ExponentialDecay(value, alpha, decay); - Assert.AreEqual(expected, actual, 1e-6); + Assert.That(actual, Is.EqualTo(expected).Within(1e-6)); } - [TestMethod] + [Test] public void ExponentialDecay_ShouldReturnCorrectValue_GivenSingle() { const float value = 100.0f; @@ -62,50 +71,62 @@ public class MathUtilityTests const float expected = 95.12295f; float actual = MathUtility.ExponentialDecay(value, alpha, decay); - Assert.AreEqual(expected, actual, 1e-6f); + Assert.That(actual, Is.EqualTo(expected).Within(1e-6f)); } - [TestMethod] + [Test] public void GammaToLinear_ShouldReturnQuarter_GivenQuarterAndGamma1() { double doubleResult = MathUtility.GammaToLinear(0.25, 1.0); float floatResult = MathUtility.GammaToLinear(0.25f, 1.0f); - Assert.AreEqual(0.25, doubleResult, 1e-6); - Assert.AreEqual(0.25f, floatResult, 1e-6f); + Assert.Multiple(() => + { + Assert.That(doubleResult, Is.EqualTo(0.25).Within(1e-6)); + Assert.That(floatResult, Is.EqualTo(0.25f).Within(1e-6f)); + }); } - [TestMethod] + [Test] public void GammaToLinear_ShouldReturn1_Given1AndDefaultGamma() { double doubleResult = MathUtility.GammaToLinear(1.0); float floatResult = MathUtility.GammaToLinear(1.0f); - Assert.AreEqual(1.0, doubleResult); - Assert.AreEqual(1.0f, floatResult); + Assert.Multiple(() => + { + Assert.That(doubleResult, Is.EqualTo(1.0)); + Assert.That(floatResult, Is.EqualTo(1.0f)); + }); } - [TestMethod] + [Test] public void InverseLerp_ShouldReturn0_5_Given0_5_0_1() { double doubleResult = MathUtility.InverseLerp(0.5, 0.0, 1.0); float floatResult = MathUtility.InverseLerp(0.5f, 0f, 1f); - Assert.AreEqual(0.5, doubleResult, 1e-6); - Assert.AreEqual(0.5f, floatResult, 1e-6f); + Assert.Multiple(() => + { + Assert.That(doubleResult, Is.EqualTo(0.5).Within(1e-6)); + Assert.That(floatResult, Is.EqualTo(0.5f).Within(1e-6f)); + }); } - [TestMethod] + [Test] public void InverseLerp_ShouldReturn0_5_Given5_0_10() { double doubleResult = MathUtility.InverseLerp(5.0, 0.0, 10.0); float floatResult = MathUtility.InverseLerp(5f, 0f, 10f); - Assert.AreEqual(0.5, doubleResult, 1e-6); - Assert.AreEqual(0.5f, floatResult, 1e-6f); + Assert.Multiple(() => + { + Assert.That(doubleResult, Is.EqualTo(0.5).Within(1e-6)); + Assert.That(floatResult, Is.EqualTo(0.5f).Within(1e-6f)); + }); } - [TestMethod] + [Test] public void InverseLerp_ShouldReturn0_GivenTwoEqualValues() { var random = new Random(); @@ -118,52 +139,70 @@ public class MathUtilityTests double doubleResult = MathUtility.InverseLerp(doubleA, doubleB, doubleB); float floatResult = MathUtility.InverseLerp(floatA, floatB, floatB); - Assert.AreEqual(0.0, doubleResult, 1e-6); - Assert.AreEqual(0.0f, floatResult, 1e-6f); + Assert.Multiple(() => + { + Assert.That(doubleResult, Is.EqualTo(0.0).Within(1e-6)); + Assert.That(floatResult, Is.EqualTo(0.0f).Within(1e-6f)); + }); } - [TestMethod] + [Test] public void Lerp_ShouldReturnHigher_GivenAlpha1() { - Assert.AreEqual(20.0f, MathUtility.Lerp(10.0f, 20.0f, 1.0f)); - Assert.AreEqual(20.0, MathUtility.Lerp(10.0, 20.0, 1.0)); + Assert.Multiple(() => + { + Assert.That(MathUtility.Lerp(10.0f, 20.0f, 1.0f), Is.EqualTo(20.0f)); + Assert.That(MathUtility.Lerp(10.0, 20.0, 1.0), Is.EqualTo(20.0)); + }); } - [TestMethod] + [Test] public void Lerp_ShouldReturnLower_GivenAlpha0() { - Assert.AreEqual(10.0f, MathUtility.Lerp(10.0f, 20.0f, 0.0f)); - Assert.AreEqual(10.0, MathUtility.Lerp(10.0, 20.0, 0.0)); + Assert.Multiple(() => + { + Assert.That(MathUtility.Lerp(10.0f, 20.0f, 0.0f), Is.EqualTo(10.0f)); + Assert.That(MathUtility.Lerp(10.0, 20.0, 0.0), Is.EqualTo(10.0)); + }); } - [TestMethod] + [Test] public void Lerp_ShouldReturnMidPoint_GivenAlphaPoint5() { - Assert.AreEqual(15.0f, MathUtility.Lerp(10.0f, 20.0f, 0.5f)); - Assert.AreEqual(15.0, MathUtility.Lerp(10.0, 20.0, 0.5)); + Assert.Multiple(() => + { + Assert.That(MathUtility.Lerp(10.0f, 20.0f, 0.5f), Is.EqualTo(15.0f)); + Assert.That(MathUtility.Lerp(10.0, 20.0, 0.5), Is.EqualTo(15.0)); + }); } - [TestMethod] + [Test] public void LinearToGamma_ShouldReturnQuarter_GivenQuarterAndGamma1() { double doubleResult = MathUtility.LinearToGamma(0.25, 1.0); float floatResult = MathUtility.LinearToGamma(0.25f, 1.0f); - Assert.AreEqual(0.25, doubleResult); - Assert.AreEqual(0.25f, floatResult); + Assert.Multiple(() => + { + Assert.That(doubleResult, Is.EqualTo(0.25)); + Assert.That(floatResult, Is.EqualTo(0.25f)); + }); } - [TestMethod] + [Test] public void LinearToGamma_ShouldReturn1_Given1AndDefaultGamma() { double doubleResult = MathUtility.LinearToGamma(1.0); float floatResult = MathUtility.LinearToGamma(1.0f); - Assert.AreEqual(1.0, doubleResult); - Assert.AreEqual(1.0f, floatResult); + Assert.Multiple(() => + { + Assert.That(doubleResult, Is.EqualTo(1.0)); + Assert.That(floatResult, Is.EqualTo(1.0f)); + }); } - [TestMethod] + [Test] public void Pulse_ShouldReturn1_GivenDoubleValueWithinBounds() { const double value = 0.5; @@ -172,10 +211,10 @@ public class MathUtilityTests double result = MathUtility.Pulse(value, lower, upper); - Assert.AreEqual(1.0, result, 1e-6); + Assert.That(result, Is.EqualTo(1.0).Within(1e-6)); } - [TestMethod] + [Test] public void Pulse_ShouldReturn0_GivenDoubleValueLessThanLowerBound() { const double value = -1.0; @@ -184,10 +223,10 @@ public class MathUtilityTests double result = MathUtility.Pulse(value, lower, upper); - Assert.AreEqual(0.0, result, 1e-6); + Assert.That(result, Is.EqualTo(0.0).Within(1e-6)); } - [TestMethod] + [Test] public void Pulse_ShouldReturn0_GivenDoubleValueGreaterThanUpperBound() { const double value = 2.0; @@ -196,10 +235,10 @@ public class MathUtilityTests double result = MathUtility.Pulse(value, lower, upper); - Assert.AreEqual(0.0, result, 1e-6); + Assert.That(result, Is.EqualTo(0.0).Within(1e-6)); } - [TestMethod] + [Test] public void Pulse_ShouldReturn1_GivenSingleValueWithinBounds() { const float value = 0.5f; @@ -208,10 +247,10 @@ public class MathUtilityTests float result = MathUtility.Pulse(value, lower, upper); - Assert.AreEqual(1.0f, result, 1e-6f); + Assert.That(result, Is.EqualTo(1.0f).Within(1e-6f)); } - [TestMethod] + [Test] public void Pulse_ShouldReturn0_GivenSingleValueLessThanLowerBound() { const float value = -1.0f; @@ -220,10 +259,10 @@ public class MathUtilityTests float result = MathUtility.Pulse(value, lower, upper); - Assert.AreEqual(0.0f, result, 1e-6f); + Assert.That(result, Is.EqualTo(0.0f).Within(1e-6f)); } - [TestMethod] + [Test] public void Pulse_ShouldReturn0_GivenSingleValueGreaterThanUpperBound() { const float value = 2.0f; @@ -232,10 +271,10 @@ public class MathUtilityTests float result = MathUtility.Pulse(value, lower, upper); - Assert.AreEqual(0.0f, result, 1e-6f); + Assert.That(result, Is.EqualTo(0.0f).Within(1e-6f)); } - [TestMethod] + [Test] public void Sawtooth_ShouldReturn0Point5_Given0Point5AsDouble() { const double value = 0.5; @@ -243,10 +282,10 @@ public class MathUtilityTests const double expected = 0.5; double actual = MathUtility.Sawtooth(value); - Assert.AreEqual(expected, actual, 1e-6); + Assert.That(actual, Is.EqualTo(expected).Within(1e-6)); } - [TestMethod] + [Test] public void Sawtooth_ShouldReturn0Point5_Given0Point5AsSingle() { const float value = 0.5f; @@ -254,10 +293,10 @@ public class MathUtilityTests const float expected = 0.5f; float actual = MathUtility.Sawtooth(value); - Assert.AreEqual(expected, actual, 1e-6f); + Assert.That(actual, Is.EqualTo(expected).Within(1e-6f)); } - [TestMethod] + [Test] public void Sawtooth_ShouldReturn0Point5_Given1Point5AsDouble() { const double value = 1.5; @@ -265,10 +304,10 @@ public class MathUtilityTests const double expected = 0.5; double actual = MathUtility.Sawtooth(value); - Assert.AreEqual(expected, actual, 1e-6); + Assert.That(actual, Is.EqualTo(expected).Within(1e-6)); } - [TestMethod] + [Test] public void Sawtooth_ShouldReturn0Point5_Given1Point5AsSingle() { const float value = 1.5f; @@ -276,10 +315,10 @@ public class MathUtilityTests const float expected = 0.5f; float actual = MathUtility.Sawtooth(value); - Assert.AreEqual(expected, actual, 1e-6f); + Assert.That(actual, Is.EqualTo(expected).Within(1e-6f)); } - [TestMethod] + [Test] public void Sawtooth_ShouldReturn0Point5_GivenNegative1Point5AsDouble() { const double value = -1.5; @@ -287,10 +326,10 @@ public class MathUtilityTests const double expected = 0.5; double actual = MathUtility.Sawtooth(value); - Assert.AreEqual(expected, actual, 1e-6); + Assert.That(actual, Is.EqualTo(expected).Within(1e-6)); } - [TestMethod] + [Test] public void Sawtooth_ShouldReturn0Point5_GivenNegative1Point5AsSingle() { const float value = -1.5f; @@ -298,24 +337,24 @@ public class MathUtilityTests const float expected = 0.5f; float actual = MathUtility.Sawtooth(value); - Assert.AreEqual(expected, actual, 1e-6f); + Assert.That(actual, Is.EqualTo(expected).Within(1e-6f)); } - [TestMethod] + [Test] public void ScaleRangeDouble_ShouldScaleRange_GivenItsValues() { double result = MathUtility.ScaleRange(0.5, 0.0, 1.0, 5.0, 10.0); - Assert.AreEqual(7.5, result); + Assert.That(result, Is.EqualTo(7.5)); } - [TestMethod] + [Test] public void ScaleRangeSingle_ShouldScaleRange_GivenItsValues() { float result = MathUtility.ScaleRange(0.5f, 0.0f, 1.0f, 5.0f, 10.0f); - Assert.AreEqual(7.5f, result); + Assert.That(result, Is.EqualTo(7.5f)); } - [TestMethod] + [Test] public void Sigmoid_ReturnsExpectedValue_UsingDouble() { const double input = 0.5f; @@ -323,10 +362,10 @@ public class MathUtilityTests double actual = MathUtility.Sigmoid(input); - Assert.AreEqual(expected, actual, 1e-6); + Assert.That(actual, Is.EqualTo(expected).Within(1e-6)); } - [TestMethod] + [Test] public void Sigmoid_ReturnsExpectedValue_UsingSingle() { const float input = 0.5f; @@ -334,10 +373,10 @@ public class MathUtilityTests float actual = MathUtility.Sigmoid(input); - Assert.AreEqual(expected, actual, 1e-6f); + Assert.That(actual, Is.EqualTo(expected).Within(1e-6f)); } - [TestMethod] + [Test] public void Sigmoid_ReturnsZeroWhenInputIsNegativeInfinity_UsingDouble() { const double input = double.NegativeInfinity; @@ -345,10 +384,10 @@ public class MathUtilityTests double actual = MathUtility.Sigmoid(input); - Assert.AreEqual(expected, actual, 1e-6); + Assert.That(actual, Is.EqualTo(expected).Within(1e-6)); } - [TestMethod] + [Test] public void Sigmoid_ReturnsZeroWhenInputIsNegativeInfinity_UsingSingle() { const float input = float.NegativeInfinity; @@ -356,10 +395,10 @@ public class MathUtilityTests float actual = MathUtility.Sigmoid(input); - Assert.AreEqual(expected, actual, 1e-6f); + Assert.That(actual, Is.EqualTo(expected).Within(1e-6f)); } - [TestMethod] + [Test] public void Sigmoid_ReturnsOneWhenInputIsPositiveInfinity_UsingDouble() { const double input = double.PositiveInfinity; @@ -367,10 +406,10 @@ public class MathUtilityTests double actual = MathUtility.Sigmoid(input); - Assert.AreEqual(expected, actual, 1e-6); + Assert.That(actual, Is.EqualTo(expected).Within(1e-6)); } - [TestMethod] + [Test] public void Sigmoid_ReturnsOneWhenInputIsPositiveInfinity_UsingSingle() { const float input = float.PositiveInfinity; @@ -378,10 +417,10 @@ public class MathUtilityTests float actual = MathUtility.Sigmoid(input); - Assert.AreEqual(expected, actual, 1e-6f); + Assert.That(actual, Is.EqualTo(expected).Within(1e-6f)); } - [TestMethod] + [Test] public void Sigmoid_ReturnsZeroPointFiveWhenInputIsZero_UsingDouble() { const double input = 0f; @@ -389,10 +428,10 @@ public class MathUtilityTests double actual = MathUtility.Sigmoid(input); - Assert.AreEqual(expected, actual, 1e-6); + Assert.That(actual, Is.EqualTo(expected).Within(1e-6)); } - [TestMethod] + [Test] public void Sigmoid_ReturnsZeroPointFiveWhenInputIsZero_UsingSingle() { const float input = 0f; @@ -400,28 +439,36 @@ public class MathUtilityTests float actual = MathUtility.Sigmoid(input); - Assert.AreEqual(expected, actual, 1e-6f); + Assert.That(actual, Is.EqualTo(expected).Within(1e-6f)); } - - [TestMethod] + [Test] public void SmoothStep_ShouldReturnHigher_GivenAlpha1() { - Assert.AreEqual(20.0f, MathUtility.SmoothStep(10.0f, 20.0f, 1.0f)); - Assert.AreEqual(20.0, MathUtility.SmoothStep(10.0, 20.0, 1.0)); + Assert.Multiple(() => + { + Assert.That(MathUtility.SmoothStep(10.0f, 20.0f, 1.0f), Is.EqualTo(20.0f)); + Assert.That(MathUtility.SmoothStep(10.0, 20.0, 1.0), Is.EqualTo(20.0)); + }); } - [TestMethod] + [Test] public void SmoothStep_ShouldReturnLower_GivenAlpha0() { - Assert.AreEqual(10.0f, MathUtility.SmoothStep(10.0f, 20.0f, 0.0f)); - Assert.AreEqual(10.0, MathUtility.SmoothStep(10.0, 20.0, 0.0)); + Assert.Multiple(() => + { + Assert.That(MathUtility.SmoothStep(10.0f, 20.0f, 0.0f), Is.EqualTo(10.0f)); + Assert.That(MathUtility.SmoothStep(10.0, 20.0, 0.0), Is.EqualTo(10.0)); + }); } - [TestMethod] + [Test] public void SmoothStep_ShouldReturnMidPoint_GivenAlphaPoint5() { - Assert.AreEqual(15.0f, MathUtility.SmoothStep(10.0f, 20.0f, 0.5f)); - Assert.AreEqual(15.0, MathUtility.SmoothStep(10.0, 20.0, 0.5)); + Assert.Multiple(() => + { + Assert.That(MathUtility.SmoothStep(10.0f, 20.0f, 0.5f), Is.EqualTo(15.0f)); + Assert.That(MathUtility.SmoothStep(10.0, 20.0, 0.5), Is.EqualTo(15.0)); + }); } } diff --git a/X10D.Tests/src/Math/SByteTests.Wrap.cs b/X10D.Tests/src/Math/SByteTests.Wrap.cs index 64b473a..eaecb3c 100644 --- a/X10D.Tests/src/Math/SByteTests.Wrap.cs +++ b/X10D.Tests/src/Math/SByteTests.Wrap.cs @@ -1,14 +1,14 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Math; namespace X10D.Tests.Math; public partial class SByteTests { - [TestClass] + [TestFixture] public class WrapTests { - [TestMethod] + [Test] public void Wrap_ShouldReturnLow_WhenValueIsEqualToLow() { const sbyte value = 10; @@ -17,10 +17,10 @@ public partial class SByteTests sbyte result = value.Wrap(low, high); - Assert.AreEqual(low, result); + Assert.That(result, Is.EqualTo(low)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnHigh_WhenValueIsEqualToHigh() { const sbyte value = 20; @@ -29,10 +29,10 @@ public partial class SByteTests sbyte result = value.Wrap(low, high); - Assert.AreEqual(low, result); + Assert.That(result, Is.EqualTo(low)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsGreaterThanHigh() { const sbyte value = 30; @@ -41,10 +41,10 @@ public partial class SByteTests sbyte result = value.Wrap(low, high); - Assert.AreEqual(low, result); + Assert.That(result, Is.EqualTo(low)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsLessThanLow() { const sbyte value = 5; @@ -53,10 +53,10 @@ public partial class SByteTests sbyte result = value.Wrap(low, high); - Assert.AreEqual(15, result); + Assert.That(result, Is.EqualTo(15)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsInBetweenLowAndHigh() { const sbyte value = 15; @@ -65,10 +65,10 @@ public partial class SByteTests sbyte result = value.Wrap(low, high); - Assert.AreEqual(value, result); + Assert.That(result, Is.EqualTo(value)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnZero_WhenValueIsEqualToLength() { const sbyte value = 10; @@ -76,10 +76,10 @@ public partial class SByteTests sbyte result = value.Wrap(length); - Assert.AreEqual(0, result); + Assert.That(result, Is.Zero); } - [TestMethod] + [Test] public void Wrap_ShouldReturnValue_WhenValueIsLessThanLength() { const sbyte value = 5; @@ -87,10 +87,10 @@ public partial class SByteTests sbyte result = value.Wrap(length); - Assert.AreEqual(value, result); + Assert.That(result, Is.EqualTo(value)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsGreaterThanLength() { const sbyte value = 15; @@ -98,7 +98,7 @@ public partial class SByteTests sbyte result = value.Wrap(length); - Assert.AreEqual(5, result); + Assert.That(result, Is.EqualTo(5)); } } } diff --git a/X10D.Tests/src/Math/SByteTests.cs b/X10D.Tests/src/Math/SByteTests.cs index 3874515..703b1af 100644 --- a/X10D.Tests/src/Math/SByteTests.cs +++ b/X10D.Tests/src/Math/SByteTests.cs @@ -1,37 +1,37 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Math; namespace X10D.Tests.Math; -[TestClass] +[TestFixture] [CLSCompliant(false)] public partial class SByteTests { - [TestMethod] + [Test] public void DigitalRootShouldBeCorrect() { const sbyte value = 127; // sbyte.MaxValue. can't use 238 like the other tests - Assert.AreEqual(1, value.DigitalRoot()); - Assert.AreEqual(1, (-value).DigitalRoot()); + Assert.That(value.DigitalRoot(), Is.EqualTo(1)); + Assert.That((-value).DigitalRoot(), Is.EqualTo(1)); } - [TestMethod] + [Test] public void FactorialShouldBeCorrect() { - Assert.AreEqual(1L, ((sbyte)0).Factorial()); - Assert.AreEqual(1L, ((sbyte)1).Factorial()); - Assert.AreEqual(2L, ((sbyte)2).Factorial()); - Assert.AreEqual(6L, ((sbyte)3).Factorial()); - Assert.AreEqual(24L, ((sbyte)4).Factorial()); - Assert.AreEqual(120L, ((sbyte)5).Factorial()); - Assert.AreEqual(720L, ((sbyte)6).Factorial()); - Assert.AreEqual(5040L, ((sbyte)7).Factorial()); - Assert.AreEqual(40320L, ((sbyte)8).Factorial()); - Assert.AreEqual(362880L, ((sbyte)9).Factorial()); - Assert.AreEqual(3628800L, ((sbyte)10).Factorial()); + Assert.That(((sbyte)0).Factorial(), Is.EqualTo(1L)); + Assert.That(((sbyte)1).Factorial(), Is.EqualTo(1L)); + Assert.That(((sbyte)2).Factorial(), Is.EqualTo(2L)); + Assert.That(((sbyte)3).Factorial(), Is.EqualTo(6L)); + Assert.That(((sbyte)4).Factorial(), Is.EqualTo(24L)); + Assert.That(((sbyte)5).Factorial(), Is.EqualTo(120L)); + Assert.That(((sbyte)6).Factorial(), Is.EqualTo(720L)); + Assert.That(((sbyte)7).Factorial(), Is.EqualTo(5040L)); + Assert.That(((sbyte)8).Factorial(), Is.EqualTo(40320L)); + Assert.That(((sbyte)9).Factorial(), Is.EqualTo(362880L)); + Assert.That(((sbyte)10).Factorial(), Is.EqualTo(3628800L)); } - [TestMethod] + [Test] public void GreatestCommonFactor_ShouldBe1_ForPrimeNumbers() { const sbyte first = 5; @@ -39,10 +39,10 @@ public partial class SByteTests sbyte multiple = first.GreatestCommonFactor(second); - Assert.AreEqual(1, multiple); + Assert.That(multiple, Is.EqualTo(1)); } - [TestMethod] + [Test] public void GreatestCommonFactor_ShouldBe6_Given12And18() { const sbyte first = 12; @@ -50,30 +50,30 @@ public partial class SByteTests sbyte multiple = first.GreatestCommonFactor(second); - Assert.AreEqual(6, multiple); + Assert.That(multiple, Is.EqualTo(6)); } - [TestMethod] + [Test] public void IsEvenShouldBeCorrect() { const sbyte one = 1; const sbyte two = 2; - Assert.IsFalse(one.IsEven()); - Assert.IsTrue(two.IsEven()); + Assert.That(one.IsEven(), Is.False); + Assert.That(two.IsEven()); } - [TestMethod] + [Test] public void IsOddShouldBeCorrect() { const sbyte one = 1; const sbyte two = 2; - Assert.IsTrue(one.IsOdd()); - Assert.IsFalse(two.IsOdd()); + Assert.That(one.IsOdd()); + Assert.That(two.IsOdd(), Is.False); } - [TestMethod] + [Test] public void LowestCommonMultiple_ShouldReturnCorrectValue_WhenCalledWithValidInput() { const sbyte value1 = 2; @@ -82,10 +82,10 @@ public partial class SByteTests sbyte result = value1.LowestCommonMultiple(value2); - Assert.AreEqual(expected, result); + Assert.That(result, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void LowestCommonMultiple_ShouldReturnZero_WhenCalledWithZero() { const sbyte value1 = 0; @@ -94,10 +94,10 @@ public partial class SByteTests sbyte result = value1.LowestCommonMultiple(value2); - Assert.AreEqual(expected, result); + Assert.That(result, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void LowestCommonMultiple_ShouldReturnGreaterValue_WhenCalledWithOne() { const sbyte value1 = 1; @@ -106,10 +106,10 @@ public partial class SByteTests sbyte result = value1.LowestCommonMultiple(value2); - Assert.AreEqual(expected, result); + Assert.That(result, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void LowestCommonMultiple_ShouldReturnOtherValue_WhenCalledWithSameValue() { const sbyte value1 = 5; @@ -119,11 +119,11 @@ public partial class SByteTests sbyte result1 = value1.LowestCommonMultiple(value2); sbyte result2 = value2.LowestCommonMultiple(value1); - Assert.AreEqual(expected, result1); - Assert.AreEqual(expected, result2); + Assert.That(result1, Is.EqualTo(expected)); + Assert.That(result2, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void LowestCommonMultiple_ShouldReturnCorrectValue_WhenCalledWithNegativeValues() { const sbyte value1 = -2; @@ -132,41 +132,41 @@ public partial class SByteTests sbyte result = value1.LowestCommonMultiple(value2); - Assert.AreEqual(expected, result); + Assert.That(result, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void MultiplicativePersistence_ShouldReturn1_ForAnyDigitBeing0() { - Assert.AreEqual(1, ((sbyte)10).MultiplicativePersistence()); - Assert.AreEqual(1, ((sbyte)20).MultiplicativePersistence()); - Assert.AreEqual(1, ((sbyte)101).MultiplicativePersistence()); - Assert.AreEqual(1, ((sbyte)120).MultiplicativePersistence()); + Assert.That(((sbyte)10).MultiplicativePersistence(), Is.EqualTo(1)); + Assert.That(((sbyte)20).MultiplicativePersistence(), Is.EqualTo(1)); + Assert.That(((sbyte)101).MultiplicativePersistence(), Is.EqualTo(1)); + Assert.That(((sbyte)120).MultiplicativePersistence(), Is.EqualTo(1)); } - [TestMethod] + [Test] public void MultiplicativePersistence_ShouldBeCorrect_ForRecordHolders() { - Assert.AreEqual(0, ((sbyte)0).MultiplicativePersistence()); - Assert.AreEqual(1, ((sbyte)10).MultiplicativePersistence()); - Assert.AreEqual(2, ((sbyte)25).MultiplicativePersistence()); - Assert.AreEqual(3, ((sbyte)39).MultiplicativePersistence()); - Assert.AreEqual(4, ((sbyte)77).MultiplicativePersistence()); + Assert.That(((sbyte)0).MultiplicativePersistence(), Is.Zero); + Assert.That(((sbyte)10).MultiplicativePersistence(), Is.EqualTo(1)); + Assert.That(((sbyte)25).MultiplicativePersistence(), Is.EqualTo(2)); + Assert.That(((sbyte)39).MultiplicativePersistence(), Is.EqualTo(3)); + Assert.That(((sbyte)77).MultiplicativePersistence(), Is.EqualTo(4)); } - [TestMethod] + [Test] public void NegativeFactorialShouldThrow() { - Assert.ThrowsException(() => ((sbyte)-1).Factorial()); + Assert.Throws(() => ((sbyte)-1).Factorial()); } - [TestMethod] + [Test] public void SignShouldBeCorrect() { const sbyte one = 1; const sbyte zero = 0; - Assert.AreEqual(one, one.Sign()); - Assert.AreEqual(zero, zero.Sign()); - Assert.AreEqual(-one, (-one).Sign()); + Assert.That(one.Sign(), Is.EqualTo(one)); + Assert.That(zero.Sign(), Is.EqualTo(zero)); + Assert.That((-one).Sign(), Is.EqualTo(-one)); } } diff --git a/X10D.Tests/src/Math/SingleTests.Wrap.cs b/X10D.Tests/src/Math/SingleTests.Wrap.cs index 5d75ccb..9430e9a 100644 --- a/X10D.Tests/src/Math/SingleTests.Wrap.cs +++ b/X10D.Tests/src/Math/SingleTests.Wrap.cs @@ -1,14 +1,14 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Math; namespace X10D.Tests.Math; public partial class SingleTests { - [TestClass] + [TestFixture] public class WrapTests { - [TestMethod] + [Test] public void Wrap_ShouldReturnLow_WhenValueIsEqualToLow() { const float value = 10; @@ -17,10 +17,10 @@ public partial class SingleTests float result = value.Wrap(low, high); - Assert.AreEqual(low, result); + Assert.That(result, Is.EqualTo(low)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnHigh_WhenValueIsEqualToHigh() { const float value = 20; @@ -29,10 +29,10 @@ public partial class SingleTests float result = value.Wrap(low, high); - Assert.AreEqual(low, result); + Assert.That(result, Is.EqualTo(low)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsGreaterThanHigh() { const float value = 30; @@ -41,10 +41,10 @@ public partial class SingleTests float result = value.Wrap(low, high); - Assert.AreEqual(low, result); + Assert.That(result, Is.EqualTo(low)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsLessThanLow() { const float value = 5; @@ -53,10 +53,10 @@ public partial class SingleTests float result = value.Wrap(low, high); - Assert.AreEqual(15.0f, result); + Assert.That(result, Is.EqualTo(15.0f)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsInBetweenLowAndHigh() { const float value = 15; @@ -65,10 +65,10 @@ public partial class SingleTests float result = value.Wrap(low, high); - Assert.AreEqual(value, result); + Assert.That(result, Is.EqualTo(value)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnZero_WhenValueIsEqualToLength() { const float value = 10; @@ -76,10 +76,10 @@ public partial class SingleTests float result = value.Wrap(length); - Assert.AreEqual(0.0f, result); + Assert.That(result, Is.EqualTo(0.0f)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnValue_WhenValueIsLessThanLength() { const float value = 5; @@ -87,10 +87,10 @@ public partial class SingleTests float result = value.Wrap(length); - Assert.AreEqual(value, result); + Assert.That(result, Is.EqualTo(value)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsGreaterThanLength() { const float value = 15; @@ -98,7 +98,7 @@ public partial class SingleTests float result = value.Wrap(length); - Assert.AreEqual(5.0f, result); + Assert.That(result, Is.EqualTo(5.0f)); } } } diff --git a/X10D.Tests/src/Math/SingleTests.cs b/X10D.Tests/src/Math/SingleTests.cs index a6ecddc..f13ec65 100644 --- a/X10D.Tests/src/Math/SingleTests.cs +++ b/X10D.Tests/src/Math/SingleTests.cs @@ -1,260 +1,290 @@ using System.Numerics; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Math; namespace X10D.Tests.Math; -[TestClass] +[TestFixture] public partial class SingleTests { - [TestMethod] + [Test] public void DegreesToRadians_ShouldBeCorrect() { - Assert.AreEqual(MathF.PI, 180.0f.DegreesToRadians(), 1e-6f); - Assert.AreEqual(MathF.PI * 1.5f, 270.0f.DegreesToRadians(), 1e-6f); - Assert.AreEqual(0.0f, 0.0f.DegreesToRadians(), 1e-6f); - Assert.AreEqual(0.017453292f, 1.0f.DegreesToRadians(), 1e-6f); - Assert.AreEqual(0.10471976f, 6.0f.DegreesToRadians(), 1e-6f); - Assert.AreEqual(0.20943952f, 12.0f.DegreesToRadians(), 1e-6f); + Assert.That(180.0f.DegreesToRadians(), Is.EqualTo(MathF.PI).Within(1e-6f)); + Assert.That(270.0f.DegreesToRadians(), Is.EqualTo(MathF.PI * 1.5f).Within(1e-6f)); + Assert.That(0.0f.DegreesToRadians(), Is.EqualTo(0.0f).Within(1e-6f)); + Assert.That(1.0f.DegreesToRadians(), Is.EqualTo(0.017453292f).Within(1e-6f)); + Assert.That(6.0f.DegreesToRadians(), Is.EqualTo(0.10471976f).Within(1e-6f)); + Assert.That(12.0f.DegreesToRadians(), Is.EqualTo(0.20943952f).Within(1e-6f)); } - [TestMethod] + [Test] public void RadiansToDegrees_ShouldBeCorrect() { - Assert.AreEqual(180.0f, MathF.PI.RadiansToDegrees(), 1e-6f); - Assert.AreEqual(270.0f, (MathF.PI * 1.5f).RadiansToDegrees(), 1e-6f); - Assert.AreEqual(0.0, 0.0f.RadiansToDegrees(), 1e-6f); - Assert.AreEqual(0.99999994f, 0.017453292f.RadiansToDegrees(), 1e-6f); // rounding errors are fun - Assert.AreEqual(6.0f, 0.10471976f.RadiansToDegrees(), 1e-6f); - Assert.AreEqual(12.0f, 0.20943952f.RadiansToDegrees(), 1e-6f); + Assert.That(MathF.PI.RadiansToDegrees(), Is.EqualTo(180.0f).Within(1e-6f)); + Assert.That((MathF.PI * 1.5f).RadiansToDegrees(), Is.EqualTo(270.0f).Within(1e-6f)); + Assert.That(0.0f.RadiansToDegrees(), Is.EqualTo(0.0).Within(1e-6f)); + Assert.That(0.017453292f.RadiansToDegrees(), Is.EqualTo(0.99999994f).Within(1e-6f)); // rounding errors are fun + Assert.That(0.10471976f.RadiansToDegrees(), Is.EqualTo(6.0f).Within(1e-6f)); + Assert.That(0.20943952f.RadiansToDegrees(), Is.EqualTo(12.0f).Within(1e-6f)); } - [TestMethod] + [Test] public void ComplexSqrt_ShouldBeCorrect_GivenReal() { - Assert.AreEqual(0.0f, 0.0f.ComplexSqrt()); - Assert.AreEqual(1.4142135f, 2.0f.ComplexSqrt()); - Assert.AreEqual(3.0f, 9.0f.ComplexSqrt()); - Assert.AreEqual(4.0f, 16.0f.ComplexSqrt()); - Assert.AreEqual(100.0f, 10000.0f.ComplexSqrt()); + Assert.That(0.0f.ComplexSqrt(), Is.EqualTo((Complex)0.0f)); + Assert.That(2.0f.ComplexSqrt(), Is.EqualTo((Complex)1.4142135f)); + Assert.That(9.0f.ComplexSqrt(), Is.EqualTo((Complex)3.0f)); + Assert.That(16.0f.ComplexSqrt(), Is.EqualTo((Complex)4.0f)); + Assert.That(10000.0f.ComplexSqrt(), Is.EqualTo((Complex)100.0f)); } - [TestMethod] + [Test] public void ComplexSqrt_ShouldBeImaginary_GivenNegativeValue() { - Assert.AreEqual(new Complex(0, 1), (-1.0f).ComplexSqrt()); - Assert.AreEqual(new Complex(0, 1.4142135f), (-2.0f).ComplexSqrt()); - Assert.AreEqual(new Complex(0, 3.0f), (-9.0f).ComplexSqrt()); - Assert.AreEqual(new Complex(0, 4.0f), (-16.0f).ComplexSqrt()); + Assert.That((-1.0f).ComplexSqrt(), Is.EqualTo(new Complex(0, 1))); + Assert.That((-2.0f).ComplexSqrt(), Is.EqualTo(new Complex(0, 1.4142135f))); + Assert.That((-9.0f).ComplexSqrt(), Is.EqualTo(new Complex(0, 3.0f))); + Assert.That((-16.0f).ComplexSqrt(), Is.EqualTo(new Complex(0, 4.0f))); } - [TestMethod] + [Test] public void ComplexSqrt_ShouldBeComplexInfinity_GivenInfinity() { - Assert.AreEqual(Complex.Infinity, float.NegativeInfinity.ComplexSqrt()); - Assert.AreEqual(Complex.Infinity, float.PositiveInfinity.ComplexSqrt()); + Assert.Multiple(() => + { + Assert.That(float.NegativeInfinity.ComplexSqrt(), Is.EqualTo(Complex.Infinity)); + Assert.That(float.PositiveInfinity.ComplexSqrt(), Is.EqualTo(Complex.Infinity)); + }); } - [TestMethod] + [Test] public void ComplexSqrt_ShouldBeNaN_GivenNaN() { - Assert.AreEqual(Complex.NaN, float.NaN.ComplexSqrt()); + Assert.That(float.NaN.ComplexSqrt(), Is.EqualTo(Complex.NaN)); } - [TestMethod] + [Test] public void IsEven_ShouldBeFalse_GivenOddNumber() { - Assert.IsFalse((-3.0f).IsEven()); - Assert.IsFalse((-1.0f).IsEven()); - Assert.IsFalse(1.0f.IsEven()); - Assert.IsFalse(3.0f.IsEven()); + Assert.Multiple(() => + { + Assert.That((-3.0f).IsEven(), Is.False); + Assert.That((-1.0f).IsEven(), Is.False); + Assert.That(1.0f.IsEven(), Is.False); + Assert.That(3.0f.IsEven(), Is.False); + }); } - [TestMethod] + [Test] public void IsEven_ShouldBeTrue_GivenOddNumber() { - Assert.IsTrue((-4.0f).IsEven()); - Assert.IsTrue((-2.0f).IsEven()); - Assert.IsTrue(0.0f.IsEven()); - Assert.IsTrue(2.0f.IsEven()); - Assert.IsTrue(4.0f.IsEven()); + Assert.Multiple(() => + { + Assert.That((-4.0f).IsEven()); + Assert.That((-2.0f).IsEven()); + Assert.That(0.0f.IsEven()); + Assert.That(2.0f.IsEven()); + Assert.That(4.0f.IsEven()); + }); } - [TestMethod] + [Test] public void IsOdd_ShouldBeFalse_GivenEvenNumber() { - Assert.IsFalse((-4.0f).IsOdd()); - Assert.IsFalse((-2.0f).IsOdd()); - Assert.IsFalse(0.0f.IsOdd()); - Assert.IsFalse(2.0f.IsOdd()); - Assert.IsFalse(4.0f.IsOdd()); + Assert.Multiple(() => + { + Assert.That((-4.0f).IsOdd(), Is.False); + Assert.That((-2.0f).IsOdd(), Is.False); + Assert.That(0.0f.IsOdd(), Is.False); + Assert.That(2.0f.IsOdd(), Is.False); + Assert.That(4.0f.IsOdd(), Is.False); + }); } - [TestMethod] + [Test] public void IsOdd_ShouldBeTrue_GivenOddNumber() { - Assert.IsTrue((-3.0f).IsOdd()); - Assert.IsTrue((-1.0f).IsOdd()); - Assert.IsTrue(1.0f.IsOdd()); - Assert.IsTrue(3.0f.IsOdd()); + Assert.Multiple(() => + { + Assert.That((-3.0f).IsOdd()); + Assert.That((-1.0f).IsOdd()); + Assert.That(1.0f.IsOdd()); + Assert.That(3.0f.IsOdd()); + }); } - [TestMethod] + [Test] public void Round_ShouldRoundToNearestInteger() { - Assert.AreEqual(4.0f, 3.5f.Round(), 1e-6f); - Assert.AreEqual(7.0f, 6.8f.Round(), 1e-6f); - Assert.AreEqual(7.0f, 7.2f.Round(), 1e-6f); + Assert.Multiple(() => + { + Assert.That(3.5f.Round(), Is.EqualTo(4.0f).Within(1e-6f)); + Assert.That(6.8f.Round(), Is.EqualTo(7.0f).Within(1e-6f)); + Assert.That(7.2f.Round(), Is.EqualTo(7.0f).Within(1e-6f)); + }); } - [TestMethod] + [Test] public void Round_ShouldRoundToNearestMultiple() { - Assert.AreEqual(5.0f, 3.5f.Round(5), 1e-6f); - Assert.AreEqual(5.0f, 7.0f.Round(5), 1e-6f); - Assert.AreEqual(10.0f, 7.5f.Round(5), 1e-6f); + Assert.Multiple(() => + { + Assert.That(3.5f.Round(5), Is.EqualTo(5.0f).Within(1e-6f)); + Assert.That(7.0f.Round(5), Is.EqualTo(5.0f).Within(1e-6f)); + Assert.That(7.5f.Round(5), Is.EqualTo(10.0f).Within(1e-6f)); + }); } - [TestMethod] + [Test] public void Saturate_ShouldClampValueTo1_GivenGreaterThan1() { - Assert.AreEqual(1.0f, 1.5f.Saturate(), 1e-6f); + Assert.That(1.5f.Saturate(), Is.EqualTo(1.0f).Within(1e-6f)); } - [TestMethod] + [Test] public void Saturate_ShouldClampValueTo0_GivenLessThan0() { - Assert.AreEqual(0.0f, (-0.5f).Saturate(), 1e-6f); + Assert.That((-0.5f).Saturate(), Is.EqualTo(0.0f).Within(1e-6f)); } - [TestMethod] + [Test] public void Saturate_ShouldReturnValue_GivenValueBetween0And1() { - Assert.AreEqual(0.5f, 0.5f.Saturate(), 1e-6f); + Assert.That(0.5f.Saturate(), Is.EqualTo(0.5f).Within(1e-6f)); } - [TestMethod] + [Test] public void Sign_ShouldBeMinus1_GivenNegative() { - Assert.AreEqual(-1, -1.0f.Sign()); - Assert.AreEqual(-1, -2.0f.Sign()); - Assert.AreEqual(-1, -3.0f.Sign()); + Assert.That(-1.0f.Sign(), Is.EqualTo(-1)); + Assert.That(-2.0f.Sign(), Is.EqualTo(-1)); + Assert.That(-3.0f.Sign(), Is.EqualTo(-1)); } - [TestMethod] + [Test] public void Sign_ShouldBe0_Given0() { - Assert.AreEqual(0, 0.0f.Sign()); + Assert.That(0.0f.Sign(), Is.Zero); } - [TestMethod] + [Test] public void Sign_ShouldBe1_GivenPositive() { - Assert.AreEqual(1, 1.0f.Sign()); - Assert.AreEqual(1, 2.0f.Sign()); - Assert.AreEqual(1, 3.0f.Sign()); + Assert.Multiple(() => + { + Assert.That(1.0f.Sign(), Is.EqualTo(1)); + Assert.That(2.0f.Sign(), Is.EqualTo(1)); + Assert.That(3.0f.Sign(), Is.EqualTo(1)); + }); } - [TestMethod] + [Test] public void Sqrt_ShouldBeCorrect_GivenValue() { - Assert.AreEqual(0.0f, 0.0f.Sqrt(), 1e-6f); - Assert.AreEqual(1.4142135f, 2.0f.Sqrt(), 1e-6f); - Assert.AreEqual(3.0f, 9.0f.Sqrt(), 1e-6f); - Assert.AreEqual(4.0f, 16.0f.Sqrt(), 1e-6f); - Assert.AreEqual(100.0f, 10000.0f.Sqrt(), 1e-6f); + Assert.Multiple(() => + { + Assert.That(0.0f.Sqrt(), Is.EqualTo(0.0f).Within(1e-6f)); + Assert.That(2.0f.Sqrt(), Is.EqualTo(1.4142135f).Within(1e-6f)); + Assert.That(9.0f.Sqrt(), Is.EqualTo(3.0f).Within(1e-6f)); + Assert.That(16.0f.Sqrt(), Is.EqualTo(4.0f).Within(1e-6f)); + Assert.That(10000.0f.Sqrt(), Is.EqualTo(100.0f).Within(1e-6f)); + }); } - [TestMethod] + [Test] public void Sqrt_ShouldBeNaN_GivenNaN() { - Assert.AreEqual(float.NaN, float.NaN.Sqrt()); + Assert.That(float.NaN.Sqrt(), Is.EqualTo(float.NaN)); } - [TestMethod] + [Test] public void Sqrt_ShouldBeNaN_GivenNegativeValue() { - Assert.AreEqual(float.NaN, (-1.0f).Sqrt()); - Assert.AreEqual(float.NaN, (-2.0f).Sqrt()); - Assert.AreEqual(float.NaN, (-3.0f).Sqrt()); - Assert.AreEqual(float.NaN, float.NegativeInfinity.Sqrt()); + Assert.Multiple(() => + { + Assert.That((-1.0f).Sqrt(), Is.EqualTo(float.NaN)); + Assert.That((-2.0f).Sqrt(), Is.EqualTo(float.NaN)); + Assert.That((-3.0f).Sqrt(), Is.EqualTo(float.NaN)); + Assert.That(float.NegativeInfinity.Sqrt(), Is.EqualTo(float.NaN)); + }); } - [TestMethod] + [Test] public void Sqrt_ShouldBePositiveInfinity_GivenPositiveInfinity() { - Assert.AreEqual(float.PositiveInfinity, float.PositiveInfinity.Sqrt()); + Assert.That(float.PositiveInfinity.Sqrt(), Is.EqualTo(float.PositiveInfinity)); } - [TestMethod] + [Test] public void Acos_ShouldBeCorrect() { - Assert.AreEqual(1.0471975803375244f, 0.5f.Acos(), 1e-6f); + Assert.That(0.5f.Acos(), Is.EqualTo(1.0471975803375244f).Within(1e-6f)); } - [TestMethod] + [Test] public void Acosh_ShouldBeCorrect() { - Assert.AreEqual(0.9624236822128296f, 1.5f.Acosh(), 1e-6f); + Assert.That(1.5f.Acosh(), Is.EqualTo(0.9624236822128296f).Within(1e-6f)); } - [TestMethod] + [Test] public void Asin_ShouldBeCorrect() { - Assert.AreEqual(0.5235987901687622f, 0.5f.Asin(), 1e-6f); + Assert.That(0.5f.Asin(), Is.EqualTo(0.5235987901687622f).Within(1e-6f)); } - [TestMethod] + [Test] public void Asinh_ShouldBeCorrect() { - Assert.AreEqual(1.19476318359375f, 1.5f.Asinh(), 1e-6f); + Assert.That(1.5f.Asinh(), Is.EqualTo(1.19476318359375f).Within(1e-6f)); } - [TestMethod] + [Test] public void Atan_ShouldBeCorrect() { - Assert.AreEqual(0.46364760398864746, 0.5f.Atan(), 1e-6f); + Assert.That(0.5f.Atan(), Is.EqualTo(0.46364760398864746).Within(1e-6f)); } - [TestMethod] + [Test] public void Atanh_ShouldBeCorrect() { - Assert.AreEqual(0.5493061542510986f, 0.5f.Atanh(), 1e-6f); + Assert.That(0.5f.Atanh(), Is.EqualTo(0.5493061542510986f).Within(1e-6f)); } - [TestMethod] + [Test] public void Cos_ShouldBeCorrect() { - Assert.AreEqual(0.8775825500488281f, 0.5f.Cos(), 1e-6f); + Assert.That(0.5f.Cos(), Is.EqualTo(0.8775825500488281f).Within(1e-6f)); } - [TestMethod] + [Test] public void Cosh_ShouldBeCorrect() { - Assert.AreEqual(2.352409601211548f, 1.5f.Cosh(), 1e-6f); + Assert.That(1.5f.Cosh(), Is.EqualTo(2.352409601211548f).Within(1e-6f)); } - [TestMethod] + [Test] public void Sin_ShouldBeCorrect() { - Assert.AreEqual(0.4794255495071411, 0.5f.Sin(), 1e-6f); + Assert.That(0.5f.Sin(), Is.EqualTo(0.4794255495071411).Within(1e-6f)); } - [TestMethod] + [Test] public void Sinh_ShouldBeCorrect() { - Assert.AreEqual(2.129279375076294f, 1.5f.Sinh(), 1e-6f); + Assert.That(1.5f.Sinh(), Is.EqualTo(2.129279375076294f).Within(1e-6f)); } - [TestMethod] + [Test] public void Tan_ShouldBeCorrect() { - Assert.AreEqual(0.4794255495071411f, 0.5f.Tan(), 1e-6f); + Assert.That(0.5f.Tan(), Is.EqualTo(0.4794255495071411f).Within(1e-6f)); } - [TestMethod] + [Test] public void Tanh_ShouldBeCorrect() { - Assert.AreEqual(0.46211716532707214f, 0.5f.Tanh(), 1e-6f); + Assert.That(0.5f.Tanh(), Is.EqualTo(0.46211716532707214f).Within(1e-6f)); } } diff --git a/X10D.Tests/src/Math/UInt16Tests.Wrap.cs b/X10D.Tests/src/Math/UInt16Tests.Wrap.cs index 9704639..6f21662 100644 --- a/X10D.Tests/src/Math/UInt16Tests.Wrap.cs +++ b/X10D.Tests/src/Math/UInt16Tests.Wrap.cs @@ -1,14 +1,14 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Math; namespace X10D.Tests.Math; public partial class UInt16Tests { - [TestClass] + [TestFixture] public class WrapTests { - [TestMethod] + [Test] public void Wrap_ShouldReturnLow_WhenValueIsEqualToLow() { const ushort value = 10; @@ -17,10 +17,10 @@ public partial class UInt16Tests ushort result = value.Wrap(low, high); - Assert.AreEqual(low, result); + Assert.That(result, Is.EqualTo(low)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnHigh_WhenValueIsEqualToHigh() { const ushort value = 20; @@ -29,10 +29,10 @@ public partial class UInt16Tests ushort result = value.Wrap(low, high); - Assert.AreEqual(low, result); + Assert.That(result, Is.EqualTo(low)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsGreaterThanHigh() { const ushort value = 30; @@ -41,10 +41,10 @@ public partial class UInt16Tests ushort result = value.Wrap(low, high); - Assert.AreEqual(low, result); + Assert.That(result, Is.EqualTo(low)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsLessThanLow() { const ushort value = 5; @@ -53,10 +53,10 @@ public partial class UInt16Tests ushort result = value.Wrap(low, high); - Assert.AreEqual(11U, result); + Assert.That(result, Is.EqualTo(11U)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsInBetweenLowAndHigh() { const ushort value = 15; @@ -65,10 +65,10 @@ public partial class UInt16Tests ushort result = value.Wrap(low, high); - Assert.AreEqual(value, result); + Assert.That(result, Is.EqualTo(value)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnZero_WhenValueIsEqualToLength() { const ushort value = 10; @@ -76,10 +76,10 @@ public partial class UInt16Tests ushort result = value.Wrap(length); - Assert.AreEqual(0U, result); + Assert.That(result, Is.EqualTo(0U)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnValue_WhenValueIsLessThanLength() { const ushort value = 5; @@ -87,10 +87,10 @@ public partial class UInt16Tests ushort result = value.Wrap(length); - Assert.AreEqual(value, result); + Assert.That(result, Is.EqualTo(value)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsGreaterThanLength() { const ushort value = 15; @@ -98,7 +98,7 @@ public partial class UInt16Tests ushort result = value.Wrap(length); - Assert.AreEqual(5U, result); + Assert.That(result, Is.EqualTo(5U)); } } } diff --git a/X10D.Tests/src/Math/UInt16Tests.cs b/X10D.Tests/src/Math/UInt16Tests.cs index d873829..7055a00 100644 --- a/X10D.Tests/src/Math/UInt16Tests.cs +++ b/X10D.Tests/src/Math/UInt16Tests.cs @@ -1,37 +1,37 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Math; namespace X10D.Tests.Math; -[TestClass] +[TestFixture] [CLSCompliant(false)] public partial class UInt16Tests { - [TestMethod] + [Test] public void DigitalRootShouldBeCorrect() { const ushort value = 238; - Assert.AreEqual(4, value.DigitalRoot()); - Assert.AreEqual(4, (-value).DigitalRoot()); + Assert.That(value.DigitalRoot(), Is.EqualTo(4)); + Assert.That((-value).DigitalRoot(), Is.EqualTo(4)); } - [TestMethod] + [Test] public void FactorialShouldBeCorrect() { - Assert.AreEqual(1UL, ((ushort)0).Factorial()); - Assert.AreEqual(1UL, ((ushort)1).Factorial()); - Assert.AreEqual(2UL, ((ushort)2).Factorial()); - Assert.AreEqual(6UL, ((ushort)3).Factorial()); - Assert.AreEqual(24UL, ((ushort)4).Factorial()); - Assert.AreEqual(120UL, ((ushort)5).Factorial()); - Assert.AreEqual(720UL, ((ushort)6).Factorial()); - Assert.AreEqual(5040UL, ((ushort)7).Factorial()); - Assert.AreEqual(40320UL, ((ushort)8).Factorial()); - Assert.AreEqual(362880UL, ((ushort)9).Factorial()); - Assert.AreEqual(3628800UL, ((ushort)10).Factorial()); + Assert.That(((ushort)0).Factorial(), Is.EqualTo(1UL)); + Assert.That(((ushort)1).Factorial(), Is.EqualTo(1UL)); + Assert.That(((ushort)2).Factorial(), Is.EqualTo(2UL)); + Assert.That(((ushort)3).Factorial(), Is.EqualTo(6UL)); + Assert.That(((ushort)4).Factorial(), Is.EqualTo(24UL)); + Assert.That(((ushort)5).Factorial(), Is.EqualTo(120UL)); + Assert.That(((ushort)6).Factorial(), Is.EqualTo(720UL)); + Assert.That(((ushort)7).Factorial(), Is.EqualTo(5040UL)); + Assert.That(((ushort)8).Factorial(), Is.EqualTo(40320UL)); + Assert.That(((ushort)9).Factorial(), Is.EqualTo(362880UL)); + Assert.That(((ushort)10).Factorial(), Is.EqualTo(3628800UL)); } - [TestMethod] + [Test] public void GreatestCommonFactor_ShouldBe1_ForPrimeNumbers() { const ushort first = 5; @@ -39,10 +39,10 @@ public partial class UInt16Tests ushort multiple = first.GreatestCommonFactor(second); - Assert.AreEqual(1, multiple); + Assert.That(multiple, Is.EqualTo(1)); } - [TestMethod] + [Test] public void GreatestCommonFactor_ShouldBe6_Given12And18() { const ushort first = 12; @@ -50,30 +50,30 @@ public partial class UInt16Tests ushort multiple = first.GreatestCommonFactor(second); - Assert.AreEqual(6, multiple); + Assert.That(multiple, Is.EqualTo(6)); } - [TestMethod] + [Test] public void IsEvenShouldBeCorrect() { const ushort one = 1; const ushort two = 2; - Assert.IsFalse(one.IsEven()); - Assert.IsTrue(two.IsEven()); + Assert.That(one.IsEven(), Is.False); + Assert.That(two.IsEven()); } - [TestMethod] + [Test] public void IsOddShouldBeCorrect() { const ushort one = 1; const ushort two = 2; - Assert.IsTrue(one.IsOdd()); - Assert.IsFalse(two.IsOdd()); + Assert.That(one.IsOdd()); + Assert.That(two.IsOdd(), Is.False); } - [TestMethod] + [Test] public void LowestCommonMultiple_ShouldReturnCorrectValue_WhenCalledWithValidInput() { const ushort value1 = 2; @@ -82,10 +82,10 @@ public partial class UInt16Tests ushort result = value1.LowestCommonMultiple(value2); - Assert.AreEqual(expected, result); + Assert.That(result, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void LowestCommonMultiple_ShouldReturnZero_WhenCalledWithZero() { const ushort value1 = 0; @@ -94,10 +94,10 @@ public partial class UInt16Tests ushort result = value1.LowestCommonMultiple(value2); - Assert.AreEqual(expected, result); + Assert.That(result, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void LowestCommonMultiple_ShouldReturnGreaterValue_WhenCalledWithOne() { const ushort value1 = 1; @@ -107,11 +107,11 @@ public partial class UInt16Tests ushort result1 = value1.LowestCommonMultiple(value2); ushort result2 = value2.LowestCommonMultiple(value1); - Assert.AreEqual(expected, result1); - Assert.AreEqual(expected, result2); + Assert.That(result1, Is.EqualTo(expected)); + Assert.That(result2, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void LowestCommonMultiple_ShouldReturnOtherValue_WhenCalledWithSameValue() { const ushort value1 = 5; @@ -120,27 +120,27 @@ public partial class UInt16Tests ushort result = value1.LowestCommonMultiple(value2); - Assert.AreEqual(expected, result); + Assert.That(result, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void MultiplicativePersistence_ShouldReturn1_ForAnyDigitBeing0() { - Assert.AreEqual(1, ((ushort)10).MultiplicativePersistence()); - Assert.AreEqual(1, ((ushort)201).MultiplicativePersistence()); - Assert.AreEqual(1, ((ushort)200).MultiplicativePersistence()); - Assert.AreEqual(1, ((ushort)20007).MultiplicativePersistence()); + Assert.That(((ushort)10).MultiplicativePersistence(), Is.EqualTo(1)); + Assert.That(((ushort)201).MultiplicativePersistence(), Is.EqualTo(1)); + Assert.That(((ushort)200).MultiplicativePersistence(), Is.EqualTo(1)); + Assert.That(((ushort)20007).MultiplicativePersistence(), Is.EqualTo(1)); } - [TestMethod] + [Test] public void MultiplicativePersistence_ShouldBeCorrect_ForRecordHolders() { - Assert.AreEqual(0, ((ushort)0).MultiplicativePersistence()); - Assert.AreEqual(1, ((ushort)10).MultiplicativePersistence()); - Assert.AreEqual(2, ((ushort)25).MultiplicativePersistence()); - Assert.AreEqual(3, ((ushort)39).MultiplicativePersistence()); - Assert.AreEqual(4, ((ushort)77).MultiplicativePersistence()); - Assert.AreEqual(5, ((ushort)679).MultiplicativePersistence()); - Assert.AreEqual(6, ((ushort)6788).MultiplicativePersistence()); + Assert.That(((ushort)0).MultiplicativePersistence(), Is.Zero); + Assert.That(((ushort)10).MultiplicativePersistence(), Is.EqualTo(1)); + Assert.That(((ushort)25).MultiplicativePersistence(), Is.EqualTo(2)); + Assert.That(((ushort)39).MultiplicativePersistence(), Is.EqualTo(3)); + Assert.That(((ushort)77).MultiplicativePersistence(), Is.EqualTo(4)); + Assert.That(((ushort)679).MultiplicativePersistence(), Is.EqualTo(5)); + Assert.That(((ushort)6788).MultiplicativePersistence(), Is.EqualTo(6)); } } diff --git a/X10D.Tests/src/Math/UInt32Tests.Wrap.cs b/X10D.Tests/src/Math/UInt32Tests.Wrap.cs index 0fefee7..a46ee45 100644 --- a/X10D.Tests/src/Math/UInt32Tests.Wrap.cs +++ b/X10D.Tests/src/Math/UInt32Tests.Wrap.cs @@ -1,14 +1,14 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Math; namespace X10D.Tests.Math; public partial class UInt32Tests { - [TestClass] + [TestFixture] public class WrapTests { - [TestMethod] + [Test] public void Wrap_ShouldReturnLow_WhenValueIsEqualToLow() { const uint value = 10; @@ -17,10 +17,10 @@ public partial class UInt32Tests uint result = value.Wrap(low, high); - Assert.AreEqual(low, result); + Assert.That(result, Is.EqualTo(low)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnHigh_WhenValueIsEqualToHigh() { const uint value = 20; @@ -29,10 +29,10 @@ public partial class UInt32Tests uint result = value.Wrap(low, high); - Assert.AreEqual(low, result); + Assert.That(result, Is.EqualTo(low)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsGreaterThanHigh() { const uint value = 30; @@ -41,10 +41,10 @@ public partial class UInt32Tests uint result = value.Wrap(low, high); - Assert.AreEqual(low, result); + Assert.That(result, Is.EqualTo(low)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsLessThanLow() { const uint value = 5; @@ -53,10 +53,10 @@ public partial class UInt32Tests uint result = value.Wrap(low, high); - Assert.AreEqual(11U, result); + Assert.That(result, Is.EqualTo(11U)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsInBetweenLowAndHigh() { const uint value = 15; @@ -65,10 +65,10 @@ public partial class UInt32Tests uint result = value.Wrap(low, high); - Assert.AreEqual(value, result); + Assert.That(result, Is.EqualTo(value)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnZero_WhenValueIsEqualToLength() { const uint value = 10; @@ -76,10 +76,10 @@ public partial class UInt32Tests uint result = value.Wrap(length); - Assert.AreEqual(0U, result); + Assert.That(result, Is.EqualTo(0U)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnValue_WhenValueIsLessThanLength() { const uint value = 5; @@ -87,10 +87,10 @@ public partial class UInt32Tests uint result = value.Wrap(length); - Assert.AreEqual(value, result); + Assert.That(result, Is.EqualTo(value)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsGreaterThanLength() { const uint value = 15; @@ -98,7 +98,7 @@ public partial class UInt32Tests uint result = value.Wrap(length); - Assert.AreEqual(5U, result); + Assert.That(result, Is.EqualTo(5U)); } } } diff --git a/X10D.Tests/src/Math/UInt32Tests.cs b/X10D.Tests/src/Math/UInt32Tests.cs index 4454642..b550667 100644 --- a/X10D.Tests/src/Math/UInt32Tests.cs +++ b/X10D.Tests/src/Math/UInt32Tests.cs @@ -1,37 +1,37 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Math; namespace X10D.Tests.Math; -[TestClass] +[TestFixture] [CLSCompliant(false)] public partial class UInt32Tests { - [TestMethod] + [Test] public void DigitalRootShouldBeCorrect() { const uint value = 238; - Assert.AreEqual(4U, value.DigitalRoot()); - Assert.AreEqual(4U, (-value).DigitalRoot()); + Assert.That(value.DigitalRoot(), Is.EqualTo(4U)); + Assert.That((-value).DigitalRoot(), Is.EqualTo(4U)); } - [TestMethod] + [Test] public void FactorialShouldBeCorrect() { - Assert.AreEqual(1UL, 0U.Factorial()); - Assert.AreEqual(1UL, 1U.Factorial()); - Assert.AreEqual(2UL, 2U.Factorial()); - Assert.AreEqual(6UL, 3U.Factorial()); - Assert.AreEqual(24UL, 4U.Factorial()); - Assert.AreEqual(120UL, 5U.Factorial()); - Assert.AreEqual(720UL, 6U.Factorial()); - Assert.AreEqual(5040UL, 7U.Factorial()); - Assert.AreEqual(40320UL, 8U.Factorial()); - Assert.AreEqual(362880UL, 9U.Factorial()); - Assert.AreEqual(3628800UL, 10U.Factorial()); + Assert.That(0U.Factorial(), Is.EqualTo(1UL)); + Assert.That(1U.Factorial(), Is.EqualTo(1UL)); + Assert.That(2U.Factorial(), Is.EqualTo(2UL)); + Assert.That(3U.Factorial(), Is.EqualTo(6UL)); + Assert.That(4U.Factorial(), Is.EqualTo(24UL)); + Assert.That(5U.Factorial(), Is.EqualTo(120UL)); + Assert.That(6U.Factorial(), Is.EqualTo(720UL)); + Assert.That(7U.Factorial(), Is.EqualTo(5040UL)); + Assert.That(8U.Factorial(), Is.EqualTo(40320UL)); + Assert.That(9U.Factorial(), Is.EqualTo(362880UL)); + Assert.That(10U.Factorial(), Is.EqualTo(3628800UL)); } - [TestMethod] + [Test] public void GreatestCommonFactor_ShouldBe1_ForPrimeNumbers() { const uint first = 5U; @@ -39,10 +39,10 @@ public partial class UInt32Tests uint multiple = first.GreatestCommonFactor(second); - Assert.AreEqual(1U, multiple); + Assert.That(multiple, Is.EqualTo(1U)); } - [TestMethod] + [Test] public void GreatestCommonFactor_ShouldBe6_Given12And18() { const uint first = 12U; @@ -50,30 +50,30 @@ public partial class UInt32Tests uint multiple = first.GreatestCommonFactor(second); - Assert.AreEqual(6U, multiple); + Assert.That(multiple, Is.EqualTo(6U)); } - [TestMethod] + [Test] public void IsEvenShouldBeCorrect() { const uint one = 1; const uint two = 2; - Assert.IsFalse(one.IsEven()); - Assert.IsTrue(two.IsEven()); + Assert.That(one.IsEven(), Is.False); + Assert.That(two.IsEven()); } - [TestMethod] + [Test] public void IsOddShouldBeCorrect() { const uint one = 1; const uint two = 2; - Assert.IsTrue(one.IsOdd()); - Assert.IsFalse(two.IsOdd()); + Assert.That(one.IsOdd()); + Assert.That(two.IsOdd(), Is.False); } - [TestMethod] + [Test] public void LowestCommonMultiple_ShouldReturnCorrectValue_WhenCalledWithValidInput() { const uint value1 = 2; @@ -82,10 +82,10 @@ public partial class UInt32Tests uint result = value1.LowestCommonMultiple(value2); - Assert.AreEqual(expected, result); + Assert.That(result, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void LowestCommonMultiple_ShouldReturnZero_WhenCalledWithZero() { const uint value1 = 0; @@ -94,10 +94,10 @@ public partial class UInt32Tests uint result = value1.LowestCommonMultiple(value2); - Assert.AreEqual(expected, result); + Assert.That(result, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void LowestCommonMultiple_ShouldReturnGreaterValue_WhenCalledWithOne() { const uint value1 = 1; @@ -107,11 +107,11 @@ public partial class UInt32Tests uint result1 = value1.LowestCommonMultiple(value2); uint result2 = value2.LowestCommonMultiple(value1); - Assert.AreEqual(expected, result1); - Assert.AreEqual(expected, result2); + Assert.That(result1, Is.EqualTo(expected)); + Assert.That(result2, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void LowestCommonMultiple_ShouldReturnOtherValue_WhenCalledWithSameValue() { const uint value1 = 5; @@ -120,31 +120,31 @@ public partial class UInt32Tests uint result = value1.LowestCommonMultiple(value2); - Assert.AreEqual(expected, result); + Assert.That(result, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void MultiplicativePersistence_ShouldReturn1_ForAnyDigitBeing0() { - Assert.AreEqual(1, 10U.MultiplicativePersistence()); - Assert.AreEqual(1, 201U.MultiplicativePersistence()); - Assert.AreEqual(1, 200U.MultiplicativePersistence()); - Assert.AreEqual(1, 20007U.MultiplicativePersistence()); + Assert.That(10U.MultiplicativePersistence(), Is.EqualTo(1)); + Assert.That(201U.MultiplicativePersistence(), Is.EqualTo(1)); + Assert.That(200U.MultiplicativePersistence(), Is.EqualTo(1)); + Assert.That(20007U.MultiplicativePersistence(), Is.EqualTo(1)); } - [TestMethod] + [Test] public void MultiplicativePersistence_ShouldBeCorrect_ForRecordHolders() { - Assert.AreEqual(0, 0U.MultiplicativePersistence()); - Assert.AreEqual(1, 10U.MultiplicativePersistence()); - Assert.AreEqual(2, 25U.MultiplicativePersistence()); - Assert.AreEqual(3, 39U.MultiplicativePersistence()); - Assert.AreEqual(4, 77U.MultiplicativePersistence()); - Assert.AreEqual(5, 679U.MultiplicativePersistence()); - Assert.AreEqual(6, 6788U.MultiplicativePersistence()); - Assert.AreEqual(7, 68889U.MultiplicativePersistence()); - Assert.AreEqual(8, 2677889U.MultiplicativePersistence()); - Assert.AreEqual(9, 26888999U.MultiplicativePersistence()); - Assert.AreEqual(10, 3778888999U.MultiplicativePersistence()); + Assert.That(0U.MultiplicativePersistence(), Is.Zero); + Assert.That(10U.MultiplicativePersistence(), Is.EqualTo(1)); + Assert.That(25U.MultiplicativePersistence(), Is.EqualTo(2)); + Assert.That(39U.MultiplicativePersistence(), Is.EqualTo(3)); + Assert.That(77U.MultiplicativePersistence(), Is.EqualTo(4)); + Assert.That(679U.MultiplicativePersistence(), Is.EqualTo(5)); + Assert.That(6788U.MultiplicativePersistence(), Is.EqualTo(6)); + Assert.That(68889U.MultiplicativePersistence(), Is.EqualTo(7)); + Assert.That(2677889U.MultiplicativePersistence(), Is.EqualTo(8)); + Assert.That(26888999U.MultiplicativePersistence(), Is.EqualTo(9)); + Assert.That(3778888999U.MultiplicativePersistence(), Is.EqualTo(10)); } } diff --git a/X10D.Tests/src/Math/UInt64Tests.Wrap.cs b/X10D.Tests/src/Math/UInt64Tests.Wrap.cs index e28c49b..a99e8ad 100644 --- a/X10D.Tests/src/Math/UInt64Tests.Wrap.cs +++ b/X10D.Tests/src/Math/UInt64Tests.Wrap.cs @@ -1,14 +1,14 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Math; namespace X10D.Tests.Math; public partial class UInt64Tests { - [TestClass] + [TestFixture] public class WrapTests { - [TestMethod] + [Test] public void Wrap_ShouldReturnLow_WhenValueIsEqualToLow() { const ulong value = 10; @@ -17,10 +17,10 @@ public partial class UInt64Tests ulong result = value.Wrap(low, high); - Assert.AreEqual(low, result); + Assert.That(result, Is.EqualTo(low)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnHigh_WhenValueIsEqualToHigh() { const ulong value = 20; @@ -29,10 +29,10 @@ public partial class UInt64Tests ulong result = value.Wrap(low, high); - Assert.AreEqual(low, result); + Assert.That(result, Is.EqualTo(low)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsGreaterThanHigh() { const ulong value = 30; @@ -41,10 +41,10 @@ public partial class UInt64Tests ulong result = value.Wrap(low, high); - Assert.AreEqual(low, result); + Assert.That(result, Is.EqualTo(low)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsLessThanLow() { const ulong value = 5; @@ -53,10 +53,10 @@ public partial class UInt64Tests ulong result = value.Wrap(low, high); - Assert.AreEqual(11UL, result); + Assert.That(result, Is.EqualTo(11UL)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsInBetweenLowAndHigh() { const ulong value = 15; @@ -65,10 +65,10 @@ public partial class UInt64Tests ulong result = value.Wrap(low, high); - Assert.AreEqual(value, result); + Assert.That(result, Is.EqualTo(value)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnZero_WhenValueIsEqualToLength() { const ulong value = 10; @@ -76,10 +76,10 @@ public partial class UInt64Tests ulong result = value.Wrap(length); - Assert.AreEqual(0UL, result); + Assert.That(result, Is.EqualTo(0UL)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnValue_WhenValueIsLessThanLength() { const ulong value = 5; @@ -87,10 +87,10 @@ public partial class UInt64Tests ulong result = value.Wrap(length); - Assert.AreEqual(value, result); + Assert.That(result, Is.EqualTo(value)); } - [TestMethod] + [Test] public void Wrap_ShouldReturnCorrectResult_WhenValueIsGreaterThanLength() { const ulong value = 15; @@ -98,7 +98,7 @@ public partial class UInt64Tests ulong result = value.Wrap(length); - Assert.AreEqual(5UL, result); + Assert.That(result, Is.EqualTo(5UL)); } } } diff --git a/X10D.Tests/src/Math/UInt64Tests.cs b/X10D.Tests/src/Math/UInt64Tests.cs index c5e81ba..777c5ab 100644 --- a/X10D.Tests/src/Math/UInt64Tests.cs +++ b/X10D.Tests/src/Math/UInt64Tests.cs @@ -1,41 +1,41 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Math; namespace X10D.Tests.Math; -[TestClass] +[TestFixture] [CLSCompliant(false)] public partial class UInt64Tests { - [TestMethod] + [Test] public void DigitalRootShouldBeCorrect() { const ulong value = 238; - Assert.AreEqual(4U, value.DigitalRoot()); + Assert.That(value.DigitalRoot(), Is.EqualTo(4U)); // -ulong operator not defined because it might exceed long.MinValue, // so instead, cast to long and then negate. // HAX. - Assert.AreEqual(4U, (-(long)value).DigitalRoot()); + Assert.That((-(long)value).DigitalRoot(), Is.EqualTo(4U)); } - [TestMethod] + [Test] public void FactorialShouldBeCorrect() { - Assert.AreEqual(1UL, 0UL.Factorial()); - Assert.AreEqual(1UL, 1UL.Factorial()); - Assert.AreEqual(2UL, 2UL.Factorial()); - Assert.AreEqual(6UL, 3UL.Factorial()); - Assert.AreEqual(24UL, 4UL.Factorial()); - Assert.AreEqual(120UL, 5UL.Factorial()); - Assert.AreEqual(720UL, 6UL.Factorial()); - Assert.AreEqual(5040UL, 7UL.Factorial()); - Assert.AreEqual(40320UL, 8UL.Factorial()); - Assert.AreEqual(362880UL, 9UL.Factorial()); - Assert.AreEqual(3628800UL, 10UL.Factorial()); + Assert.That(0UL.Factorial(), Is.EqualTo(1UL)); + Assert.That(1UL.Factorial(), Is.EqualTo(1UL)); + Assert.That(2UL.Factorial(), Is.EqualTo(2UL)); + Assert.That(3UL.Factorial(), Is.EqualTo(6UL)); + Assert.That(4UL.Factorial(), Is.EqualTo(24UL)); + Assert.That(5UL.Factorial(), Is.EqualTo(120UL)); + Assert.That(6UL.Factorial(), Is.EqualTo(720UL)); + Assert.That(7UL.Factorial(), Is.EqualTo(5040UL)); + Assert.That(8UL.Factorial(), Is.EqualTo(40320UL)); + Assert.That(9UL.Factorial(), Is.EqualTo(362880UL)); + Assert.That(10UL.Factorial(), Is.EqualTo(3628800UL)); } - [TestMethod] + [Test] public void GreatestCommonFactor_ShouldBe1_ForPrimeNumbers() { const ulong first = 5UL; @@ -43,10 +43,10 @@ public partial class UInt64Tests ulong multiple = first.GreatestCommonFactor(second); - Assert.AreEqual(1UL, multiple); + Assert.That(multiple, Is.EqualTo(1UL)); } - [TestMethod] + [Test] public void GreatestCommonFactor_ShouldBe6_Given12And18() { const ulong first = 12UL; @@ -54,30 +54,30 @@ public partial class UInt64Tests ulong multiple = first.GreatestCommonFactor(second); - Assert.AreEqual(6UL, multiple); + Assert.That(multiple, Is.EqualTo(6UL)); } - [TestMethod] + [Test] public void IsEvenShouldBeCorrect() { const ulong one = 1; const ulong two = 2; - Assert.IsFalse(one.IsEven()); - Assert.IsTrue(two.IsEven()); + Assert.That(one.IsEven(), Is.False); + Assert.That(two.IsEven()); } - [TestMethod] + [Test] public void IsOddShouldBeCorrect() { const ulong one = 1; const ulong two = 2; - Assert.IsTrue(one.IsOdd()); - Assert.IsFalse(two.IsOdd()); + Assert.That(one.IsOdd()); + Assert.That(two.IsOdd(), Is.False); } - [TestMethod] + [Test] public void LowestCommonMultiple_ShouldReturnCorrectValue_WhenCalledWithValidInput() { const ulong value1 = 2; @@ -86,10 +86,10 @@ public partial class UInt64Tests ulong result = value1.LowestCommonMultiple(value2); - Assert.AreEqual(expected, result); + Assert.That(result, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void LowestCommonMultiple_ShouldReturnZero_WhenCalledWithZero() { const ulong value1 = 0; @@ -98,10 +98,10 @@ public partial class UInt64Tests ulong result = value1.LowestCommonMultiple(value2); - Assert.AreEqual(expected, result); + Assert.That(result, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void LowestCommonMultiple_ShouldReturnGreaterValue_WhenCalledWithOne() { const ulong value1 = 1; @@ -110,10 +110,10 @@ public partial class UInt64Tests ulong result = value1.LowestCommonMultiple(value2); - Assert.AreEqual(expected, result); + Assert.That(result, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void LowestCommonMultiple_ShouldReturnOtherValue_WhenCalledWithSameValue() { const ulong value1 = 5; @@ -122,32 +122,32 @@ public partial class UInt64Tests ulong result = value1.LowestCommonMultiple(value2); - Assert.AreEqual(expected, result); + Assert.That(result, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void MultiplicativePersistence_ShouldReturn1_ForAnyDigitBeing0() { - Assert.AreEqual(1, 10UL.MultiplicativePersistence()); - Assert.AreEqual(1, 201UL.MultiplicativePersistence()); - Assert.AreEqual(1, 200UL.MultiplicativePersistence()); - Assert.AreEqual(1, 20007UL.MultiplicativePersistence()); + Assert.That(10UL.MultiplicativePersistence(), Is.EqualTo(1)); + Assert.That(201UL.MultiplicativePersistence(), Is.EqualTo(1)); + Assert.That(200UL.MultiplicativePersistence(), Is.EqualTo(1)); + Assert.That(20007UL.MultiplicativePersistence(), Is.EqualTo(1)); } - [TestMethod] + [Test] public void MultiplicativePersistence_ShouldBeCorrect_ForRecordHolders() { - Assert.AreEqual(0, 0UL.MultiplicativePersistence()); - Assert.AreEqual(1, 10UL.MultiplicativePersistence()); - Assert.AreEqual(2, 25UL.MultiplicativePersistence()); - Assert.AreEqual(3, 39UL.MultiplicativePersistence()); - Assert.AreEqual(4, 77UL.MultiplicativePersistence()); - Assert.AreEqual(5, 679UL.MultiplicativePersistence()); - Assert.AreEqual(6, 6788UL.MultiplicativePersistence()); - Assert.AreEqual(7, 68889UL.MultiplicativePersistence()); - Assert.AreEqual(8, 2677889UL.MultiplicativePersistence()); - Assert.AreEqual(9, 26888999UL.MultiplicativePersistence()); - Assert.AreEqual(10, 3778888999UL.MultiplicativePersistence()); - Assert.AreEqual(11, 277777788888899UL.MultiplicativePersistence()); + Assert.That(0UL.MultiplicativePersistence(), Is.Zero); + Assert.That(10UL.MultiplicativePersistence(), Is.EqualTo(1)); + Assert.That(25UL.MultiplicativePersistence(), Is.EqualTo(2)); + Assert.That(39UL.MultiplicativePersistence(), Is.EqualTo(3)); + Assert.That(77UL.MultiplicativePersistence(), Is.EqualTo(4)); + Assert.That(679UL.MultiplicativePersistence(), Is.EqualTo(5)); + Assert.That(6788UL.MultiplicativePersistence(), Is.EqualTo(6)); + Assert.That(68889UL.MultiplicativePersistence(), Is.EqualTo(7)); + Assert.That(2677889UL.MultiplicativePersistence(), Is.EqualTo(8)); + Assert.That(26888999UL.MultiplicativePersistence(), Is.EqualTo(9)); + Assert.That(3778888999UL.MultiplicativePersistence(), Is.EqualTo(10)); + Assert.That(277777788888899UL.MultiplicativePersistence(), Is.EqualTo(11)); } } diff --git a/X10D.Tests/src/Net/EndPointTests.cs b/X10D.Tests/src/Net/EndPointTests.cs index 8b508d9..eb69138 100644 --- a/X10D.Tests/src/Net/EndPointTests.cs +++ b/X10D.Tests/src/Net/EndPointTests.cs @@ -1,73 +1,73 @@ using System.Net; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Net; namespace X10D.Tests.Net; -[TestClass] +[TestFixture] public class EndPointTests { - [TestMethod] + [Test] public void GetHost_ShouldBeLocalhost_GivenLocalhostDnsEndPoint() { var endPoint = new DnsEndPoint("localhost", 1234); - Assert.AreEqual("localhost", endPoint.GetHost()); + Assert.That(endPoint.GetHost(), Is.EqualTo("localhost")); } - [TestMethod] + [Test] public void GetHost_ShouldBe127001_GivenLoopbackIPEndPoint() { var endPoint = new IPEndPoint(IPAddress.Loopback, 1234); - Assert.AreEqual("127.0.0.1", endPoint.GetHost()); + Assert.That(endPoint.GetHost(), Is.EqualTo("127.0.0.1")); } - [TestMethod] + [Test] public void GetHost_ShouldBeColonColon1_GivenIPv6LoopBackIPEndPoint() { var endPoint = new IPEndPoint(IPAddress.IPv6Loopback, 1234); - Assert.AreEqual("::1", endPoint.GetHost()); + Assert.That(endPoint.GetHost(), Is.EqualTo("::1")); } - [TestMethod] + [Test] public void GetHost_ShouldThrow_GivenNull() { - Assert.ThrowsException(() => ((IPEndPoint?)null)!.GetHost()); - Assert.ThrowsException(() => ((DnsEndPoint?)null)!.GetHost()); + Assert.Throws(() => ((IPEndPoint?)null)!.GetHost()); + Assert.Throws(() => ((DnsEndPoint?)null)!.GetHost()); } - [TestMethod] + [Test] public void GetPort_ShouldBe1234_Given1234IPEndPoint() { var endPoint = new IPEndPoint(IPAddress.Loopback, 1234); - Assert.AreEqual(1234, endPoint.GetPort()); + Assert.That(endPoint.GetPort(), Is.EqualTo(1234)); } - [TestMethod] + [Test] public void GetPort_ShouldBe1234_Given1234DnsEndPoint() { var endPoint = new DnsEndPoint("localhost", 1234); - Assert.AreEqual(1234, endPoint.GetPort()); + Assert.That(endPoint.GetPort(), Is.EqualTo(1234)); } - [TestMethod] + [Test] public void GetPort_ShouldThrow_GivenNull() { - Assert.ThrowsException(() => ((IPEndPoint?)null)!.GetPort()); - Assert.ThrowsException(() => ((DnsEndPoint?)null)!.GetPort()); + Assert.Throws(() => ((IPEndPoint?)null)!.GetPort()); + Assert.Throws(() => ((DnsEndPoint?)null)!.GetPort()); } - [TestMethod] + [Test] public void GetHost_ShouldBeEmpty_GivenInvalidEndPoint() { var endPoint = new DummyEndPoint(); - Assert.AreEqual(string.Empty, endPoint.GetHost()); + Assert.That(endPoint.GetHost(), Is.EqualTo(string.Empty)); } - [TestMethod] + [Test] public void GetPort_ShouldBe0_GivenInvalidEndPoint() { var endPoint = new DummyEndPoint(); - Assert.AreEqual(0, endPoint.GetPort()); + Assert.That(endPoint.GetPort(), Is.Zero); } private class DummyEndPoint : EndPoint diff --git a/X10D.Tests/src/Net/IPAddressTests.cs b/X10D.Tests/src/Net/IPAddressTests.cs index 443d6fb..de0f8eb 100644 --- a/X10D.Tests/src/Net/IPAddressTests.cs +++ b/X10D.Tests/src/Net/IPAddressTests.cs @@ -1,57 +1,57 @@ using System.Net; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Net; namespace X10D.Tests.Net; -[TestClass] +[TestFixture] public class IPAddressTests { private IPAddress _ipv4Address = null!; private IPAddress _ipv6Address = null!; - [TestInitialize] + [SetUp] public void Initialize() { _ipv4Address = IPAddress.Parse("127.0.0.1"); _ipv6Address = IPAddress.Parse("::1"); } - [TestMethod] + [Test] public void IsIPv4_ShouldBeTrue_GivenIPv4() { - Assert.IsTrue(_ipv4Address.IsIPv4()); + Assert.That(_ipv4Address.IsIPv4()); } - [TestMethod] + [Test] public void IsIPv4_ShouldBeFalse_GivenIPv6() { - Assert.IsFalse(_ipv6Address.IsIPv4()); + Assert.That(_ipv6Address.IsIPv4(), Is.False); } - [TestMethod] + [Test] public void IsIPv4_ShouldThrowArgumentNullException_GivenNullAddress() { IPAddress address = null!; - Assert.ThrowsException(() => address.IsIPv4()); + Assert.Throws(() => address.IsIPv4()); } - [TestMethod] + [Test] public void IsIPv6_ShouldBeFalse_GivenIPv4() { - Assert.IsFalse(_ipv4Address.IsIPv6()); + Assert.That(_ipv4Address.IsIPv6(), Is.False); } - [TestMethod] + [Test] public void IsIPv6_ShouldBeTrue_GivenIPv6() { - Assert.IsTrue(_ipv6Address.IsIPv6()); + Assert.That(_ipv6Address.IsIPv6()); } - [TestMethod] + [Test] public void IsIPv6_ShouldThrowArgumentNullException_GivenNullAddress() { IPAddress address = null!; - Assert.ThrowsException(() => address.IsIPv6()); + Assert.Throws(() => address.IsIPv6()); } } diff --git a/X10D.Tests/src/Net/Int16Tests.cs b/X10D.Tests/src/Net/Int16Tests.cs index 9dea812..4a850c7 100644 --- a/X10D.Tests/src/Net/Int16Tests.cs +++ b/X10D.Tests/src/Net/Int16Tests.cs @@ -1,26 +1,26 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Net; namespace X10D.Tests.Net; -[TestClass] +[TestFixture] public class Int16Tests { - [TestMethod] + [Test] public void HostToNetworkOrder_ReturnsCorrectValue() { const short hostOrder = 0x0102; const short networkOrder = 0x0201; - Assert.AreEqual(BitConverter.IsLittleEndian ? networkOrder : hostOrder, hostOrder.HostToNetworkOrder()); + Assert.That(hostOrder.HostToNetworkOrder(), Is.EqualTo(BitConverter.IsLittleEndian ? networkOrder : hostOrder)); } - [TestMethod] + [Test] public void NetworkToHostOrder_ReturnsCorrectValue() { const short hostOrder = 0x0102; const short networkOrder = 0x0201; - Assert.AreEqual(BitConverter.IsLittleEndian ? hostOrder : networkOrder, networkOrder.NetworkToHostOrder()); + Assert.That(networkOrder.NetworkToHostOrder(), Is.EqualTo(BitConverter.IsLittleEndian ? hostOrder : networkOrder)); } } diff --git a/X10D.Tests/src/Net/Int32Tests.cs b/X10D.Tests/src/Net/Int32Tests.cs index 7157eef..7e876ec 100644 --- a/X10D.Tests/src/Net/Int32Tests.cs +++ b/X10D.Tests/src/Net/Int32Tests.cs @@ -1,26 +1,26 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Net; namespace X10D.Tests.Net; -[TestClass] +[TestFixture] public class Int32Tests { - [TestMethod] + [Test] public void HostToNetworkOrder_ReturnsCorrectValue() { const int hostOrder = 0x01020304; const int networkOrder = 0x04030201; - Assert.AreEqual(BitConverter.IsLittleEndian ? networkOrder : hostOrder, hostOrder.HostToNetworkOrder()); + Assert.That(hostOrder.HostToNetworkOrder(), Is.EqualTo(BitConverter.IsLittleEndian ? networkOrder : hostOrder)); } - [TestMethod] + [Test] public void NetworkToHostOrder_ReturnsCorrectValue() { const int hostOrder = 0x01020304; const int networkOrder = 0x04030201; - Assert.AreEqual(BitConverter.IsLittleEndian ? hostOrder : networkOrder, networkOrder.NetworkToHostOrder()); + Assert.That(networkOrder.NetworkToHostOrder(), Is.EqualTo(BitConverter.IsLittleEndian ? hostOrder : networkOrder)); } } diff --git a/X10D.Tests/src/Net/Int64Tests.cs b/X10D.Tests/src/Net/Int64Tests.cs index c207125..2e1bc76 100644 --- a/X10D.Tests/src/Net/Int64Tests.cs +++ b/X10D.Tests/src/Net/Int64Tests.cs @@ -1,26 +1,26 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Net; namespace X10D.Tests.Net; -[TestClass] +[TestFixture] public class Int64Tests { - [TestMethod] + [Test] public void HostToNetworkOrder_ReturnsCorrectValue() { const long hostOrder = 0x0102030405060708; const long networkOrder = 0x0807060504030201; - Assert.AreEqual(BitConverter.IsLittleEndian ? networkOrder : hostOrder, hostOrder.HostToNetworkOrder()); + Assert.That(hostOrder.HostToNetworkOrder(), Is.EqualTo(BitConverter.IsLittleEndian ? networkOrder : hostOrder)); } - [TestMethod] + [Test] public void NetworkToHostOrder_ReturnsCorrectValue() { const long hostOrder = 0x0102030405060708; const long networkOrder = 0x0807060504030201; - Assert.AreEqual(BitConverter.IsLittleEndian ? hostOrder : networkOrder, networkOrder.NetworkToHostOrder()); + Assert.That(networkOrder.NetworkToHostOrder(), Is.EqualTo(BitConverter.IsLittleEndian ? hostOrder : networkOrder)); } } diff --git a/X10D.Tests/src/Numerics/ByteTests.cs b/X10D.Tests/src/Numerics/ByteTests.cs index b9f875a..6257ea3 100644 --- a/X10D.Tests/src/Numerics/ByteTests.cs +++ b/X10D.Tests/src/Numerics/ByteTests.cs @@ -1,85 +1,85 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Numerics; namespace X10D.Tests.Numerics; -[TestClass] +[TestFixture] public class ByteTests { - [TestMethod] + [Test] public void PopCount_ShouldBe0_Given0() { - Assert.AreEqual(0, ((byte)0).PopCount()); + Assert.That(((byte)0).PopCount(), Is.Zero); } - [TestMethod] + [Test] public void PopCount_ShouldBe5_Given11010101() { - Assert.AreEqual(5, ((byte)0b11010101).PopCount()); + Assert.That(((byte)0b11010101).PopCount(), Is.EqualTo(5)); } - [TestMethod] + [Test] public void PopCount_ShouldBe8_Given11111111() { - Assert.AreEqual(8, ((byte)0b11111111).PopCount()); + Assert.That(((byte)0b11111111).PopCount(), Is.EqualTo(8)); } - [TestMethod] + [Test] public void RotateLeft_ShouldRotateCorrectly() { const byte value = 181; // 10110101 const byte expected = 91; // 01011011 - Assert.AreEqual(value, value.RotateLeft(0)); - Assert.AreEqual(expected, value.RotateLeft(4)); + Assert.That(value.RotateLeft(0), Is.EqualTo(value)); + Assert.That(value.RotateLeft(4), Is.EqualTo(expected)); } - [TestMethod] + [Test] public void RotateLeft_ShouldModForLargeCount() { const byte value = 181; // 10110101 - Assert.AreEqual(value, value.RotateLeft(8)); + Assert.That(value.RotateLeft(8), Is.EqualTo(value)); } - [TestMethod] + [Test] public void RotateRight_ShouldRotateCorrectly() { const byte value = 181; // 10110101 const byte expected = 91; // 01011011 - Assert.AreEqual(value, value.RotateRight(0)); - Assert.AreEqual(expected, value.RotateRight(4)); + Assert.That(value.RotateRight(0), Is.EqualTo(value)); + Assert.That(value.RotateRight(4), Is.EqualTo(expected)); } - [TestMethod] + [Test] public void RotateRight_ShouldModForLargeCount() { const byte value = 181; // 10110101 - Assert.AreEqual(value, value.RotateRight(8)); + Assert.That(value.RotateRight(8), Is.EqualTo(value)); } - [TestMethod] + [Test] public void RoundUpToPowerOf2_ShouldReturnRoundedValue_GivenValue() { - Assert.AreEqual(4, ((byte)3).RoundUpToPowerOf2()); - Assert.AreEqual(8, ((byte)5).RoundUpToPowerOf2()); - Assert.AreEqual(8, ((byte)6).RoundUpToPowerOf2()); - Assert.AreEqual(8, ((byte)7).RoundUpToPowerOf2()); + Assert.That(((byte)3).RoundUpToPowerOf2(), Is.EqualTo(4)); + Assert.That(((byte)5).RoundUpToPowerOf2(), Is.EqualTo(8)); + Assert.That(((byte)6).RoundUpToPowerOf2(), Is.EqualTo(8)); + Assert.That(((byte)7).RoundUpToPowerOf2(), Is.EqualTo(8)); } - [TestMethod] + [Test] public void RoundUpToPowerOf2_ShouldReturnSameValue_GivenPowerOf2() { for (var i = 0; i < 8; i++) { var value = (byte)System.Math.Pow(2, i); - Assert.AreEqual(value, value.RoundUpToPowerOf2()); + Assert.That(value.RoundUpToPowerOf2(), Is.EqualTo(value)); } } - [TestMethod] + [Test] public void RoundUpToPowerOf2_ShouldReturn0_Given0() { - Assert.AreEqual(0, ((byte)0).RoundUpToPowerOf2()); + Assert.That(((byte)0).RoundUpToPowerOf2(), Is.Zero); } } diff --git a/X10D.Tests/src/Numerics/Int16Tests.cs b/X10D.Tests/src/Numerics/Int16Tests.cs index 1368cd2..3058845 100644 --- a/X10D.Tests/src/Numerics/Int16Tests.cs +++ b/X10D.Tests/src/Numerics/Int16Tests.cs @@ -1,87 +1,87 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Numerics; namespace X10D.Tests.Numerics; -[TestClass] +[TestFixture] public class Int16Tests { - [TestMethod] + [Test] public void PopCount_ShouldBe0_Given0() { - Assert.AreEqual(0, ((short)0).PopCount()); + Assert.That(((short)0).PopCount(), Is.Zero); } - [TestMethod] + [Test] public void PopCount_ShouldBe5_Given11010101() { - Assert.AreEqual(5, ((short)0b11010101).PopCount()); + Assert.That(((short)0b11010101).PopCount(), Is.EqualTo(5)); } - [TestMethod] + [Test] public void PopCount_ShouldBe15_Given0111111111111111() { - Assert.AreEqual(15, ((short)0b0111111111111111).PopCount()); + Assert.That(((short)0b0111111111111111).PopCount(), Is.EqualTo(15)); } - [TestMethod] + [Test] public void RotateLeft_ShouldRotateCorrectly() { const short value = 2896; // 00001011 01010000 const short expected = 27137; // 01101010 00000001 - Assert.AreEqual(value, value.RotateLeft(0)); - Assert.AreEqual(expected, value.RotateLeft(5)); - Assert.AreEqual(value, value.RotateLeft(16)); + Assert.That(value.RotateLeft(0), Is.EqualTo(value)); + Assert.That(value.RotateLeft(5), Is.EqualTo(expected)); + Assert.That(value.RotateLeft(16), Is.EqualTo(value)); } - [TestMethod] + [Test] public void RotateLeft_ShouldModForLargeCount() { const short value = 2896; // 00001011 01010000 - Assert.AreEqual(value, value.RotateLeft(16)); + Assert.That(value.RotateLeft(16), Is.EqualTo(value)); } - [TestMethod] + [Test] public void RotateRight_ShouldRotateCorrectly() { const short value = 2896; // 00001011 01010000 const short expected = -32678; // 01111111 10100110 - Assert.AreEqual(value, value.RotateRight(0)); - Assert.AreEqual(expected, value.RotateRight(5)); - Assert.AreEqual(value, value.RotateRight(16)); + Assert.That(value.RotateRight(0), Is.EqualTo(value)); + Assert.That(value.RotateRight(5), Is.EqualTo(expected)); + Assert.That(value.RotateRight(16), Is.EqualTo(value)); } - [TestMethod] + [Test] public void RotateRight_ShouldModForLargeCount() { const short value = 2896; // 00001011 01010000 - Assert.AreEqual(value, value.RotateRight(16)); + Assert.That(value.RotateRight(16), Is.EqualTo(value)); } - [TestMethod] + [Test] public void RoundUpToPowerOf2_ShouldReturnRoundedValue_GivenValue() { - Assert.AreEqual(4, ((short)3).RoundUpToPowerOf2()); - Assert.AreEqual(8, ((short)5).RoundUpToPowerOf2()); - Assert.AreEqual(8, ((short)6).RoundUpToPowerOf2()); - Assert.AreEqual(8, ((short)7).RoundUpToPowerOf2()); + Assert.That(((short)3).RoundUpToPowerOf2(), Is.EqualTo(4)); + Assert.That(((short)5).RoundUpToPowerOf2(), Is.EqualTo(8)); + Assert.That(((short)6).RoundUpToPowerOf2(), Is.EqualTo(8)); + Assert.That(((short)7).RoundUpToPowerOf2(), Is.EqualTo(8)); } - [TestMethod] + [Test] public void RoundUpToPowerOf2_ShouldReturnSameValue_GivenPowerOf2() { for (var i = 0; i < 8; i++) { var value = (short)System.Math.Pow(2, i); - Assert.AreEqual(value, value.RoundUpToPowerOf2()); + Assert.That(value.RoundUpToPowerOf2(), Is.EqualTo(value)); } } - [TestMethod] + [Test] public void RoundUpToPowerOf2_ShouldReturn0_Given0() { - Assert.AreEqual(0, ((short)0).RoundUpToPowerOf2()); + Assert.That(((short)0).RoundUpToPowerOf2(), Is.Zero); } } diff --git a/X10D.Tests/src/Numerics/Int32Tests.cs b/X10D.Tests/src/Numerics/Int32Tests.cs index 121ac68..db0d7a3 100644 --- a/X10D.Tests/src/Numerics/Int32Tests.cs +++ b/X10D.Tests/src/Numerics/Int32Tests.cs @@ -1,85 +1,85 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Numerics; namespace X10D.Tests.Numerics; -[TestClass] +[TestFixture] public class Int32Tests { - [TestMethod] + [Test] public void PopCount_ShouldBe0_Given0() { - Assert.AreEqual(0, ((uint)0).PopCount()); + Assert.That(((uint)0).PopCount(), Is.Zero); } - [TestMethod] + [Test] public void PopCount_ShouldBe5_Given11010101() { - Assert.AreEqual(5, ((uint)0b11010101).PopCount()); + Assert.That(((uint)0b11010101).PopCount(), Is.EqualTo(5)); } - [TestMethod] + [Test] public void PopCount_ShouldBe31_Given11111111111111111111111111111111() { - Assert.AreEqual(31, 0b01111111111111111111111111111111.PopCount()); + Assert.That(0b01111111111111111111111111111111.PopCount(), Is.EqualTo(31)); } - [TestMethod] + [Test] public void RotateLeft_ShouldRotateCorrectly() { const int value = 284719; // 00000000 00000100 01011000 00101111 const int expected = -1336016888; // 10110000 01011110 00000000 00001000 - Assert.AreEqual(value, value.RotateLeft(0)); - Assert.AreEqual(expected, value.RotateLeft(17)); + Assert.That(value.RotateLeft(0), Is.EqualTo(value)); + Assert.That(value.RotateLeft(17), Is.EqualTo(expected)); } - [TestMethod] + [Test] public void RotateLeft_ShouldModForLargeCount() { const int value = 284719; // 00000000 00000100 01011000 00101111 - Assert.AreEqual(value, value.RotateLeft(32)); + Assert.That(value.RotateLeft(32), Is.EqualTo(value)); } - [TestMethod] + [Test] public void RotateRight_ShouldRotateCorrectly() { const int value = 284719; // 00000000 00000100 01011000 00101111 const int expected = 739737602; // 00101100 00010111 10000000 00000010 - Assert.AreEqual(value, value.RotateRight(0)); - Assert.AreEqual(expected, value.RotateRight(17)); + Assert.That(value.RotateRight(0), Is.EqualTo(value)); + Assert.That(value.RotateRight(17), Is.EqualTo(expected)); } - [TestMethod] + [Test] public void RotateRight_ShouldModForLargeCount() { const int value = 284719; // 00000000 00000100 01011000 00101111 - Assert.AreEqual(value, value.RotateRight(32)); + Assert.That(value.RotateRight(32), Is.EqualTo(value)); } - [TestMethod] + [Test] public void RoundUpToPowerOf2_ShouldReturnRoundedValue_GivenValue() { - Assert.AreEqual(4, 3.RoundUpToPowerOf2()); - Assert.AreEqual(8, 5.RoundUpToPowerOf2()); - Assert.AreEqual(8, 6.RoundUpToPowerOf2()); - Assert.AreEqual(8, 7.RoundUpToPowerOf2()); + Assert.That(3.RoundUpToPowerOf2(), Is.EqualTo(4)); + Assert.That(5.RoundUpToPowerOf2(), Is.EqualTo(8)); + Assert.That(6.RoundUpToPowerOf2(), Is.EqualTo(8)); + Assert.That(7.RoundUpToPowerOf2(), Is.EqualTo(8)); } - [TestMethod] + [Test] public void RoundUpToPowerOf2_ShouldReturnSameValue_GivenPowerOf2() { for (var i = 0; i < 8; i++) { var value = (int)System.Math.Pow(2, i); - Assert.AreEqual(value, value.RoundUpToPowerOf2()); + Assert.That(value.RoundUpToPowerOf2(), Is.EqualTo(value)); } } - [TestMethod] + [Test] public void RoundUpToPowerOf2_ShouldReturn0_Given0() { - Assert.AreEqual(0, 0.RoundUpToPowerOf2()); + Assert.That(0.RoundUpToPowerOf2(), Is.Zero); } } diff --git a/X10D.Tests/src/Numerics/Int64Tests.cs b/X10D.Tests/src/Numerics/Int64Tests.cs index d151c6a..e6253ca 100644 --- a/X10D.Tests/src/Numerics/Int64Tests.cs +++ b/X10D.Tests/src/Numerics/Int64Tests.cs @@ -1,85 +1,85 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Numerics; namespace X10D.Tests.Numerics; -[TestClass] +[TestFixture] public class Int64Tests { - [TestMethod] + [Test] public void PopCount_ShouldBe0_Given0() { - Assert.AreEqual(0, 0L.PopCount()); + Assert.That(0L.PopCount(), Is.Zero); } - [TestMethod] + [Test] public void PopCount_ShouldBe5_Given11010101() { - Assert.AreEqual(5, 0b11010101L.PopCount()); + Assert.That(0b11010101L.PopCount(), Is.EqualTo(5)); } - [TestMethod] + [Test] public void PopCount_ShouldBe63_Given0111111111111111111111111111111111111111111111111111111111111111() { - Assert.AreEqual(63, 0b0111111111111111111111111111111111111111111111111111111111111111L.PopCount()); + Assert.That(0b0111111111111111111111111111111111111111111111111111111111111111L.PopCount(), Is.EqualTo(63)); } - [TestMethod] + [Test] public void RotateLeft_ShouldRotateCorrectly() { const long value = 5972019251303316844; // 01010010 11100000 11011111 11011110 00110001 10111010 01111101 01101100 const long expected = -1588168355691398970; // 11101001 11110101 10110001 01001011 10000011 01111111 01111000 11000110 - Assert.AreEqual(value, value.RotateLeft(0)); - Assert.AreEqual(expected, value.RotateLeft(42)); + Assert.That(value.RotateLeft(0), Is.EqualTo(value)); + Assert.That(value.RotateLeft(42), Is.EqualTo(expected)); } - [TestMethod] + [Test] public void RotateLeft_ShouldModForLargeCount() { const long value = 5972019251303316844; // 01010010 11100000 11011111 11011110 00110001 10111010 01111101 01101100 - Assert.AreEqual(value, value.RotateLeft(64)); + Assert.That(value.RotateLeft(64), Is.EqualTo(value)); } - [TestMethod] + [Test] public void RotateRight_ShouldRotateCorrectly() { const long value = 5972019251303316844; // 01010010 11100000 11011111 11011110 00110001 10111010 01111101 01101100 const long expected = -608990218894919625; // 11110111 10001100 01101110 10011111 01011011 00010100 10111000 00110111 - Assert.AreEqual(value, value.RotateRight(0)); - Assert.AreEqual(expected, value.RotateRight(42)); + Assert.That(value.RotateRight(0), Is.EqualTo(value)); + Assert.That(value.RotateRight(42), Is.EqualTo(expected)); } - [TestMethod] + [Test] public void RotateRight_ShouldModForLargeCount() { const long value = 5972019251303316844; // 01010010 11100000 11011111 11011110 00110001 10111010 01111101 01101100 - Assert.AreEqual(value, value.RotateRight(64)); + Assert.That(value.RotateRight(64), Is.EqualTo(value)); } - [TestMethod] + [Test] public void RoundUpToPowerOf2_ShouldReturnRoundedValue_GivenValue() { - Assert.AreEqual(4L, 3L.RoundUpToPowerOf2()); - Assert.AreEqual(8L, 5L.RoundUpToPowerOf2()); - Assert.AreEqual(8L, 6L.RoundUpToPowerOf2()); - Assert.AreEqual(8L, 7L.RoundUpToPowerOf2()); + Assert.That(3L.RoundUpToPowerOf2(), Is.EqualTo(4L)); + Assert.That(5L.RoundUpToPowerOf2(), Is.EqualTo(8L)); + Assert.That(6L.RoundUpToPowerOf2(), Is.EqualTo(8L)); + Assert.That(7L.RoundUpToPowerOf2(), Is.EqualTo(8L)); } - [TestMethod] + [Test] public void RoundUpToPowerOf2_ShouldReturnSameValue_GivenPowerOf2() { for (var i = 0; i < 8; i++) { var value = (long)System.Math.Pow(2, i); - Assert.AreEqual(value, value.RoundUpToPowerOf2()); + Assert.That(value.RoundUpToPowerOf2(), Is.EqualTo(value)); } } - [TestMethod] + [Test] public void RoundUpToPowerOf2_ShouldReturn0_Given0() { - Assert.AreEqual(0L, 0L.RoundUpToPowerOf2()); + Assert.That(0L.RoundUpToPowerOf2(), Is.EqualTo(0L)); } } diff --git a/X10D.Tests/src/Numerics/QuaternionTests.cs b/X10D.Tests/src/Numerics/QuaternionTests.cs index 22e4fec..3d81754 100644 --- a/X10D.Tests/src/Numerics/QuaternionTests.cs +++ b/X10D.Tests/src/Numerics/QuaternionTests.cs @@ -1,13 +1,13 @@ using System.Numerics; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Numerics; namespace X10D.Tests.Numerics; -[TestClass] +[TestFixture] public class QuaternionTests { - [TestMethod] + [Test] public void ToAxisAngle_ShouldGiveAngle180VectorZero_GivenQuaternion() { Vector3 axis = Vector3.UnitY; @@ -15,25 +15,31 @@ public class QuaternionTests var quaternion = Quaternion.CreateFromAxisAngle(axis, angle); (Vector3 Axis, float Angle) axisAngle = quaternion.ToAxisAngle(); - Assert.AreEqual(axis, axisAngle.Axis); - Assert.AreEqual(angle, axisAngle.Angle); + Assert.Multiple(() => + { + Assert.That(axisAngle.Axis, Is.EqualTo(axis)); + Assert.That(axisAngle.Angle, Is.EqualTo(angle)); + }); } - [TestMethod] + [Test] public void ToVector3_ShouldReturnZeroVector_GivenIdentityQuaternion() { - Assert.AreEqual(Vector3.Zero, Quaternion.Identity.ToVector3()); + Assert.That(Quaternion.Identity.ToVector3(), Is.EqualTo(Vector3.Zero)); } - [TestMethod] + [Test] public void ToVector3_ShouldReturnVector_0_PI_0_GivenQuaternionCreatedFrom_PI_0_0() { Quaternion quaternion = Quaternion.CreateFromYawPitchRoll(MathF.PI, 0, 0); var expected = new Vector3(0, MathF.PI, 0); var actual = quaternion.ToVector3(); - - Assert.AreEqual(expected.X, actual.X, 1e-5f); - Assert.AreEqual(expected.Y, actual.Y, 1e-5f); - Assert.AreEqual(expected.Z, actual.Z, 1e-5f); + + Assert.Multiple(() => + { + Assert.That(actual.X, Is.EqualTo(expected.X).Within(1e-5f)); + Assert.That(actual.Y, Is.EqualTo(expected.Y).Within(1e-5f)); + Assert.That(actual.Z, Is.EqualTo(expected.Z).Within(1e-5f)); + }); } } diff --git a/X10D.Tests/src/Numerics/RandomTests.cs b/X10D.Tests/src/Numerics/RandomTests.cs index 3864574..5f70b31 100644 --- a/X10D.Tests/src/Numerics/RandomTests.cs +++ b/X10D.Tests/src/Numerics/RandomTests.cs @@ -1,68 +1,68 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Numerics; namespace X10D.Tests.Numerics; -[TestClass] +[TestFixture] public class RandomTests { - [TestMethod] + [Test] public void NextUnitVector2_ShouldReturnVector_WithMagnitude1() { var random = new Random(); var vector = random.NextUnitVector2(); - Assert.AreEqual(1, vector.Length(), 1e-6); + Assert.That(vector.Length(), Is.EqualTo(1).Within(1e-6)); } - [TestMethod] + [Test] public void NextUnitVector2_ShouldThrow_GivenNullRandom() { - Random? random = null; - Assert.ThrowsException(() => random!.NextUnitVector2()); + Random random = null!; + Assert.Throws(() => random.NextUnitVector2()); } - [TestMethod] + [Test] public void NextUnitVector3_ShouldReturnVector_WithMagnitude1() { var random = new Random(); var vector = random.NextUnitVector3(); - Assert.AreEqual(1, vector.Length(), 1e-6); + Assert.That(vector.Length(), Is.EqualTo(1).Within(1e-6)); } - [TestMethod] + [Test] public void NextUnitVector3_ShouldThrow_GivenNullRandom() { - Random? random = null; - Assert.ThrowsException(() => random!.NextUnitVector3()); + Random random = null!; + Assert.Throws(() => random.NextUnitVector3()); } - [TestMethod] + [Test] public void NextRotation_ShouldReturnQuaternion_WithMagnitude1() { var random = new Random(); var rotation = random.NextRotation(); - Assert.AreEqual(1, rotation.Length(), 1e-6); + Assert.That(rotation.Length(), Is.EqualTo(1).Within(1e-6)); } - [TestMethod] + [Test] public void NextRotation_ShouldThrow_GivenNullRandom() { - Random? random = null; - Assert.ThrowsException(() => random!.NextRotation()); + Random random = null!; + Assert.Throws(() => random.NextRotation()); } - [TestMethod] + [Test] public void NextRotationUniform_ShouldReturnQuaternion_WithMagnitude1() { var random = new Random(); var rotation = random.NextRotationUniform(); - Assert.AreEqual(1, rotation.Length(), 1e-6); + Assert.That(rotation.Length(), Is.EqualTo(1).Within(1e-6)); } - [TestMethod] + [Test] public void NextRotationUniform_ShouldThrow_GivenNullRandom() { - Random? random = null; - Assert.ThrowsException(() => random!.NextRotationUniform()); + Random random = null!; + Assert.Throws(() => random.NextRotationUniform()); } } diff --git a/X10D.Tests/src/Numerics/SByteTests.cs b/X10D.Tests/src/Numerics/SByteTests.cs index b16dbb9..a161831 100644 --- a/X10D.Tests/src/Numerics/SByteTests.cs +++ b/X10D.Tests/src/Numerics/SByteTests.cs @@ -1,86 +1,86 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Numerics; namespace X10D.Tests.Numerics; -[TestClass] +[TestFixture] [CLSCompliant(false)] public class SByteTests { - [TestMethod] + [Test] public void PopCount_ShouldBe0_Given0() { - Assert.AreEqual(0, ((sbyte)0).PopCount()); + Assert.That(((sbyte)0).PopCount(), Is.Zero); } - [TestMethod] + [Test] public void PopCount_ShouldBe4_Given01010101() { - Assert.AreEqual(4, ((sbyte)0b01010101).PopCount()); + Assert.That(((sbyte)0b01010101).PopCount(), Is.EqualTo(4)); } - [TestMethod] + [Test] public void PopCount_ShouldBe7_Given01111111() { - Assert.AreEqual(7, ((sbyte)0b01111111).PopCount()); + Assert.That(((sbyte)0b01111111).PopCount(), Is.EqualTo(7)); } - [TestMethod] + [Test] public void RotateLeft_ShouldRotateCorrectly() { const sbyte value = 117; // 01110101 const sbyte expected = 87; // 01010111 - Assert.AreEqual(value, value.RotateLeft(0)); - Assert.AreEqual(expected, value.RotateLeft(4)); + Assert.That(value.RotateLeft(0), Is.EqualTo(value)); + Assert.That(value.RotateLeft(4), Is.EqualTo(expected)); } - [TestMethod] + [Test] public void RotateLeft_ShouldModForLargeCount() { const sbyte value = 117; // 01110101 - Assert.AreEqual(value, value.RotateLeft(8)); + Assert.That(value.RotateLeft(8), Is.EqualTo(value)); } - [TestMethod] + [Test] public void RotateRight_ShouldRotateCorrectly() { const sbyte value = 117; // 01110101 const sbyte expected = 87; // 01010111 - Assert.AreEqual(value, value.RotateRight(0)); - Assert.AreEqual(expected, value.RotateRight(4)); + Assert.That(value.RotateRight(0), Is.EqualTo(value)); + Assert.That(value.RotateRight(4), Is.EqualTo(expected)); } - [TestMethod] + [Test] public void RotateRight_ShouldModForLargeCount() { const sbyte value = 117; // 01110101 - Assert.AreEqual(value, value.RotateRight(8)); + Assert.That(value.RotateRight(8), Is.EqualTo(value)); } - [TestMethod] + [Test] public void RoundUpToPowerOf2_ShouldReturnRoundedValue_GivenValue() { - Assert.AreEqual(4, ((sbyte)3).RoundUpToPowerOf2()); - Assert.AreEqual(8, ((sbyte)5).RoundUpToPowerOf2()); - Assert.AreEqual(8, ((sbyte)6).RoundUpToPowerOf2()); - Assert.AreEqual(8, ((sbyte)7).RoundUpToPowerOf2()); + Assert.That(((sbyte)3).RoundUpToPowerOf2(), Is.EqualTo(4)); + Assert.That(((sbyte)5).RoundUpToPowerOf2(), Is.EqualTo(8)); + Assert.That(((sbyte)6).RoundUpToPowerOf2(), Is.EqualTo(8)); + Assert.That(((sbyte)7).RoundUpToPowerOf2(), Is.EqualTo(8)); } - [TestMethod] + [Test] public void RoundUpToPowerOf2_ShouldReturnSameValue_GivenPowerOf2() { for (var i = 0; i < 7; i++) { var value = (sbyte)System.Math.Pow(2, i); - Assert.AreEqual(value, value.RoundUpToPowerOf2()); + Assert.That(value.RoundUpToPowerOf2(), Is.EqualTo(value)); } } - [TestMethod] + [Test] public void RoundUpToPowerOf2_ShouldReturn0_Given0() { - Assert.AreEqual(0, ((sbyte)0).RoundUpToPowerOf2()); + Assert.That(((sbyte)0).RoundUpToPowerOf2(), Is.Zero); } } diff --git a/X10D.Tests/src/Numerics/UInt16Tests.cs b/X10D.Tests/src/Numerics/UInt16Tests.cs index 98072d1..89553d7 100644 --- a/X10D.Tests/src/Numerics/UInt16Tests.cs +++ b/X10D.Tests/src/Numerics/UInt16Tests.cs @@ -1,88 +1,88 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Numerics; namespace X10D.Tests.Numerics; -[TestClass] +[TestFixture] [CLSCompliant(false)] public class UInt16Tests { - [TestMethod] + [Test] public void PopCount_ShouldBe0_Given0() { - Assert.AreEqual(0, ((ushort)0).PopCount()); + Assert.That(((ushort)0).PopCount(), Is.Zero); } - [TestMethod] + [Test] public void PopCount_ShouldBe5_Given11010101() { - Assert.AreEqual(5, ((ushort)0b11010101).PopCount()); + Assert.That(((ushort)0b11010101).PopCount(), Is.EqualTo(5)); } - [TestMethod] + [Test] public void PopCount_ShouldBe16_Given1111111111111111() { - Assert.AreEqual(16, ((ushort)0b1111111111111111).PopCount()); + Assert.That(((ushort)0b1111111111111111).PopCount(), Is.EqualTo(16)); } - [TestMethod] + [Test] public void RotateLeft_ShouldRotateCorrectly() { const ushort value = 2896; // 00001011 01010000 const ushort expected = 27137; // 01101010 00000001 - Assert.AreEqual(value, value.RotateLeft(0)); - Assert.AreEqual(expected, value.RotateLeft(5)); - Assert.AreEqual(value, value.RotateLeft(16)); + Assert.That(value.RotateLeft(0), Is.EqualTo(value)); + Assert.That(value.RotateLeft(5), Is.EqualTo(expected)); + Assert.That(value.RotateLeft(16), Is.EqualTo(value)); } - [TestMethod] + [Test] public void RotateLeft_ShouldModForLargeCount() { const ushort value = 2896; // 00001011 01010000 - Assert.AreEqual(value, value.RotateLeft(16)); + Assert.That(value.RotateLeft(16), Is.EqualTo(value)); } - [TestMethod] + [Test] public void RotateRight_ShouldRotateCorrectly() { const ushort value = 2896; // 00001011 01010000 const ushort expected = 32858; // 10000000 01011010 - Assert.AreEqual(value, value.RotateRight(0)); - Assert.AreEqual(expected, value.RotateRight(5)); - Assert.AreEqual(value, value.RotateRight(16)); + Assert.That(value.RotateRight(0), Is.EqualTo(value)); + Assert.That(value.RotateRight(5), Is.EqualTo(expected)); + Assert.That(value.RotateRight(16), Is.EqualTo(value)); } - [TestMethod] + [Test] public void RotateRight_ShouldModForLargeCount() { const ushort value = 2896; // 00001011 01010000 - Assert.AreEqual(value, value.RotateRight(16)); + Assert.That(value.RotateRight(16), Is.EqualTo(value)); } - [TestMethod] + [Test] public void RoundUpToPowerOf2_ShouldReturnRoundedValue_GivenValue() { - Assert.AreEqual(4U, ((ushort)3).RoundUpToPowerOf2()); - Assert.AreEqual(8U, ((ushort)5).RoundUpToPowerOf2()); - Assert.AreEqual(8U, ((ushort)6).RoundUpToPowerOf2()); - Assert.AreEqual(8U, ((ushort)7).RoundUpToPowerOf2()); + Assert.That(((ushort)3).RoundUpToPowerOf2(), Is.EqualTo(4U)); + Assert.That(((ushort)5).RoundUpToPowerOf2(), Is.EqualTo(8U)); + Assert.That(((ushort)6).RoundUpToPowerOf2(), Is.EqualTo(8U)); + Assert.That(((ushort)7).RoundUpToPowerOf2(), Is.EqualTo(8U)); } - [TestMethod] + [Test] public void RoundUpToPowerOf2_ShouldReturnSameValue_GivenPowerOf2() { for (var i = 0; i < 8; i++) { var value = (ushort)System.Math.Pow(2, i); - Assert.AreEqual(value, value.RoundUpToPowerOf2()); + Assert.That(value.RoundUpToPowerOf2(), Is.EqualTo(value)); } } - [TestMethod] + [Test] public void RoundUpToPowerOf2_ShouldReturn0_Given0() { - Assert.AreEqual(0U, ((ushort)0).RoundUpToPowerOf2()); + Assert.That(((ushort)0).RoundUpToPowerOf2(), Is.EqualTo(0U)); } } diff --git a/X10D.Tests/src/Numerics/UInt32Tests.cs b/X10D.Tests/src/Numerics/UInt32Tests.cs index dbaae05..eb15df5 100644 --- a/X10D.Tests/src/Numerics/UInt32Tests.cs +++ b/X10D.Tests/src/Numerics/UInt32Tests.cs @@ -1,86 +1,86 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Numerics; namespace X10D.Tests.Numerics; -[TestClass] +[TestFixture] [CLSCompliant(false)] public class UInt32Tests { - [TestMethod] + [Test] public void PopCount_ShouldBe0_Given0() { - Assert.AreEqual(0, 0U.PopCount()); + Assert.That(0U.PopCount(), Is.Zero); } - [TestMethod] + [Test] public void PopCount_ShouldBe5_Given11010101() { - Assert.AreEqual(5, 0b11010101U.PopCount()); + Assert.That(0b11010101U.PopCount(), Is.EqualTo(5)); } - [TestMethod] + [Test] public void PopCount_ShouldBe32_Given11111111111111111111111111111111() { - Assert.AreEqual(32, 0b11111111111111111111111111111111U.PopCount()); + Assert.That(0b11111111111111111111111111111111U.PopCount(), Is.EqualTo(32)); } - [TestMethod] + [Test] public void RotateLeft_ShouldRotateCorrectly() { const uint value = 284719; // 00000000 00000100 01011000 00101111 const uint expected = 2958950408; // 10110000 01011110 00000000 00001000 - Assert.AreEqual(value, value.RotateLeft(0)); - Assert.AreEqual(expected, value.RotateLeft(17)); + Assert.That(value.RotateLeft(0), Is.EqualTo(value)); + Assert.That(value.RotateLeft(17), Is.EqualTo(expected)); } - [TestMethod] + [Test] public void RotateLeft_ShouldModForLargeCount() { const uint value = 284719; // 00000000 00000100 01011000 00101111 - Assert.AreEqual(value, value.RotateLeft(32)); + Assert.That(value.RotateLeft(32), Is.EqualTo(value)); } - [TestMethod] + [Test] public void RotateRight_ShouldRotateCorrectly() { const uint value = 284719; // 00000000 00000100 01011000 00101111 const uint expected = 739737602; // 00101100 00010111 10000000 00000010 - Assert.AreEqual(value, value.RotateRight(0)); - Assert.AreEqual(expected, value.RotateRight(17)); + Assert.That(value.RotateRight(0), Is.EqualTo(value)); + Assert.That(value.RotateRight(17), Is.EqualTo(expected)); } - [TestMethod] + [Test] public void RotateRight_ShouldModForLargeCount() { const uint value = 284719; // 00000000 00000100 01011000 00101111 - Assert.AreEqual(value, value.RotateRight(32)); + Assert.That(value.RotateRight(32), Is.EqualTo(value)); } - [TestMethod] + [Test] public void RoundUpToPowerOf2_ShouldReturnRoundedValue_GivenValue() { - Assert.AreEqual(4U, 3U.RoundUpToPowerOf2()); - Assert.AreEqual(8U, 5U.RoundUpToPowerOf2()); - Assert.AreEqual(8U, 6U.RoundUpToPowerOf2()); - Assert.AreEqual(8U, 7U.RoundUpToPowerOf2()); + Assert.That(3U.RoundUpToPowerOf2(), Is.EqualTo(4U)); + Assert.That(5U.RoundUpToPowerOf2(), Is.EqualTo(8U)); + Assert.That(6U.RoundUpToPowerOf2(), Is.EqualTo(8U)); + Assert.That(7U.RoundUpToPowerOf2(), Is.EqualTo(8U)); } - [TestMethod] + [Test] public void RoundUpToPowerOf2_ShouldReturnSameValue_GivenPowerOf2() { for (var i = 0; i < 8; i++) { var value = (uint)System.Math.Pow(2, i); - Assert.AreEqual(value, value.RoundUpToPowerOf2()); + Assert.That(value.RoundUpToPowerOf2(), Is.EqualTo(value)); } } - [TestMethod] + [Test] public void RoundUpToPowerOf2_ShouldReturn0_Given0() { - Assert.AreEqual(0U, 0U.RoundUpToPowerOf2()); + Assert.That(0U.RoundUpToPowerOf2(), Is.EqualTo(0U)); } } diff --git a/X10D.Tests/src/Numerics/UInt64Tests.cs b/X10D.Tests/src/Numerics/UInt64Tests.cs index 41211dc..7663aa3 100644 --- a/X10D.Tests/src/Numerics/UInt64Tests.cs +++ b/X10D.Tests/src/Numerics/UInt64Tests.cs @@ -1,86 +1,86 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Numerics; namespace X10D.Tests.Numerics; -[TestClass] +[TestFixture] [CLSCompliant(false)] public class UInt64Tests { - [TestMethod] + [Test] public void PopCount_ShouldBe0_Given0() { - Assert.AreEqual(0, 0UL.PopCount()); + Assert.That(0UL.PopCount(), Is.Zero); } - [TestMethod] + [Test] public void PopCount_ShouldBe5_Given11010101() { - Assert.AreEqual(5, 0b11010101UL.PopCount()); + Assert.That(0b11010101UL.PopCount(), Is.EqualTo(5)); } - [TestMethod] + [Test] public void PopCount_ShouldBe64_Given1111111111111111111111111111111111111111111111111111111111111111() { - Assert.AreEqual(64, 0b1111111111111111111111111111111111111111111111111111111111111111UL.PopCount()); + Assert.That(0b1111111111111111111111111111111111111111111111111111111111111111UL.PopCount(), Is.EqualTo(64)); } - [TestMethod] + [Test] public void RotateLeft_ShouldRotateCorrectly() { const ulong value = 5972019251303316844; // 01010010 11100000 11011111 11011110 00110001 10111010 01111101 01101100 const ulong expected = 16858575718018152646; // 11101001 11110101 10110001 01001011 10000011 01111111 01111000 11000110 - Assert.AreEqual(value, value.RotateLeft(0)); - Assert.AreEqual(expected, value.RotateLeft(42)); + Assert.That(value.RotateLeft(0), Is.EqualTo(value)); + Assert.That(value.RotateLeft(42), Is.EqualTo(expected)); } - [TestMethod] + [Test] public void RotateLeft_ShouldModForLargeCount() { const ulong value = 5972019251303316844; // 01010010 11100000 11011111 11011110 00110001 10111010 01111101 01101100 - Assert.AreEqual(value, value.RotateLeft(64)); + Assert.That(value.RotateLeft(64), Is.EqualTo(value)); } - [TestMethod] + [Test] public void RotateRight_ShouldRotateCorrectly() { const ulong value = 5972019251303316844; // 01010010 11100000 11011111 11011110 00110001 10111010 01111101 01101100 const ulong expected = 17837753854814631991; // 11110111 10001100 01101110 10011111 01011011 00010100 10111000 00110111 - Assert.AreEqual(value, value.RotateRight(0)); - Assert.AreEqual(expected, value.RotateRight(42)); + Assert.That(value.RotateRight(0), Is.EqualTo(value)); + Assert.That(value.RotateRight(42), Is.EqualTo(expected)); } - [TestMethod] + [Test] public void RotateRight_ShouldModForLargeCount() { const ulong value = 5972019251303316844; // 01010010 11100000 11011111 11011110 00110001 10111010 01111101 01101100 - Assert.AreEqual(value, value.RotateRight(64)); + Assert.That(value.RotateRight(64), Is.EqualTo(value)); } - [TestMethod] + [Test] public void RoundUpToPowerOf2_ShouldReturnRoundedValue_GivenValue() { - Assert.AreEqual(4UL, 3UL.RoundUpToPowerOf2()); - Assert.AreEqual(8UL, 5UL.RoundUpToPowerOf2()); - Assert.AreEqual(8UL, 6UL.RoundUpToPowerOf2()); - Assert.AreEqual(8UL, 7UL.RoundUpToPowerOf2()); + Assert.That(3UL.RoundUpToPowerOf2(), Is.EqualTo(4UL)); + Assert.That(5UL.RoundUpToPowerOf2(), Is.EqualTo(8UL)); + Assert.That(6UL.RoundUpToPowerOf2(), Is.EqualTo(8UL)); + Assert.That(7UL.RoundUpToPowerOf2(), Is.EqualTo(8UL)); } - [TestMethod] + [Test] public void RoundUpToPowerOf2_ShouldReturnSameValue_GivenPowerOf2() { for (var i = 0; i < 8; i++) { var value = (ulong)System.Math.Pow(2, i); - Assert.AreEqual(value, value.RoundUpToPowerOf2()); + Assert.That(value.RoundUpToPowerOf2(), Is.EqualTo(value)); } } - [TestMethod] + [Test] public void RoundUpToPowerOf2_ShouldReturn0_Given0() { - Assert.AreEqual(0UL, 0UL.RoundUpToPowerOf2()); + Assert.That(0UL.RoundUpToPowerOf2(), Is.EqualTo(0UL)); } } diff --git a/X10D.Tests/src/Numerics/Vector2Tests.cs b/X10D.Tests/src/Numerics/Vector2Tests.cs index a0497e8..cef7bc7 100644 --- a/X10D.Tests/src/Numerics/Vector2Tests.cs +++ b/X10D.Tests/src/Numerics/Vector2Tests.cs @@ -1,5 +1,5 @@ using System.Numerics; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; #if !NET6_0_OR_GREATER using X10D.Core; #endif @@ -8,20 +8,23 @@ using X10D.Numerics; namespace X10D.Tests.Numerics; -[TestClass] +[TestFixture] public class Vector2Tests { - [TestMethod] + [Test] public void Deconstruct_ShouldReturnCorrectValues() { var vector = new Vector2(1, 2); (float x, float y) = vector; - Assert.AreEqual(1, x); - Assert.AreEqual(2, y); + Assert.Multiple(() => + { + Assert.That(x, Is.EqualTo(1)); + Assert.That(y, Is.EqualTo(2)); + }); } - [TestMethod] + [Test] public void IsOnLine_ShouldReturnTrue_ForPointOnLine() { Vector2 start = Vector2.Zero; @@ -29,12 +32,15 @@ public class Vector2Tests Vector2 point = new Vector2(0.5f, 0.0f); var line = new LineF(start, end); - Assert.IsTrue(point.IsOnLine(line)); - Assert.IsTrue(point.IsOnLine(line.Start, line.End)); - Assert.IsTrue(point.IsOnLine(line.Start.ToVector2(), line.End.ToVector2())); + Assert.Multiple(() => + { + Assert.That(point.IsOnLine(line)); + Assert.That(point.IsOnLine(line.Start, line.End)); + Assert.That(point.IsOnLine(line.Start.ToVector2(), line.End.ToVector2())); + }); } - [TestMethod] + [Test] public void IsOnLine_ShouldReturnFalse_ForPointNotOnLine() { Vector2 start = Vector2.Zero; @@ -42,78 +48,99 @@ public class Vector2Tests Vector2 point = new Vector2(0.5f, 1.0f); var line = new LineF(start, end); - Assert.IsFalse(point.IsOnLine(line)); - Assert.IsFalse(point.IsOnLine(line.Start, line.End)); - Assert.IsFalse(point.IsOnLine(line.Start.ToVector2(), line.End.ToVector2())); + Assert.Multiple(() => + { + Assert.That(point.IsOnLine(line), Is.False); + Assert.That(point.IsOnLine(line.Start, line.End), Is.False); + Assert.That(point.IsOnLine(line.Start.ToVector2(), line.End.ToVector2()), Is.False); + }); } - [TestMethod] + [Test] public void Round_ShouldRoundToNearestInteger_GivenNoParameters() { var vector = new Vector2(1.5f, 2.6f); var rounded = vector.Round(); - Assert.AreEqual(2, rounded.X); - Assert.AreEqual(3, rounded.Y); + Assert.Multiple(() => + { + Assert.That(rounded.X, Is.EqualTo(2)); + Assert.That(rounded.Y, Is.EqualTo(3)); + }); } - [TestMethod] + [Test] public void Round_ShouldRoundToNearest10_GivenPrecision10() { var vector = new Vector2(1.5f, 25.2f); var rounded = vector.Round(10); - Assert.AreEqual(0, rounded.X); - Assert.AreEqual(30, rounded.Y); + Assert.Multiple(() => + { + Assert.That(rounded.X, Is.Zero); + Assert.That(rounded.Y, Is.EqualTo(30)); + }); } - [TestMethod] + [Test] public void ToPointF_ShouldReturnPoint_WithEquivalentMembers() { var random = new Random(); var vector = new Vector2(random.NextSingle(), random.NextSingle()); var point = vector.ToPointF(); - Assert.AreEqual(vector.X, point.X, 1e-6f); - Assert.AreEqual(vector.Y, point.Y, 1e-6f); + Assert.Multiple(() => + { + Assert.That(point.X, Is.EqualTo(vector.X).Within(1e-6f)); + Assert.That(point.Y, Is.EqualTo(vector.Y).Within(1e-6f)); + }); } - [TestMethod] + [Test] public void ToSizeF_ShouldReturnSize_WithEquivalentMembers() { var random = new Random(); var vector = new Vector2(random.NextSingle(), random.NextSingle()); var size = vector.ToSizeF(); - Assert.AreEqual(vector.X, size.Width); - Assert.AreEqual(vector.Y, size.Height); + Assert.Multiple(() => + { + Assert.That(size.Width, Is.EqualTo(vector.X)); + Assert.That(size.Height, Is.EqualTo(vector.Y)); + }); } - [TestMethod] + [Test] public void WithX_ShouldReturnVectorWithNewX_GivenVector() { - Assert.AreEqual(Vector2.UnitY, Vector2.One.WithX(0)); - Assert.AreEqual(Vector2.Zero, Vector2.Zero.WithX(0)); - Assert.AreEqual(Vector2.Zero, Vector2.UnitX.WithX(0)); - Assert.AreEqual(Vector2.UnitY, Vector2.UnitY.WithX(0)); + Assert.Multiple(() => + { + Assert.That(Vector2.One.WithX(0), Is.EqualTo(Vector2.UnitY)); + Assert.That(Vector2.Zero.WithX(0), Is.EqualTo(Vector2.Zero)); + Assert.That(Vector2.UnitX.WithX(0), Is.EqualTo(Vector2.Zero)); + Assert.That(Vector2.UnitY.WithX(0), Is.EqualTo(Vector2.UnitY)); - Assert.AreEqual(Vector2.One, Vector2.One.WithX(1)); - Assert.AreEqual(Vector2.UnitX, Vector2.Zero.WithX(1)); - Assert.AreEqual(Vector2.UnitX, Vector2.UnitX.WithX(1)); - Assert.AreEqual(Vector2.One, Vector2.UnitY.WithX(1)); + Assert.That(Vector2.One.WithX(1), Is.EqualTo(Vector2.One)); + Assert.That(Vector2.Zero.WithX(1), Is.EqualTo(Vector2.UnitX)); + Assert.That(Vector2.UnitX.WithX(1), Is.EqualTo(Vector2.UnitX)); + Assert.That(Vector2.UnitY.WithX(1), Is.EqualTo(Vector2.One)); + }); } - [TestMethod] + [Test] public void WithY_ShouldReturnVectorWithNewY_GivenVector() { - Assert.AreEqual(Vector2.UnitX, Vector2.One.WithY(0)); - Assert.AreEqual(Vector2.Zero, Vector2.Zero.WithY(0)); - Assert.AreEqual(Vector2.UnitX, Vector2.UnitX.WithY(0)); - Assert.AreEqual(Vector2.Zero, Vector2.UnitY.WithY(0)); + Assert.Multiple(() => + { + Assert.That(Vector2.One.WithY(0), Is.EqualTo(Vector2.UnitX)); + Assert.That(Vector2.Zero.WithY(0), Is.EqualTo(Vector2.Zero)); + Assert.That(Vector2.UnitX.WithY(0), Is.EqualTo(Vector2.UnitX)); + Assert.That(Vector2.UnitY.WithY(0), Is.EqualTo(Vector2.Zero)); - Assert.AreEqual(Vector2.One, Vector2.One.WithY(1)); - Assert.AreEqual(Vector2.UnitY, Vector2.Zero.WithY(1)); - Assert.AreEqual(Vector2.One, Vector2.UnitX.WithY(1)); - Assert.AreEqual(Vector2.UnitY, Vector2.UnitY.WithY(1)); + Assert.That(Vector2.One.WithY(1), Is.EqualTo(Vector2.One)); + Assert.That(Vector2.Zero.WithY(1), Is.EqualTo(Vector2.UnitY)); + Assert.That(Vector2.UnitX.WithY(1), Is.EqualTo(Vector2.One)); + Assert.That(Vector2.UnitY.WithY(1), Is.EqualTo(Vector2.UnitY)); + }); } } diff --git a/X10D.Tests/src/Numerics/Vector3Tests.cs b/X10D.Tests/src/Numerics/Vector3Tests.cs index 10b1ad0..402f94b 100644 --- a/X10D.Tests/src/Numerics/Vector3Tests.cs +++ b/X10D.Tests/src/Numerics/Vector3Tests.cs @@ -1,90 +1,108 @@ using System.Numerics; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Numerics; namespace X10D.Tests.Numerics; -[TestClass] +[TestFixture] public class Vector3Tests { - [TestMethod] + [Test] public void Deconstruct_ShouldReturnCorrectValues() { var vector = new Vector3(1, 2, 3); (float x, float y, float z) = vector; - Assert.AreEqual(1, x); - Assert.AreEqual(2, y); - Assert.AreEqual(3, z); + Assert.Multiple(() => + { + Assert.That(x, Is.EqualTo(1)); + Assert.That(y, Is.EqualTo(2)); + Assert.That(z, Is.EqualTo(3)); + }); } - [TestMethod] + [Test] public void Round_ShouldRoundToNearestInteger_GivenNoParameters() { var vector = new Vector3(1.5f, 2.6f, -5.2f); var rounded = vector.Round(); - Assert.AreEqual(2, rounded.X); - Assert.AreEqual(3, rounded.Y); - Assert.AreEqual(-5, rounded.Z); + Assert.Multiple(() => + { + Assert.That(rounded.X, Is.EqualTo(2)); + Assert.That(rounded.Y, Is.EqualTo(3)); + Assert.That(rounded.Z, Is.EqualTo(-5)); + }); } - [TestMethod] + [Test] public void Round_ShouldRoundToNearest10_GivenPrecision10() { var vector = new Vector3(1.5f, 25.2f, -12.5f); var rounded = vector.Round(10); - Assert.AreEqual(0, rounded.X); - Assert.AreEqual(30, rounded.Y); - Assert.AreEqual(-10, rounded.Z); + Assert.Multiple(() => + { + Assert.That(rounded.X, Is.Zero); + Assert.That(rounded.Y, Is.EqualTo(30)); + Assert.That(rounded.Z, Is.EqualTo(-10)); + }); } - [TestMethod] + [Test] public void WithX_ShouldReturnVectorWithNewX_GivenVector() { - Assert.AreEqual(new Vector3(0, 1, 1), Vector3.One.WithX(0)); - Assert.AreEqual(Vector3.Zero, Vector3.Zero.WithX(0)); - Assert.AreEqual(Vector3.Zero, Vector3.UnitX.WithX(0)); - Assert.AreEqual(Vector3.UnitY, Vector3.UnitY.WithX(0)); - Assert.AreEqual(Vector3.UnitZ, Vector3.UnitZ.WithX(0)); + Assert.Multiple(() => + { + Assert.That(Vector3.One.WithX(0), Is.EqualTo(new Vector3(0, 1, 1))); + Assert.That(Vector3.Zero.WithX(0), Is.EqualTo(Vector3.Zero)); + Assert.That(Vector3.UnitX.WithX(0), Is.EqualTo(Vector3.Zero)); + Assert.That(Vector3.UnitY.WithX(0), Is.EqualTo(Vector3.UnitY)); + Assert.That(Vector3.UnitZ.WithX(0), Is.EqualTo(Vector3.UnitZ)); - Assert.AreEqual(Vector3.One, Vector3.One.WithX(1)); - Assert.AreEqual(Vector3.UnitX, Vector3.Zero.WithX(1)); - Assert.AreEqual(Vector3.UnitX, Vector3.UnitX.WithX(1)); - Assert.AreEqual(new Vector3(1, 1, 0), Vector3.UnitY.WithX(1)); - Assert.AreEqual(new Vector3(1, 0, 1), Vector3.UnitZ.WithX(1)); + Assert.That(Vector3.One.WithX(1), Is.EqualTo(Vector3.One)); + Assert.That(Vector3.Zero.WithX(1), Is.EqualTo(Vector3.UnitX)); + Assert.That(Vector3.UnitX.WithX(1), Is.EqualTo(Vector3.UnitX)); + Assert.That(Vector3.UnitY.WithX(1), Is.EqualTo(new Vector3(1, 1, 0))); + Assert.That(Vector3.UnitZ.WithX(1), Is.EqualTo(new Vector3(1, 0, 1))); + }); } - [TestMethod] + [Test] public void WithY_ShouldReturnVectorWithNewY_GivenVector() { - Assert.AreEqual(new Vector3(1, 0, 1), Vector3.One.WithY(0)); - Assert.AreEqual(Vector3.Zero, Vector3.Zero.WithY(0)); - Assert.AreEqual(Vector3.UnitX, Vector3.UnitX.WithY(0)); - Assert.AreEqual(Vector3.Zero, Vector3.UnitY.WithY(0)); - Assert.AreEqual(Vector3.UnitZ, Vector3.UnitZ.WithY(0)); + Assert.Multiple(() => + { + Assert.That(Vector3.One.WithY(0), Is.EqualTo(new Vector3(1, 0, 1))); + Assert.That(Vector3.Zero.WithY(0), Is.EqualTo(Vector3.Zero)); + Assert.That(Vector3.UnitX.WithY(0), Is.EqualTo(Vector3.UnitX)); + Assert.That(Vector3.UnitY.WithY(0), Is.EqualTo(Vector3.Zero)); + Assert.That(Vector3.UnitZ.WithY(0), Is.EqualTo(Vector3.UnitZ)); - Assert.AreEqual(Vector3.One, Vector3.One.WithY(1)); - Assert.AreEqual(Vector3.UnitY, Vector3.Zero.WithY(1)); - Assert.AreEqual(new Vector3(1, 1, 0), Vector3.UnitX.WithY(1)); - Assert.AreEqual(Vector3.UnitY, Vector3.UnitY.WithY(1)); - Assert.AreEqual(new Vector3(0, 1, 1), Vector3.UnitZ.WithY(1)); + Assert.That(Vector3.One.WithY(1), Is.EqualTo(Vector3.One)); + Assert.That(Vector3.Zero.WithY(1), Is.EqualTo(Vector3.UnitY)); + Assert.That(Vector3.UnitX.WithY(1), Is.EqualTo(new Vector3(1, 1, 0))); + Assert.That(Vector3.UnitY.WithY(1), Is.EqualTo(Vector3.UnitY)); + Assert.That(Vector3.UnitZ.WithY(1), Is.EqualTo(new Vector3(0, 1, 1))); + }); } - [TestMethod] + [Test] public void WithZ_ShouldReturnVectorWithNewZ_GivenVector() { - Assert.AreEqual(new Vector3(1, 1, 0), Vector3.One.WithZ(0)); - Assert.AreEqual(Vector3.Zero, Vector3.Zero.WithZ(0)); - Assert.AreEqual(Vector3.UnitX, Vector3.UnitX.WithZ(0)); - Assert.AreEqual(Vector3.UnitY, Vector3.UnitY.WithZ(0)); - Assert.AreEqual(Vector3.Zero, Vector3.UnitZ.WithZ(0)); + Assert.Multiple(() => + { + Assert.That(Vector3.One.WithZ(0), Is.EqualTo(new Vector3(1, 1, 0))); + Assert.That(Vector3.Zero.WithZ(0), Is.EqualTo(Vector3.Zero)); + Assert.That(Vector3.UnitX.WithZ(0), Is.EqualTo(Vector3.UnitX)); + Assert.That(Vector3.UnitY.WithZ(0), Is.EqualTo(Vector3.UnitY)); + Assert.That(Vector3.UnitZ.WithZ(0), Is.EqualTo(Vector3.Zero)); - Assert.AreEqual(Vector3.One, Vector3.One.WithZ(1)); - Assert.AreEqual(Vector3.UnitZ, Vector3.Zero.WithZ(1)); - Assert.AreEqual(new Vector3(1, 0, 1), Vector3.UnitX.WithZ(1)); - Assert.AreEqual(new Vector3(0, 1, 1), Vector3.UnitY.WithZ(1)); - Assert.AreEqual(Vector3.UnitZ, Vector3.UnitZ.WithZ(1)); + Assert.That(Vector3.One.WithZ(1), Is.EqualTo(Vector3.One)); + Assert.That(Vector3.Zero.WithZ(1), Is.EqualTo(Vector3.UnitZ)); + Assert.That(Vector3.UnitX.WithZ(1), Is.EqualTo(new Vector3(1, 0, 1))); + Assert.That(Vector3.UnitY.WithZ(1), Is.EqualTo(new Vector3(0, 1, 1))); + Assert.That(Vector3.UnitZ.WithZ(1), Is.EqualTo(Vector3.UnitZ)); + }); } } diff --git a/X10D.Tests/src/Numerics/Vector4Tests.cs b/X10D.Tests/src/Numerics/Vector4Tests.cs index 88dbac7..3c1ba1f 100644 --- a/X10D.Tests/src/Numerics/Vector4Tests.cs +++ b/X10D.Tests/src/Numerics/Vector4Tests.cs @@ -1,117 +1,138 @@ using System.Numerics; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Numerics; namespace X10D.Tests.Numerics; -[TestClass] +[TestFixture] public class Vector4Tests { - [TestMethod] + [Test] public void Deconstruct_ShouldReturnCorrectValues() { var vector = new Vector4(1, 2, 3, 4); (float x, float y, float z, float w) = vector; - Assert.AreEqual(1, x); - Assert.AreEqual(2, y); - Assert.AreEqual(3, z); - Assert.AreEqual(4, w); + Assert.Multiple(() => + { + Assert.That(x, Is.EqualTo(1)); + Assert.That(y, Is.EqualTo(2)); + Assert.That(z, Is.EqualTo(3)); + Assert.That(w, Is.EqualTo(4)); + }); } - [TestMethod] + [Test] public void Round_ShouldRoundToNearestInteger_GivenNoParameters() { var vector = new Vector4(1.5f, 2.6f, -5.2f, 0.3f); var rounded = vector.Round(); - Assert.AreEqual(2, rounded.X); - Assert.AreEqual(3, rounded.Y); - Assert.AreEqual(-5, rounded.Z); - Assert.AreEqual(0, rounded.W); + Assert.Multiple(() => + { + Assert.That(rounded.X, Is.EqualTo(2)); + Assert.That(rounded.Y, Is.EqualTo(3)); + Assert.That(rounded.Z, Is.EqualTo(-5)); + Assert.That(rounded.W, Is.Zero); + }); } - [TestMethod] + [Test] public void Round_ShouldRoundToNearest10_GivenPrecision10() { var vector = new Vector4(1.5f, 25.2f, -12.5f, 101.2f); var rounded = vector.Round(10); - Assert.AreEqual(0, rounded.X); - Assert.AreEqual(30, rounded.Y); - Assert.AreEqual(-10, rounded.Z); - Assert.AreEqual(100, rounded.W); + Assert.Multiple(() => + { + Assert.That(rounded.X, Is.Zero); + Assert.That(rounded.Y, Is.EqualTo(30)); + Assert.That(rounded.Z, Is.EqualTo(-10)); + Assert.That(rounded.W, Is.EqualTo(100)); + }); } - [TestMethod] + [Test] public void WithW_ShouldReturnVectorWithNewW_GivenVector() { - Assert.AreEqual(new Vector4(1, 1, 1, 0), Vector4.One.WithW(0)); - Assert.AreEqual(Vector4.Zero, Vector4.Zero.WithW(0)); - Assert.AreEqual(Vector4.Zero, Vector4.UnitW.WithW(0)); - Assert.AreEqual(Vector4.UnitX, Vector4.UnitX.WithW(0)); - Assert.AreEqual(Vector4.UnitY, Vector4.UnitY.WithW(0)); - Assert.AreEqual(Vector4.UnitZ, Vector4.UnitZ.WithW(0)); + Assert.Multiple(() => + { + Assert.That(Vector4.One.WithW(0), Is.EqualTo(new Vector4(1, 1, 1, 0))); + Assert.That(Vector4.Zero.WithW(0), Is.EqualTo(Vector4.Zero)); + Assert.That(Vector4.UnitW.WithW(0), Is.EqualTo(Vector4.Zero)); + Assert.That(Vector4.UnitX.WithW(0), Is.EqualTo(Vector4.UnitX)); + Assert.That(Vector4.UnitY.WithW(0), Is.EqualTo(Vector4.UnitY)); + Assert.That(Vector4.UnitZ.WithW(0), Is.EqualTo(Vector4.UnitZ)); - Assert.AreEqual(Vector4.One, Vector4.One.WithW(1)); - Assert.AreEqual(Vector4.UnitW, Vector4.Zero.WithW(1)); - Assert.AreEqual(Vector4.UnitW, Vector4.UnitW.WithW(1)); - Assert.AreEqual(new Vector4(1, 0, 0, 1), Vector4.UnitX.WithW(1)); - Assert.AreEqual(new Vector4(0, 1, 0, 1), Vector4.UnitY.WithW(1)); - Assert.AreEqual(new Vector4(0, 0, 1, 1), Vector4.UnitZ.WithW(1)); + Assert.That(Vector4.One.WithW(1), Is.EqualTo(Vector4.One)); + Assert.That(Vector4.Zero.WithW(1), Is.EqualTo(Vector4.UnitW)); + Assert.That(Vector4.UnitW.WithW(1), Is.EqualTo(Vector4.UnitW)); + Assert.That(Vector4.UnitX.WithW(1), Is.EqualTo(new Vector4(1, 0, 0, 1))); + Assert.That(Vector4.UnitY.WithW(1), Is.EqualTo(new Vector4(0, 1, 0, 1))); + Assert.That(Vector4.UnitZ.WithW(1), Is.EqualTo(new Vector4(0, 0, 1, 1))); + }); } - [TestMethod] + [Test] public void WithX_ShouldReturnVectorWithNewX_GivenVector() { - Assert.AreEqual(new Vector4(0, 1, 1, 1), Vector4.One.WithX(0)); - Assert.AreEqual(Vector4.Zero, Vector4.Zero.WithX(0)); - Assert.AreEqual(Vector4.UnitW, Vector4.UnitW.WithX(0)); - Assert.AreEqual(Vector4.Zero, Vector4.UnitX.WithX(0)); - Assert.AreEqual(Vector4.UnitY, Vector4.UnitY.WithX(0)); - Assert.AreEqual(Vector4.UnitZ, Vector4.UnitZ.WithX(0)); + Assert.Multiple(() => + { + Assert.That(Vector4.One.WithX(0), Is.EqualTo(new Vector4(0, 1, 1, 1))); + Assert.That(Vector4.Zero.WithX(0), Is.EqualTo(Vector4.Zero)); + Assert.That(Vector4.UnitW.WithX(0), Is.EqualTo(Vector4.UnitW)); + Assert.That(Vector4.UnitX.WithX(0), Is.EqualTo(Vector4.Zero)); + Assert.That(Vector4.UnitY.WithX(0), Is.EqualTo(Vector4.UnitY)); + Assert.That(Vector4.UnitZ.WithX(0), Is.EqualTo(Vector4.UnitZ)); - Assert.AreEqual(Vector4.One, Vector4.One.WithX(1)); - Assert.AreEqual(Vector4.UnitX, Vector4.Zero.WithX(1)); - Assert.AreEqual(new Vector4(1, 0, 0, 1), Vector4.UnitW.WithX(1)); - Assert.AreEqual(Vector4.UnitX, Vector4.UnitX.WithX(1)); - Assert.AreEqual(new Vector4(1, 1, 0, 0), Vector4.UnitY.WithX(1)); - Assert.AreEqual(new Vector4(1, 0, 1, 0), Vector4.UnitZ.WithX(1)); + Assert.That(Vector4.One.WithX(1), Is.EqualTo(Vector4.One)); + Assert.That(Vector4.Zero.WithX(1), Is.EqualTo(Vector4.UnitX)); + Assert.That(Vector4.UnitW.WithX(1), Is.EqualTo(new Vector4(1, 0, 0, 1))); + Assert.That(Vector4.UnitX.WithX(1), Is.EqualTo(Vector4.UnitX)); + Assert.That(Vector4.UnitY.WithX(1), Is.EqualTo(new Vector4(1, 1, 0, 0))); + Assert.That(Vector4.UnitZ.WithX(1), Is.EqualTo(new Vector4(1, 0, 1, 0))); + }); } - [TestMethod] + [Test] public void WithY_ShouldReturnVectorWithNewY_GivenVector() { - Assert.AreEqual(new Vector4(1, 0, 1, 1), Vector4.One.WithY(0)); - Assert.AreEqual(Vector4.Zero, Vector4.Zero.WithY(0)); - Assert.AreEqual(Vector4.UnitW, Vector4.UnitW.WithY(0)); - Assert.AreEqual(Vector4.UnitX, Vector4.UnitX.WithY(0)); - Assert.AreEqual(Vector4.Zero, Vector4.UnitY.WithY(0)); - Assert.AreEqual(Vector4.UnitZ, Vector4.UnitZ.WithY(0)); + Assert.Multiple(() => + { + Assert.That(Vector4.One.WithY(0), Is.EqualTo(new Vector4(1, 0, 1, 1))); + Assert.That(Vector4.Zero.WithY(0), Is.EqualTo(Vector4.Zero)); + Assert.That(Vector4.UnitW.WithY(0), Is.EqualTo(Vector4.UnitW)); + Assert.That(Vector4.UnitX.WithY(0), Is.EqualTo(Vector4.UnitX)); + Assert.That(Vector4.UnitY.WithY(0), Is.EqualTo(Vector4.Zero)); + Assert.That(Vector4.UnitZ.WithY(0), Is.EqualTo(Vector4.UnitZ)); - Assert.AreEqual(Vector4.One, Vector4.One.WithY(1)); - Assert.AreEqual(Vector4.UnitY, Vector4.Zero.WithY(1)); - Assert.AreEqual(new Vector4(0, 1, 0, 1), Vector4.UnitW.WithY(1)); - Assert.AreEqual(new Vector4(1, 1, 0, 0), Vector4.UnitX.WithY(1)); - Assert.AreEqual(Vector4.UnitY, Vector4.UnitY.WithY(1)); - Assert.AreEqual(new Vector4(0, 1, 1, 0), Vector4.UnitZ.WithY(1)); + Assert.That(Vector4.One.WithY(1), Is.EqualTo(Vector4.One)); + Assert.That(Vector4.Zero.WithY(1), Is.EqualTo(Vector4.UnitY)); + Assert.That(Vector4.UnitW.WithY(1), Is.EqualTo(new Vector4(0, 1, 0, 1))); + Assert.That(Vector4.UnitX.WithY(1), Is.EqualTo(new Vector4(1, 1, 0, 0))); + Assert.That(Vector4.UnitY.WithY(1), Is.EqualTo(Vector4.UnitY)); + Assert.That(Vector4.UnitZ.WithY(1), Is.EqualTo(new Vector4(0, 1, 1, 0))); + }); } - [TestMethod] + [Test] public void WithZ_ShouldReturnVectorWithNewZ_GivenVector() { - Assert.AreEqual(new Vector4(1, 1, 0, 1), Vector4.One.WithZ(0)); - Assert.AreEqual(Vector4.Zero, Vector4.Zero.WithZ(0)); - Assert.AreEqual(Vector4.UnitW, Vector4.UnitW.WithZ(0)); - Assert.AreEqual(Vector4.UnitX, Vector4.UnitX.WithZ(0)); - Assert.AreEqual(Vector4.UnitY, Vector4.UnitY.WithZ(0)); - Assert.AreEqual(Vector4.Zero, Vector4.UnitZ.WithZ(0)); + Assert.Multiple(() => + { + Assert.That(Vector4.One.WithZ(0), Is.EqualTo(new Vector4(1, 1, 0, 1))); + Assert.That(Vector4.Zero.WithZ(0), Is.EqualTo(Vector4.Zero)); + Assert.That(Vector4.UnitW.WithZ(0), Is.EqualTo(Vector4.UnitW)); + Assert.That(Vector4.UnitX.WithZ(0), Is.EqualTo(Vector4.UnitX)); + Assert.That(Vector4.UnitY.WithZ(0), Is.EqualTo(Vector4.UnitY)); + Assert.That(Vector4.UnitZ.WithZ(0), Is.EqualTo(Vector4.Zero)); - Assert.AreEqual(Vector4.One, Vector4.One.WithZ(1)); - Assert.AreEqual(Vector4.UnitZ, Vector4.Zero.WithZ(1)); - Assert.AreEqual(new Vector4(0, 0, 1, 1), Vector4.UnitW.WithZ(1)); - Assert.AreEqual(new Vector4(1, 0, 1, 0), Vector4.UnitX.WithZ(1)); - Assert.AreEqual(new Vector4(0, 1, 1, 0), Vector4.UnitY.WithZ(1)); - Assert.AreEqual(Vector4.UnitZ, Vector4.UnitZ.WithZ(1)); + Assert.That(Vector4.One.WithZ(1), Is.EqualTo(Vector4.One)); + Assert.That(Vector4.Zero.WithZ(1), Is.EqualTo(Vector4.UnitZ)); + Assert.That(Vector4.UnitW.WithZ(1), Is.EqualTo(new Vector4(0, 0, 1, 1))); + Assert.That(Vector4.UnitX.WithZ(1), Is.EqualTo(new Vector4(1, 0, 1, 0))); + Assert.That(Vector4.UnitY.WithZ(1), Is.EqualTo(new Vector4(0, 1, 1, 0))); + Assert.That(Vector4.UnitZ.WithZ(1), Is.EqualTo(Vector4.UnitZ)); + }); } } diff --git a/X10D.Tests/src/Reflection/MemberInfoTests.cs b/X10D.Tests/src/Reflection/MemberInfoTests.cs index 1774b36..5f6e2cb 100644 --- a/X10D.Tests/src/Reflection/MemberInfoTests.cs +++ b/X10D.Tests/src/Reflection/MemberInfoTests.cs @@ -1,83 +1,94 @@ using System.Reflection; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Reflection; namespace X10D.Tests.Reflection; -[TestClass] +[TestFixture] public class MemberInfoTests { - [TestMethod] + [Test] public void HasCustomAttribute_ShouldBeTrue_GivenCLSCompliantAttributeOnUnsignedTypes() { - Assert.IsTrue(typeof(sbyte).HasCustomAttribute(typeof(CLSCompliantAttribute))); // okay, sbyte is signed. I know. - Assert.IsTrue(typeof(ushort).HasCustomAttribute(typeof(CLSCompliantAttribute))); - Assert.IsTrue(typeof(uint).HasCustomAttribute(typeof(CLSCompliantAttribute))); - Assert.IsTrue(typeof(ulong).HasCustomAttribute(typeof(CLSCompliantAttribute))); + Assert.That(typeof(sbyte).HasCustomAttribute(typeof(CLSCompliantAttribute))); // okay, sbyte is signed. I know. + Assert.That(typeof(ushort).HasCustomAttribute(typeof(CLSCompliantAttribute))); + Assert.That(typeof(uint).HasCustomAttribute(typeof(CLSCompliantAttribute))); + Assert.That(typeof(ulong).HasCustomAttribute(typeof(CLSCompliantAttribute))); } - [TestMethod] + [Test] public void HasCustomAttribute_ShouldBeTrue_GivenCLSCompliantAttributeOnUnsignedTypes_Generic() { - Assert.IsTrue(typeof(sbyte).HasCustomAttribute()); // okay, sbyte is signed. I know. - Assert.IsTrue(typeof(ushort).HasCustomAttribute()); - Assert.IsTrue(typeof(uint).HasCustomAttribute()); - Assert.IsTrue(typeof(ulong).HasCustomAttribute()); + Assert.That(typeof(sbyte).HasCustomAttribute()); // seriously don't @ me + Assert.That(typeof(ushort).HasCustomAttribute()); + Assert.That(typeof(uint).HasCustomAttribute()); + Assert.That(typeof(ulong).HasCustomAttribute()); } - [TestMethod] + [Test] public void HasCustomAttribute_ShouldThrow_GivenNull() { - Type? type = null; - Assert.ThrowsException(() => type!.HasCustomAttribute()); - Assert.ThrowsException(() => type!.HasCustomAttribute(typeof(CLSCompliantAttribute))); - - Assert.ThrowsException(() => typeof(object).HasCustomAttribute(null!)); + Type type = null!; + Assert.Throws(() => _ = type.HasCustomAttribute()); + Assert.Throws(() => _ = type.HasCustomAttribute(typeof(CLSCompliantAttribute))); + Assert.Throws(() => _ = typeof(object).HasCustomAttribute(null!)); } - [TestMethod] + [Test] public void HasCustomAttribute_ShouldThrow_GivenNonAttribute() { - Assert.ThrowsException(() => typeof(object).HasCustomAttribute(typeof(object))); + Assert.Throws(() => _ = typeof(object).HasCustomAttribute(typeof(object))); } - [TestMethod] + [Test] public void SelectFromCustomAttribute_ShouldBeFalse_GivenCLSCompliantAttributeOnUnsignedTypes() { - Assert.IsFalse(typeof(sbyte).SelectFromCustomAttribute((CLSCompliantAttribute attribute) => attribute.IsCompliant)); - Assert.IsFalse(typeof(ushort).SelectFromCustomAttribute((CLSCompliantAttribute attribute) => attribute.IsCompliant)); - Assert.IsFalse(typeof(uint).SelectFromCustomAttribute((CLSCompliantAttribute attribute) => attribute.IsCompliant)); - Assert.IsFalse(typeof(ulong).SelectFromCustomAttribute((CLSCompliantAttribute attribute) => attribute.IsCompliant)); + Func predicate = attribute => attribute.IsCompliant; + Assert.Multiple(() => + { + Assert.That(typeof(sbyte).SelectFromCustomAttribute(predicate), Is.False); + Assert.That(typeof(ushort).SelectFromCustomAttribute(predicate), Is.False); + Assert.That(typeof(uint).SelectFromCustomAttribute(predicate), Is.False); + Assert.That(typeof(ulong).SelectFromCustomAttribute(predicate), Is.False); + }); } - [TestMethod] + [Test] public void SelectFromCustomAttribute_ShouldBeTrue_GivenCLSCompliantAttributeOnSignedTypes() { - Assert.IsTrue(typeof(byte).SelectFromCustomAttribute((CLSCompliantAttribute attribute) => attribute.IsCompliant, true)); - Assert.IsTrue(typeof(short).SelectFromCustomAttribute((CLSCompliantAttribute attribute) => attribute.IsCompliant, true)); - Assert.IsTrue(typeof(int).SelectFromCustomAttribute((CLSCompliantAttribute attribute) => attribute.IsCompliant, true)); - Assert.IsTrue(typeof(long).SelectFromCustomAttribute((CLSCompliantAttribute attribute) => attribute.IsCompliant, true)); + Func predicate = attribute => attribute.IsCompliant; + Assert.Multiple(() => + { + Assert.That(typeof(byte).SelectFromCustomAttribute(predicate)); + Assert.That(typeof(short).SelectFromCustomAttribute(predicate)); + Assert.That(typeof(int).SelectFromCustomAttribute(predicate)); + Assert.That(typeof(long).SelectFromCustomAttribute(predicate)); + }); } - [TestMethod] + [Test] public void SelectFromCustomAttribute_ShouldThrow_GivenNull() { Type? type = null; - Assert.ThrowsException(() => - (type!.SelectFromCustomAttribute((CLSCompliantAttribute attribute) => attribute.IsCompliant))); + Assert.Throws(() => + { + _ = type!.SelectFromCustomAttribute((CLSCompliantAttribute attribute) => attribute.IsCompliant); + }); - Assert.ThrowsException(() => - (type!.SelectFromCustomAttribute((CLSCompliantAttribute attribute) => attribute.IsCompliant, true))); + Assert.Throws(() => + { + _ = type!.SelectFromCustomAttribute((CLSCompliantAttribute attribute) => attribute.IsCompliant, true); + }); const BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static; var memberInfo = typeof(int).GetMembers(bindingFlags)[0]; Func? selector = null; - Assert.ThrowsException(() => typeof(int).SelectFromCustomAttribute(selector!)); - Assert.ThrowsException(() => typeof(int).SelectFromCustomAttribute(selector!, default)); - Assert.ThrowsException(() => memberInfo.SelectFromCustomAttribute(selector!)); - Assert.ThrowsException(() => memberInfo.SelectFromCustomAttribute(selector!, default)); + Assert.Throws(() => typeof(int).SelectFromCustomAttribute(selector!)); + Assert.Throws(() => typeof(int).SelectFromCustomAttribute(selector!, default)); + Assert.Throws(() => memberInfo.SelectFromCustomAttribute(selector!)); + Assert.Throws(() => memberInfo.SelectFromCustomAttribute(selector!, default)); } } diff --git a/X10D.Tests/src/Reflection/TypeTests.cs b/X10D.Tests/src/Reflection/TypeTests.cs index f76b7fd..0dc24a1 100644 --- a/X10D.Tests/src/Reflection/TypeTests.cs +++ b/X10D.Tests/src/Reflection/TypeTests.cs @@ -1,61 +1,61 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Reflection; namespace X10D.Tests.Reflection; -[TestClass] +[TestFixture] public class TypeTests { - [TestMethod] + [Test] public void Inherits_ShouldBeTrue_GivenStringInheritsObject() { - Assert.IsTrue(typeof(string).Inherits(typeof(object))); - Assert.IsTrue(typeof(string).Inherits()); + Assert.That(typeof(string).Inherits(typeof(object))); + Assert.That(typeof(string).Inherits()); } - [TestMethod] + [Test] public void Inherits_ShouldBeFalse_GivenObjectInheritsString() { - Assert.IsFalse(typeof(object).Inherits(typeof(string))); - Assert.IsFalse(typeof(object).Inherits()); + Assert.That(typeof(object).Inherits(typeof(string)), Is.False); + Assert.That(typeof(object).Inherits(), Is.False); } - [TestMethod] + [Test] public void Inherits_ShouldThrow_GivenValueType() { - Assert.ThrowsException(() => typeof(int).Inherits(typeof(object))); - Assert.ThrowsException(() => typeof(object).Inherits(typeof(int))); + Assert.Throws(() => typeof(int).Inherits(typeof(object))); + Assert.Throws(() => typeof(object).Inherits(typeof(int))); } - [TestMethod] + [Test] public void Inherits_ShouldThrow_GivenNull() { - Assert.ThrowsException(() => typeof(object).Inherits(null!)); - Assert.ThrowsException(() => ((Type?)null)!.Inherits(typeof(object))); - Assert.ThrowsException(() => ((Type?)null)!.Inherits()); + Assert.Throws(() => typeof(object).Inherits(null!)); + Assert.Throws(() => ((Type?)null)!.Inherits(typeof(object))); + Assert.Throws(() => ((Type?)null)!.Inherits()); } - [TestMethod] + [Test] public void Implements_ShouldBeTrue_GivenInt32ImplementsIComparable() { - Assert.IsTrue(typeof(int).Implements()); - Assert.IsTrue(typeof(int).Implements>()); - Assert.IsTrue(typeof(int).Implements(typeof(IComparable))); - Assert.IsTrue(typeof(int).Implements(typeof(IComparable))); + Assert.That(typeof(int).Implements()); + Assert.That(typeof(int).Implements>()); + Assert.That(typeof(int).Implements(typeof(IComparable))); + Assert.That(typeof(int).Implements(typeof(IComparable))); } - [TestMethod] + [Test] public void Implements_ShouldThrow_GivenNull() { - Assert.ThrowsException(() => typeof(object).Implements(null!)); - Assert.ThrowsException(() => ((Type?)null)!.Implements(typeof(IComparable))); - Assert.ThrowsException(() => ((Type?)null)!.Implements()); + Assert.Throws(() => typeof(object).Implements(null!)); + Assert.Throws(() => ((Type?)null)!.Implements(typeof(IComparable))); + Assert.Throws(() => ((Type?)null)!.Implements()); } - [TestMethod] + [Test] public void Implements_ShouldThrow_GivenNonInterface() { - Assert.ThrowsException(() => typeof(string).Implements()); - Assert.ThrowsException(() => typeof(string).Implements(typeof(object))); + Assert.Throws(() => typeof(string).Implements()); + Assert.Throws(() => typeof(string).Implements(typeof(object))); } } diff --git a/X10D.Tests/src/Text/CharSpanTests.cs b/X10D.Tests/src/Text/CharSpanTests.cs index fd32588..27d9dc5 100644 --- a/X10D.Tests/src/Text/CharSpanTests.cs +++ b/X10D.Tests/src/Text/CharSpanTests.cs @@ -1,63 +1,63 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Text; namespace X10D.Tests.Text; -[TestClass] +[TestFixture] public class CharSpanTests { - [TestMethod] + [Test] public void CountSubstring_ShouldHonor_StringComparison() { var readOnlySpan = "Hello World".AsSpan(); Span span = stackalloc char[readOnlySpan.Length]; readOnlySpan.CopyTo(span); - Assert.AreEqual(0, readOnlySpan.CountSubstring('E')); - Assert.AreEqual(0, readOnlySpan.CountSubstring("E".AsSpan())); - Assert.AreEqual(1, readOnlySpan.CountSubstring("E".AsSpan(), StringComparison.OrdinalIgnoreCase)); + Assert.That(readOnlySpan.CountSubstring('E'), Is.Zero); + Assert.That(readOnlySpan.CountSubstring("E".AsSpan()), Is.Zero); + Assert.That(readOnlySpan.CountSubstring("E".AsSpan(), StringComparison.OrdinalIgnoreCase), Is.EqualTo(1)); - Assert.AreEqual(0, span.CountSubstring('E')); - Assert.AreEqual(0, span.CountSubstring("E".AsSpan())); - Assert.AreEqual(1, span.CountSubstring("E".AsSpan(), StringComparison.OrdinalIgnoreCase)); + Assert.That(span.CountSubstring('E'), Is.Zero); + Assert.That(span.CountSubstring("E".AsSpan()), Is.Zero); + Assert.That(span.CountSubstring("E".AsSpan(), StringComparison.OrdinalIgnoreCase), Is.EqualTo(1)); } - [TestMethod] + [Test] public void CountSubstring_ShouldReturn0_GivenNoInstanceChar() { var readOnlySpan = "Hello World".AsSpan(); Span span = stackalloc char[readOnlySpan.Length]; readOnlySpan.CopyTo(span); - Assert.AreEqual(0, readOnlySpan.CountSubstring('z')); - Assert.AreEqual(0, readOnlySpan.CountSubstring("z".AsSpan())); - Assert.AreEqual(0, readOnlySpan.CountSubstring("z".AsSpan(), StringComparison.OrdinalIgnoreCase)); + Assert.That(readOnlySpan.CountSubstring('z'), Is.Zero); + Assert.That(readOnlySpan.CountSubstring("z".AsSpan()), Is.Zero); + Assert.That(readOnlySpan.CountSubstring("z".AsSpan(), StringComparison.OrdinalIgnoreCase), Is.Zero); - Assert.AreEqual(0, span.CountSubstring('z')); - Assert.AreEqual(0, span.CountSubstring("z".AsSpan())); - Assert.AreEqual(0, span.CountSubstring("z".AsSpan(), StringComparison.OrdinalIgnoreCase)); + Assert.That(span.CountSubstring('z'), Is.Zero); + Assert.That(span.CountSubstring("z".AsSpan()), Is.Zero); + Assert.That(span.CountSubstring("z".AsSpan(), StringComparison.OrdinalIgnoreCase), Is.Zero); } - [TestMethod] + [Test] public void CountSubstring_ShouldReturn1_GivenSingleInstanceChar() { var readOnlySpan = "Hello World".AsSpan(); Span span = stackalloc char[readOnlySpan.Length]; readOnlySpan.CopyTo(span); - Assert.AreEqual(1, readOnlySpan.CountSubstring('e')); - Assert.AreEqual(1, readOnlySpan.CountSubstring("e".AsSpan())); - Assert.AreEqual(1, readOnlySpan.CountSubstring("e".AsSpan(), StringComparison.OrdinalIgnoreCase)); + Assert.That(readOnlySpan.CountSubstring('e'), Is.EqualTo(1)); + Assert.That(readOnlySpan.CountSubstring("e".AsSpan()), Is.EqualTo(1)); + Assert.That(readOnlySpan.CountSubstring("e".AsSpan(), StringComparison.OrdinalIgnoreCase), Is.EqualTo(1)); - Assert.AreEqual(1, span.CountSubstring('e')); - Assert.AreEqual(1, span.CountSubstring("e".AsSpan())); - Assert.AreEqual(1, span.CountSubstring("e".AsSpan(), StringComparison.OrdinalIgnoreCase)); + Assert.That(span.CountSubstring('e'), Is.EqualTo(1)); + Assert.That(span.CountSubstring("e".AsSpan()), Is.EqualTo(1)); + Assert.That(span.CountSubstring("e".AsSpan(), StringComparison.OrdinalIgnoreCase), Is.EqualTo(1)); } - [TestMethod] + [Test] public void CountSubstring_ShouldReturn0_GivenEmptyHaystack() { - Assert.AreEqual(0, string.Empty.AsSpan().CountSubstring('\0')); - Assert.AreEqual(0, string.Empty.AsSpan().CountSubstring(string.Empty.AsSpan(), StringComparison.OrdinalIgnoreCase)); + Assert.That(string.Empty.AsSpan().CountSubstring('\0'), Is.Zero); + Assert.That(string.Empty.AsSpan().CountSubstring(string.Empty.AsSpan(), StringComparison.OrdinalIgnoreCase), Is.Zero); } } diff --git a/X10D.Tests/src/Text/CharTests.cs b/X10D.Tests/src/Text/CharTests.cs index 7ace536..602acba 100644 --- a/X10D.Tests/src/Text/CharTests.cs +++ b/X10D.Tests/src/Text/CharTests.cs @@ -1,56 +1,56 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Text; namespace X10D.Tests.Text; -[TestClass] +[TestFixture] public class CharTests { - [TestMethod] + [Test] public void IsEmoji_ShouldReturnTrue_GivenBasicEmoji() { - Assert.IsTrue('✂'.IsEmoji()); - Assert.IsTrue('✅'.IsEmoji()); - Assert.IsTrue('❎'.IsEmoji()); - Assert.IsTrue('➕'.IsEmoji()); - Assert.IsTrue('➖'.IsEmoji()); + Assert.That('✂'.IsEmoji()); + Assert.That('✅'.IsEmoji()); + Assert.That('❎'.IsEmoji()); + Assert.That('➕'.IsEmoji()); + Assert.That('➖'.IsEmoji()); } - [TestMethod] + [Test] public void IsEmoji_ShouldReturnFalse_GivenNonEmoji() { for (var letter = 'A'; letter <= 'Z'; letter++) { - Assert.IsFalse(letter.IsEmoji()); + Assert.That(letter.IsEmoji(), Is.False); } } - [TestMethod] + [Test] public void RepeatShouldBeCorrect() { const string expected = "aaaaaaaaaa"; string actual = 'a'.Repeat(10); - Assert.AreEqual(expected, actual); + Assert.That(actual, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void RepeatOneCountShouldBeLength1String() { string repeated = 'a'.Repeat(1); - Assert.AreEqual(1, repeated.Length); - Assert.AreEqual("a", repeated); + Assert.That(repeated.Length, Is.EqualTo(1)); + Assert.That(repeated, Is.EqualTo("a")); } - [TestMethod] + [Test] public void RepeatZeroCountShouldBeEmpty() { - Assert.AreEqual(string.Empty, 'a'.Repeat(0)); + Assert.That('a'.Repeat(0), Is.EqualTo(string.Empty)); } - [TestMethod] + [Test] public void RepeatNegativeCountShouldThrow() { - Assert.ThrowsException(() => 'a'.Repeat(-1)); + Assert.Throws(() => 'a'.Repeat(-1)); } } diff --git a/X10D.Tests/src/Text/CoreTests.cs b/X10D.Tests/src/Text/CoreTests.cs index 6c4c58a..4ed8903 100644 --- a/X10D.Tests/src/Text/CoreTests.cs +++ b/X10D.Tests/src/Text/CoreTests.cs @@ -1,21 +1,21 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Text; namespace X10D.Tests.Text; -[TestClass] +[TestFixture] public class CoreTests { #if NET5_0_OR_GREATER - [TestMethod] + [Test] public void ToJsonShouldNotBeEmpty() { object? obj = null; string json = obj.ToJson(); - Assert.IsFalse(string.IsNullOrEmpty(json)); + Assert.That(string.IsNullOrEmpty(json), Is.False); } - [TestMethod] + [Test] public void ToJsonShouldDeserializeEquivalent() { int[] source = Enumerable.Range(1, 100).ToArray(); diff --git a/X10D.Tests/src/Text/EnumerableTests.cs b/X10D.Tests/src/Text/EnumerableTests.cs index 8a73cb3..a7b7c86 100644 --- a/X10D.Tests/src/Text/EnumerableTests.cs +++ b/X10D.Tests/src/Text/EnumerableTests.cs @@ -1,12 +1,12 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Text; namespace X10D.Tests.Text; -[TestClass] +[TestFixture] public class EnumerableTests { - [TestMethod] + [Test] public void Grep_ShouldFilterCorrectly_GivenPattern() { int year = DateTime.Now.Year; @@ -19,7 +19,7 @@ public class EnumerableTests CollectionAssert.AreEqual(expectedResult, actualResult); } - [TestMethod] + [Test] public void Grep_ShouldYieldNoResults_GivenEmptySource() { string[] source = Array.Empty(); @@ -31,7 +31,7 @@ public class EnumerableTests CollectionAssert.AreEqual(expectedResult, actualResult); } - [TestMethod] + [Test] public void Grep_ShouldMatchUpperCase_GivenIgnoreCaseTrue() { int year = DateTime.Now.Year; @@ -44,7 +44,7 @@ public class EnumerableTests CollectionAssert.AreEqual(expectedResult, actualResult); } - [TestMethod] + [Test] public void Grep_ShouldNotMatchUpperCase_GivenIgnoreCaseFalse() { int year = DateTime.Now.Year; @@ -53,26 +53,26 @@ public class EnumerableTests const string pattern = /*lang=regex*/@"world"; string[] actualResult = source.Grep(pattern, false).ToArray(); - Assert.AreEqual(0, actualResult.Length); + Assert.That(actualResult.Length, Is.Zero); } - [TestMethod] + [Test] public void Grep_ShouldThrowArgumentNullException_GivenNullPattern() { IEnumerable source = Enumerable.Empty(); - Assert.ThrowsException(() => source.Grep(null!).ToArray()); - Assert.ThrowsException(() => source.Grep(null!, false).ToArray()); + Assert.Throws(() => source.Grep(null!).ToArray()); + Assert.Throws(() => source.Grep(null!, false).ToArray()); } - [TestMethod] + [Test] public void Grep_ShouldThrowArgumentNullException_GivenNullSource() { IEnumerable source = null!; - Assert.ThrowsException(() => source.Grep("foo").ToArray()); - Assert.ThrowsException(() => source.Grep("foo", false).ToArray()); + Assert.Throws(() => source.Grep("foo").ToArray()); + Assert.Throws(() => source.Grep("foo", false).ToArray()); } - [TestMethod] + [Test] public void Grep_ShouldYieldNoElements_GivenNoMatchingStrings() { var source = new[] {"Hello", "World", "String"}; @@ -80,6 +80,6 @@ public class EnumerableTests const string pattern = /*lang=regex*/@"[0-9]+"; string[] actualResult = source.Grep(pattern).ToArray(); - Assert.AreEqual(0, actualResult.Length); + Assert.That(actualResult.Length, Is.Zero); } } diff --git a/X10D.Tests/src/Text/RuneTests.cs b/X10D.Tests/src/Text/RuneTests.cs index 48e7501..d5a6946 100644 --- a/X10D.Tests/src/Text/RuneTests.cs +++ b/X10D.Tests/src/Text/RuneTests.cs @@ -1,93 +1,93 @@ #if NET5_0_OR_GREATER using System.Text; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Text; namespace X10D.Tests.Text; -[TestClass] +[TestFixture] public class RuneTests { - [TestMethod] + [Test] public void IsEmoji_ShouldReturnTrue_GivenBasicEmoji() { - Assert.IsTrue(new Rune('✂').IsEmoji()); - Assert.IsTrue(new Rune('✅').IsEmoji()); - Assert.IsTrue(new Rune('❎').IsEmoji()); - Assert.IsTrue(new Rune('➕').IsEmoji()); - Assert.IsTrue(new Rune('➖').IsEmoji()); + Assert.That(new Rune('✂').IsEmoji()); + Assert.That(new Rune('✅').IsEmoji()); + Assert.That(new Rune('❎').IsEmoji()); + Assert.That(new Rune('➕').IsEmoji()); + Assert.That(new Rune('➖').IsEmoji()); } - [TestMethod] + [Test] public void IsEmoji_ShouldReturnFalse_GivenNonEmoji() { for (var letter = 'A'; letter <= 'Z'; letter++) { - Assert.IsFalse(new Rune(letter).IsEmoji()); + Assert.That(new Rune(letter).IsEmoji(), Is.False); } } - [TestMethod] + [Test] public void Repeat_ShouldRepeatRune_GivenValidCount() { const string expected = "aaaaaaaaaa"; var rune = new Rune('a'); string actual = rune.Repeat(10); - Assert.AreEqual(expected, actual); + Assert.That(actual, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void Repeat_ShouldReturnStringOfLength1_GivenCountOf1() { string repeated = new Rune('a').Repeat(1); - Assert.AreEqual(1, repeated.Length); - Assert.AreEqual("a", repeated); + Assert.That(repeated.Length, Is.EqualTo(1)); + Assert.That(repeated, Is.EqualTo("a")); } - [TestMethod] + [Test] public void Repeat_ShouldThrowArgumentOutOfRangeException_GivenNegativeCount() { var rune = new Rune('a'); - Assert.ThrowsException(() => rune.Repeat(-1)); + Assert.Throws(() => rune.Repeat(-1)); } - [TestMethod] + [Test] public void Repeat_ShouldReturnEmptyString_GivenCountOf0() { - Assert.AreEqual(string.Empty, new Rune('a').Repeat(0)); + Assert.That(new Rune('a').Repeat(0), Is.EqualTo(string.Empty)); } - [TestMethod] + [Test] public void RepeatCodepoint_0000_007F_ShouldReturnString() { string repeated = new Rune(69).Repeat(16); - Assert.AreEqual(16, repeated.Length); - Assert.AreEqual("EEEEEEEEEEEEEEEE", repeated); + Assert.That(repeated.Length, Is.EqualTo(16)); + Assert.That(repeated, Is.EqualTo("EEEEEEEEEEEEEEEE")); } - [TestMethod] + [Test] public void RepeatCodepoint_0080_07FF_ShouldReturnString() { string repeated = new Rune(192).Repeat(8); - Assert.AreEqual(8, repeated.Length); - Assert.AreEqual("ÀÀÀÀÀÀÀÀ", repeated); + Assert.That(repeated.Length, Is.EqualTo(8)); + Assert.That(repeated, Is.EqualTo("ÀÀÀÀÀÀÀÀ")); } - [TestMethod] + [Test] public void RepeatCodepoint_0800_FFFF_ShouldReturnString() { string repeated = new Rune(0x0800).Repeat(5); - Assert.AreEqual(5, repeated.Length); - Assert.AreEqual("ࠀࠀࠀࠀࠀ", repeated); + Assert.That(repeated.Length, Is.EqualTo(5)); + Assert.That(repeated, Is.EqualTo("ࠀࠀࠀࠀࠀ")); } - [TestMethod] + [Test] public void RepeatCodepointBeyondU10000ShouldReturnString() { string repeated = new Rune('\uD800', '\uDC00').Repeat(6); - Assert.AreEqual(12, repeated.Length); - Assert.AreEqual("𐀀𐀀𐀀𐀀𐀀𐀀", repeated); + Assert.That(repeated.Length, Is.EqualTo(12)); + Assert.That(repeated, Is.EqualTo("𐀀𐀀𐀀𐀀𐀀𐀀")); } } #endif diff --git a/X10D.Tests/src/Text/StringBuilderReaderTests.cs b/X10D.Tests/src/Text/StringBuilderReaderTests.cs index bdd0848..b6557ad 100644 --- a/X10D.Tests/src/Text/StringBuilderReaderTests.cs +++ b/X10D.Tests/src/Text/StringBuilderReaderTests.cs @@ -1,71 +1,71 @@ using System.Text; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Text; namespace X10D.Tests.Text; -[TestClass] +[TestFixture] public class StringBuilderReaderTests { - [TestMethod] + [Test] public void Peek_ShouldReturnNextChar_GivenBuilder() { using var reader = new StringBuilderReader(new StringBuilder("Hello\nWorld")); - Assert.AreEqual('H', reader.Peek()); + Assert.That(reader.Peek(), Is.EqualTo('H')); reader.Close(); } - [TestMethod] + [Test] public void Read_ShouldReturnNextChar_GivenBuilder() { using var reader = new StringBuilderReader(new StringBuilder("Hello\nWorld")); - Assert.AreEqual('H', reader.Read()); - Assert.AreEqual('e', reader.Read()); - Assert.AreEqual('l', reader.Read()); - Assert.AreEqual('l', reader.Read()); - Assert.AreEqual('o', reader.Read()); - Assert.AreEqual('\n', reader.Read()); - Assert.AreEqual('W', reader.Read()); - Assert.AreEqual('o', reader.Read()); - Assert.AreEqual('r', reader.Read()); - Assert.AreEqual('l', reader.Read()); - Assert.AreEqual('d', reader.Read()); - Assert.AreEqual(-1, reader.Read()); + Assert.That(reader.Read(), Is.EqualTo('H')); + Assert.That(reader.Read(), Is.EqualTo('e')); + Assert.That(reader.Read(), Is.EqualTo('l')); + Assert.That(reader.Read(), Is.EqualTo('l')); + Assert.That(reader.Read(), Is.EqualTo('o')); + Assert.That(reader.Read(), Is.EqualTo('\n')); + Assert.That(reader.Read(), Is.EqualTo('W')); + Assert.That(reader.Read(), Is.EqualTo('o')); + Assert.That(reader.Read(), Is.EqualTo('r')); + Assert.That(reader.Read(), Is.EqualTo('l')); + Assert.That(reader.Read(), Is.EqualTo('d')); + Assert.That(reader.Read(), Is.EqualTo(-1)); reader.Close(); } - [TestMethod] + [Test] public void Read_ShouldPopulateArray_GivenBuilder() { using var reader = new StringBuilderReader(new StringBuilder("Hello\nWorld")); var array = new char[5]; int read = reader.Read(array, 0, 5); - Assert.AreEqual(5, read); + Assert.That(read, Is.EqualTo(5)); CollectionAssert.AreEqual("Hello".ToCharArray(), array); reader.Close(); } - [TestMethod] + [Test] public void Read_ShouldReturnNegative1_GivenEndOfReader() { using var reader = new StringBuilderReader(new StringBuilder("Hello\nWorld")); var array = new char[11]; reader.Read(array); - Assert.AreEqual(-1, reader.Read(array, 0, 1)); + Assert.That(reader.Read(array, 0, 1), Is.EqualTo(-1)); reader.Close(); } - [TestMethod] + [Test] public void Read_ShouldThrow_GivenNullArray() { - Assert.ThrowsException(() => + Assert.Throws(() => { using var reader = new StringBuilderReader(new StringBuilder("Hello\nWorld")); reader.Read(null!, 0, 5); @@ -73,10 +73,10 @@ public class StringBuilderReaderTests }); } - [TestMethod] + [Test] public void Read_ShouldThrow_GivenNegativeIndex() { - Assert.ThrowsException(() => + Assert.Throws(() => { using var reader = new StringBuilderReader(new StringBuilder("Hello\nWorld")); var array = new char[5]; @@ -85,10 +85,10 @@ public class StringBuilderReaderTests }); } - [TestMethod] + [Test] public void Read_ShouldThrow_GivenNegativeCount() { - Assert.ThrowsException(() => + Assert.Throws(() => { using var reader = new StringBuilderReader(new StringBuilder("Hello\nWorld")); var array = new char[5]; @@ -97,10 +97,10 @@ public class StringBuilderReaderTests }); } - [TestMethod] + [Test] public void Read_ShouldThrow_GivenSmallBuffer() { - Assert.ThrowsException(() => + Assert.Throws(() => { using var reader = new StringBuilderReader(new StringBuilder("Hello\nWorld")); var array = new char[1]; @@ -109,77 +109,77 @@ public class StringBuilderReaderTests }); } - [TestMethod] + [Test] public void Read_ShouldPopulateSpan_GivenBuilder() { using var reader = new StringBuilderReader(new StringBuilder("Hello\nWorld")); Span span = stackalloc char[5]; int read = reader.Read(span); - Assert.AreEqual(5, read); + Assert.That(read, Is.EqualTo(5)); CollectionAssert.AreEqual("Hello".ToCharArray(), span.ToArray()); reader.Close(); } - [TestMethod] + [Test] public void ReadAsync_ShouldPopulateArray_GivenBuilder() { using var reader = new StringBuilderReader(new StringBuilder("Hello\nWorld")); var array = new char[5]; int read = reader.ReadAsync(array, 0, 5).GetAwaiter().GetResult(); - Assert.AreEqual(5, read); + Assert.That(read, Is.EqualTo(5)); CollectionAssert.AreEqual("Hello".ToCharArray(), array); reader.Close(); } - [TestMethod] + [Test] public void ReadAsync_ShouldPopulateMemory_GivenBuilder() { using var reader = new StringBuilderReader(new StringBuilder("Hello\nWorld")); Memory memory = new char[5]; int read = reader.ReadAsync(memory).GetAwaiter().GetResult(); - Assert.AreEqual(5, read); + Assert.That(read, Is.EqualTo(5)); CollectionAssert.AreEqual("Hello".ToCharArray(), memory.ToArray()); reader.Close(); } - [TestMethod] + [Test] public void ReadBlock_ShouldPopulateArray_GivenBuilder() { using var reader = new StringBuilderReader(new StringBuilder("Hello\nWorld")); var array = new char[5]; int read = reader.ReadBlock(array, 0, 5); - Assert.AreEqual(5, read); + Assert.That(read, Is.EqualTo(5)); CollectionAssert.AreEqual("Hello".ToCharArray(), array); reader.Close(); } - [TestMethod] + [Test] public void ReadBlock_ShouldPopulateSpan_GivenBuilder() { using var reader = new StringBuilderReader(new StringBuilder("Hello\nWorld")); Span span = stackalloc char[5]; int read = reader.ReadBlock(span); - Assert.AreEqual(5, read); + Assert.That(read, Is.EqualTo(5)); CollectionAssert.AreEqual("Hello".ToCharArray(), span.ToArray()); reader.Close(); } - [TestMethod] + [Test] public void ReadBlock_ShouldReturnNegative1_GivenEndOfReader() { using var reader = new StringBuilderReader(new StringBuilder("Hello\nWorld")); @@ -188,83 +188,83 @@ public class StringBuilderReaderTests reader.Read(array); int read = reader.ReadBlock(array, 0, 5); - Assert.AreEqual(-1, read); + Assert.That(read, Is.EqualTo(-1)); reader.Close(); } - [TestMethod] + [Test] public void ReadBlockAsync_ShouldPopulateArray_GivenBuilder() { using var reader = new StringBuilderReader(new StringBuilder("Hello\nWorld")); var array = new char[5]; int read = reader.ReadBlockAsync(array, 0, 5).GetAwaiter().GetResult(); - Assert.AreEqual(5, read); + Assert.That(read, Is.EqualTo(5)); CollectionAssert.AreEqual("Hello".ToCharArray(), array); reader.Close(); } - [TestMethod] + [Test] public void ReadBlockAsync_ShouldPopulateMemory_GivenBuilder() { using var reader = new StringBuilderReader(new StringBuilder("Hello\nWorld")); Memory memory = new char[5]; int read = reader.ReadBlockAsync(memory).GetAwaiter().GetResult(); - Assert.AreEqual(5, read); + Assert.That(read, Is.EqualTo(5)); CollectionAssert.AreEqual("Hello".ToCharArray(), memory.ToArray()); reader.Close(); } - [TestMethod] + [Test] public void ReadToEnd_ShouldReturnSourceString_GivenBuilder() { const string value = "Hello World"; using var reader = new StringBuilderReader(new StringBuilder(value)); - Assert.AreEqual(value, reader.ReadToEnd()); + Assert.That(reader.ReadToEnd(), Is.EqualTo(value)); reader.Close(); } - [TestMethod] + [Test] public void ReadToEndAsync_ShouldReturnSourceString_GivenBuilder() { const string value = "Hello World"; using var reader = new StringBuilderReader(new StringBuilder(value)); - Assert.AreEqual(value, reader.ReadToEndAsync().GetAwaiter().GetResult()); + Assert.That(reader.ReadToEndAsync().GetAwaiter().GetResult(), Is.EqualTo(value)); reader.Close(); } - [TestMethod] + [Test] public void ReadLine_ShouldReturnSourceString_GivenBuilder() { using var reader = new StringBuilderReader(new StringBuilder("Hello\nWorld")); - Assert.AreEqual("Hello", reader.ReadLine()); - Assert.AreEqual("World", reader.ReadLine()); - Assert.AreEqual(null, reader.ReadLine()); + Assert.That(reader.ReadLine(), Is.EqualTo("Hello")); + Assert.That(reader.ReadLine(), Is.EqualTo("World")); + Assert.That(reader.ReadLine(), Is.EqualTo(null)); - Assert.AreEqual(-1, reader.Peek()); + Assert.That(reader.Peek(), Is.EqualTo(-1)); reader.Close(); } - [TestMethod] + [Test] public void ReadLineAsync_ShouldReturnSourceString_GivenBuilder() { using var reader = new StringBuilderReader(new StringBuilder("Hello\nWorld")); - Assert.AreEqual("Hello", reader.ReadLineAsync().GetAwaiter().GetResult()); - Assert.AreEqual("World", reader.ReadLineAsync().GetAwaiter().GetResult()); - Assert.AreEqual(null, reader.ReadLineAsync().GetAwaiter().GetResult()); + Assert.That(reader.ReadLineAsync().GetAwaiter().GetResult(), Is.EqualTo("Hello")); + Assert.That(reader.ReadLineAsync().GetAwaiter().GetResult(), Is.EqualTo("World")); + Assert.That(reader.ReadLineAsync().GetAwaiter().GetResult(), Is.EqualTo(null)); - Assert.AreEqual(-1, reader.Peek()); + Assert.That(reader.Peek(), Is.EqualTo(-1)); reader.Close(); } diff --git a/X10D.Tests/src/Text/StringTests.cs b/X10D.Tests/src/Text/StringTests.cs index 0798b6e..99fca98 100644 --- a/X10D.Tests/src/Text/StringTests.cs +++ b/X10D.Tests/src/Text/StringTests.cs @@ -2,15 +2,15 @@ #if NET5_0_OR_GREATER using System.Text.Json.Serialization; #endif -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Text; namespace X10D.Tests.Text; -[TestClass] +[TestFixture] public class StringTests { - [TestMethod] + [Test] public void AsNullIfEmpty_ShouldBeCorrect() { const string sampleString = "Hello World"; @@ -23,13 +23,16 @@ public class StringTests string emptyResult = emptyString.AsNullIfEmpty(); string? nullResult = nullString.AsNullIfEmpty(); - Assert.AreEqual(sampleString, sampleResult); - Assert.AreEqual(whitespaceString, whitespaceResult); - Assert.AreEqual(nullString, emptyResult); - Assert.AreEqual(nullString, nullResult); + Assert.Multiple(() => + { + Assert.That(sampleResult, Is.EqualTo(sampleString)); + Assert.That(whitespaceResult, Is.EqualTo(whitespaceString)); + Assert.That(emptyResult, Is.EqualTo(nullString)); + Assert.That(nullResult, Is.EqualTo(nullString)); + }); } - [TestMethod] + [Test] public void AsNullIfWhiteSpace_ShouldBeCorrect() { const string sampleString = "Hello World"; @@ -42,275 +45,299 @@ public class StringTests string emptyResult = emptyString.AsNullIfWhiteSpace(); string? nullResult = nullString.AsNullIfWhiteSpace(); - Assert.AreEqual(sampleString, sampleResult); - Assert.AreEqual(nullString, whitespaceResult); - Assert.AreEqual(nullString, emptyResult); - Assert.AreEqual(nullString, nullResult); + Assert.Multiple(() => + { + Assert.That(sampleResult, Is.EqualTo(sampleString)); + Assert.That(whitespaceResult, Is.EqualTo(nullString)); + Assert.That(emptyResult, Is.EqualTo(nullString)); + Assert.That(nullResult, Is.EqualTo(nullString)); + }); } - [TestMethod] + [Test] public void Base64Decode_ShouldReturnHelloWorld_GivenBase64String() { - Assert.AreEqual("Hello World", "SGVsbG8gV29ybGQ=".Base64Decode()); + Assert.That("SGVsbG8gV29ybGQ=".Base64Decode(), Is.EqualTo("Hello World")); } - - [TestMethod] + [Test] public void Base64Decode_ShouldThrow_GivenNull() { - string? value = null; - Assert.ThrowsException(() => value!.Base64Decode()); + string value = null!; + Assert.Throws(() => _ = value.Base64Decode()); } - - [TestMethod] + [Test] public void Base64Encode_ShouldReturnBase64String_GivenHelloWorld() { - Assert.AreEqual("SGVsbG8gV29ybGQ=", "Hello World".Base64Encode()); + Assert.That("Hello World".Base64Encode(), Is.EqualTo("SGVsbG8gV29ybGQ=")); } - [TestMethod] + [Test] public void Base64Encode_ShouldThrow_GivenNull() { - string? value = null; - Assert.ThrowsException(() => value!.Base64Encode()); + string value = null!; + Assert.Throws(() => _ = value.Base64Encode()); } - [TestMethod] + [Test] public void ChangeEncoding_ShouldReturnAsciiString_GivenUtf8() { - Assert.AreEqual("Hello World", "Hello World".ChangeEncoding(Encoding.UTF8, Encoding.ASCII)); + Assert.That("Hello World".ChangeEncoding(Encoding.UTF8, Encoding.ASCII), Is.EqualTo("Hello World")); } - [TestMethod] + [Test] public void ChangeEncoding_ShouldThrow_GivenNullString() { - string? value = null; - Assert.ThrowsException(() => value!.ChangeEncoding(Encoding.UTF8, Encoding.ASCII)); + string value = null!; + Assert.Throws(() => _ = value.ChangeEncoding(Encoding.UTF8, Encoding.ASCII)); } - [TestMethod] + [Test] public void ChangeEncoding_ShouldThrow_GivenNullSourceEncoding() { - Assert.ThrowsException(() => "Hello World".ChangeEncoding(null!, Encoding.ASCII)); + Assert.Throws(() => _ = "Hello World".ChangeEncoding(null!, Encoding.ASCII)); } - [TestMethod] + [Test] public void ChangeEncoding_ShouldThrow_GivenNullDestinationEncoding() { - Assert.ThrowsException(() => "Hello World".ChangeEncoding(Encoding.UTF8, null!)); + Assert.Throws(() => _ = "Hello World".ChangeEncoding(Encoding.UTF8, null!)); } - [TestMethod] + [Test] public void CountSubstring_ShouldHonor_StringComparison() { - Assert.AreEqual(0, "Hello World".CountSubstring('E')); - Assert.AreEqual(0, "Hello World".CountSubstring("E")); - Assert.AreEqual(1, "Hello World".CountSubstring("E", StringComparison.OrdinalIgnoreCase)); + Assert.Multiple(() => + { + Assert.That("Hello World".CountSubstring('E'), Is.Zero); + Assert.That("Hello World".CountSubstring("E"), Is.Zero); + Assert.That("Hello World".CountSubstring("E", StringComparison.OrdinalIgnoreCase), Is.EqualTo(1)); + }); } - [TestMethod] + [Test] public void CountSubstring_ShouldReturn0_GivenNoInstanceChar() { - Assert.AreEqual(0, "Hello World".CountSubstring('z')); - Assert.AreEqual(0, "Hello World".CountSubstring("z")); - Assert.AreEqual(0, "Hello World".CountSubstring("z", StringComparison.OrdinalIgnoreCase)); + Assert.Multiple(() => + { + Assert.That("Hello World".CountSubstring('z'), Is.Zero); + Assert.That("Hello World".CountSubstring("z"), Is.Zero); + Assert.That("Hello World".CountSubstring("z", StringComparison.OrdinalIgnoreCase), Is.Zero); + }); } - [TestMethod] + [Test] public void CountSubstring_ShouldReturn1_GivenSingleInstanceChar() { - Assert.AreEqual(1, "Hello World".CountSubstring('e')); - Assert.AreEqual(1, "Hello World".CountSubstring("e")); - Assert.AreEqual(1, "Hello World".CountSubstring("e", StringComparison.OrdinalIgnoreCase)); + Assert.Multiple(() => + { + Assert.That("Hello World".CountSubstring('e'), Is.EqualTo(1)); + Assert.That("Hello World".CountSubstring("e"), Is.EqualTo(1)); + Assert.That("Hello World".CountSubstring("e", StringComparison.OrdinalIgnoreCase), Is.EqualTo(1)); + }); } - [TestMethod] + [Test] public void CountSubstring_ShouldReturn0_GivenEmptyHaystack() { - Assert.AreEqual(0, string.Empty.CountSubstring('\0')); - Assert.AreEqual(0, string.Empty.CountSubstring(string.Empty)); - Assert.AreEqual(0, string.Empty.CountSubstring(string.Empty, StringComparison.OrdinalIgnoreCase)); + Assert.Multiple(() => + { + Assert.That(string.Empty.CountSubstring('\0'), Is.Zero); + Assert.That(string.Empty.CountSubstring(string.Empty), Is.Zero); + Assert.That(string.Empty.CountSubstring(string.Empty, StringComparison.OrdinalIgnoreCase), Is.Zero); + }); } - [TestMethod] + [Test] public void CountSubstring_ShouldThrow_GivenNullHaystack() { - Assert.ThrowsException(() => ((string?)null!).CountSubstring('\0')); - Assert.ThrowsException(() => ((string?)null!).CountSubstring(string.Empty)); - Assert.ThrowsException(() => - ((string?)null!).CountSubstring(string.Empty, StringComparison.OrdinalIgnoreCase)); + string value = null!; + Assert.Throws(() => value.CountSubstring('\0')); + Assert.Throws(() => value.CountSubstring(string.Empty)); + Assert.Throws(() => value.CountSubstring(string.Empty, StringComparison.OrdinalIgnoreCase)); } - [TestMethod] + [Test] public void EnsureEndsWith_ShouldPrependChar_GivenEndsWithReturnFalse() { const string value = "Hello Worl"; const char substring = 'd'; - Assert.AreEqual("Hello World", value.EnsureEndsWith(substring)); + Assert.That(value.EnsureEndsWith(substring), Is.EqualTo("Hello World")); } - [TestMethod] + [Test] public void EnsureEndsWith_ShouldReturnChar_GivenEndsWithReturnTrue() { const string value = "A"; const char substring = 'A'; - Assert.AreEqual(value, value.EnsureEndsWith(substring)); + Assert.That(value.EnsureEndsWith(substring), Is.EqualTo(value)); } - [TestMethod] + [Test] public void EnsureStartsWith_ShouldPrependChar_GivenEndsWithReturnFalse() { const string value = "B"; const char substring = 'A'; - Assert.AreEqual("AB", value.EnsureStartsWith(substring)); + Assert.That(value.EnsureStartsWith(substring), Is.EqualTo("AB")); } - [TestMethod] + [Test] public void EnsureStartsWith_ShouldReturnChar_GivenEndsWithReturnTrue() { const string value = "A"; const char substring = 'A'; - Assert.AreEqual(value, value.EnsureStartsWith(substring)); + Assert.That(value.EnsureStartsWith(substring), Is.EqualTo(value)); } - [TestMethod] + [Test] public void EnsureEndsWith_ShouldAppendSubstring_GivenEndsWithReturnFalse() { const string value = "Hello "; const string substring = "World"; - Assert.AreEqual("Hello World", value.EnsureEndsWith(substring)); + Assert.That(value.EnsureEndsWith(substring), Is.EqualTo("Hello World")); } - [TestMethod] + [Test] public void EnsureEndsWith_ShouldReturnString_GivenEndsWithReturnTrue() { const string substring = "World"; - Assert.AreEqual(substring, substring.EnsureEndsWith(substring)); + Assert.That(substring.EnsureEndsWith(substring), Is.EqualTo(substring)); } - [TestMethod] + [Test] public void EnsureEndsWith_ShouldReturnString_GivenEmptySourceString() { const string substring = "World"; - Assert.AreEqual(substring, string.Empty.EnsureEndsWith(substring)); + Assert.That(string.Empty.EnsureEndsWith(substring), Is.EqualTo(substring)); } - [TestMethod] + [Test] public void EnsureEndsWith_ShouldReturnString_GivenEmptySubString() { const string substring = "World"; - Assert.AreEqual(substring, substring.EnsureEndsWith(string.Empty)); + Assert.That(substring.EnsureEndsWith(string.Empty), Is.EqualTo(substring)); } - [TestMethod] + [Test] public void EnsureStartsWith_ShouldAppendSubstring_GivenEndsWithReturnFalse() { const string value = "World"; const string substring = "Hello "; - Assert.AreEqual("Hello World", value.EnsureStartsWith(substring)); + Assert.That(value.EnsureStartsWith(substring), Is.EqualTo("Hello World")); } - [TestMethod] + [Test] public void EnsureStartsWith_ShouldReturnString_GivenEndsWithReturnTrue() { const string substring = "World"; - Assert.AreEqual(substring, substring.EnsureStartsWith(substring)); + Assert.That(substring.EnsureStartsWith(substring), Is.EqualTo(substring)); } - [TestMethod] + [Test] public void EnsureStartsWith_ShouldReturnString_GivenEmptySourceString() { const string substring = "World"; - Assert.AreEqual(substring, string.Empty.EnsureStartsWith(substring)); + Assert.That(string.Empty.EnsureStartsWith(substring), Is.EqualTo(substring)); } - [TestMethod] + [Test] public void EnsureStartsWith_ShouldReturnString_GivenEmptySubString() { const string substring = "World"; - Assert.AreEqual(substring, substring.EnsureStartsWith(string.Empty)); + Assert.That(substring.EnsureStartsWith(string.Empty), Is.EqualTo(substring)); } - [TestMethod] + [Test] public void EnumParse_ShouldReturnCorrectValue_GivenString() { - Assert.AreEqual(DayOfWeek.Monday, "Monday".EnumParse(false)); - Assert.AreEqual(DayOfWeek.Tuesday, "Tuesday".EnumParse(false)); - Assert.AreEqual(DayOfWeek.Wednesday, "Wednesday".EnumParse(false)); - Assert.AreEqual(DayOfWeek.Thursday, "Thursday".EnumParse(false)); - Assert.AreEqual(DayOfWeek.Friday, "Friday".EnumParse(false)); - Assert.AreEqual(DayOfWeek.Saturday, "Saturday".EnumParse(false)); - Assert.AreEqual(DayOfWeek.Sunday, "Sunday".EnumParse(false)); + Assert.Multiple(() => + { + Assert.That("Monday".EnumParse(false), Is.EqualTo(DayOfWeek.Monday)); + Assert.That("Tuesday".EnumParse(false), Is.EqualTo(DayOfWeek.Tuesday)); + Assert.That("Wednesday".EnumParse(false), Is.EqualTo(DayOfWeek.Wednesday)); + Assert.That("Thursday".EnumParse(false), Is.EqualTo(DayOfWeek.Thursday)); + Assert.That("Friday".EnumParse(false), Is.EqualTo(DayOfWeek.Friday)); + Assert.That("Saturday".EnumParse(false), Is.EqualTo(DayOfWeek.Saturday)); + Assert.That("Sunday".EnumParse(false), Is.EqualTo(DayOfWeek.Sunday)); + }); } - [TestMethod] + [Test] public void EnumParse_ShouldTrim() { - Assert.AreEqual(DayOfWeek.Monday, " Monday ".EnumParse()); - Assert.AreEqual(DayOfWeek.Tuesday, " Tuesday ".EnumParse()); - Assert.AreEqual(DayOfWeek.Wednesday, " Wednesday ".EnumParse()); - Assert.AreEqual(DayOfWeek.Thursday, " Thursday ".EnumParse()); - Assert.AreEqual(DayOfWeek.Friday, " Friday ".EnumParse()); - Assert.AreEqual(DayOfWeek.Saturday, " Saturday ".EnumParse()); - Assert.AreEqual(DayOfWeek.Sunday, " Sunday ".EnumParse()); + Assert.Multiple(() => + { + Assert.That(" Monday ".EnumParse(), Is.EqualTo(DayOfWeek.Monday)); + Assert.That(" Tuesday ".EnumParse(), Is.EqualTo(DayOfWeek.Tuesday)); + Assert.That(" Wednesday ".EnumParse(), Is.EqualTo(DayOfWeek.Wednesday)); + Assert.That(" Thursday ".EnumParse(), Is.EqualTo(DayOfWeek.Thursday)); + Assert.That(" Friday ".EnumParse(), Is.EqualTo(DayOfWeek.Friday)); + Assert.That(" Saturday ".EnumParse(), Is.EqualTo(DayOfWeek.Saturday)); + Assert.That(" Sunday ".EnumParse(), Is.EqualTo(DayOfWeek.Sunday)); + }); } - [TestMethod] + [Test] public void EnumParse_ShouldReturnCorrectValue_GivenString_Generic() { - Assert.AreEqual(DayOfWeek.Monday, "Monday".EnumParse()); - Assert.AreEqual(DayOfWeek.Tuesday, "Tuesday".EnumParse()); - Assert.AreEqual(DayOfWeek.Wednesday, "Wednesday".EnumParse()); - Assert.AreEqual(DayOfWeek.Thursday, "Thursday".EnumParse()); - Assert.AreEqual(DayOfWeek.Friday, "Friday".EnumParse()); - Assert.AreEqual(DayOfWeek.Saturday, "Saturday".EnumParse()); - Assert.AreEqual(DayOfWeek.Sunday, "Sunday".EnumParse()); + Assert.Multiple(() => + { + Assert.That("Monday".EnumParse(), Is.EqualTo(DayOfWeek.Monday)); + Assert.That("Tuesday".EnumParse(), Is.EqualTo(DayOfWeek.Tuesday)); + Assert.That("Wednesday".EnumParse(), Is.EqualTo(DayOfWeek.Wednesday)); + Assert.That("Thursday".EnumParse(), Is.EqualTo(DayOfWeek.Thursday)); + Assert.That("Friday".EnumParse(), Is.EqualTo(DayOfWeek.Friday)); + Assert.That("Saturday".EnumParse(), Is.EqualTo(DayOfWeek.Saturday)); + Assert.That("Sunday".EnumParse(), Is.EqualTo(DayOfWeek.Sunday)); + }); } - [TestMethod] + [Test] public void EnumParse_ShouldThrow_GivenNullString() { - string? value = null; - Assert.ThrowsException(() => value!.EnumParse()); + string value = null!; + Assert.Throws(() => _ = value.EnumParse()); } - [TestMethod] + [Test] public void EnumParse_ShouldThrow_GivenEmptyOrWhiteSpaceString() { - Assert.ThrowsException(() => string.Empty.EnumParse()); - Assert.ThrowsException(() => " ".EnumParse()); + Assert.Throws(() => _ = string.Empty.EnumParse()); + Assert.Throws(() => _ = " ".EnumParse()); } #if NET5_0_OR_GREATER - [TestMethod] + [Test] public void FromJson_ShouldDeserializeCorrectly_GivenJsonString() { const string json = "{\"values\": [1, 2, 3]}"; var target = json.FromJson(); - Assert.IsInstanceOfType(target, typeof(SampleStructure)); - Assert.IsNotNull(target); - Assert.IsNotNull(target.Values); - Assert.AreEqual(3, target.Values.Length); - Assert.AreEqual(1, target.Values[0]); - Assert.AreEqual(2, target.Values[1]); - Assert.AreEqual(3, target.Values[2]); + Assert.Multiple(() => + { + Assert.IsInstanceOf(target); + Assert.That(target.Values, Is.Not.Null); + Assert.That(target.Values.Length, Is.EqualTo(3)); + Assert.That(target.Values[0], Is.EqualTo(1)); + Assert.That(target.Values[1], Is.EqualTo(2)); + Assert.That(target.Values[2], Is.EqualTo(3)); + }); } #endif - [TestMethod] + [Test] public void GetBytes_ShouldReturnUtf8Bytes_GivenHelloWorld() { var expected = new byte[] {0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64}; @@ -319,7 +346,7 @@ public class StringTests CollectionAssert.AreEqual(expected, actual); } - [TestMethod] + [Test] public void GetBytes_ShouldReturnAsciiBytes_GivenHelloWorld() { var expected = new byte[] {0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64}; @@ -328,36 +355,39 @@ public class StringTests CollectionAssert.AreEqual(expected, actual); } - [TestMethod] + [Test] public void GetBytes_ShouldThrow_GivenNullString() { - string? value = null; - Assert.ThrowsException(() => value!.GetBytes()); - Assert.ThrowsException(() => value!.GetBytes(Encoding.ASCII)); + string value = null!; + Assert.Throws(() => _ = value.GetBytes()); + Assert.Throws(() => _ = value.GetBytes(Encoding.ASCII)); } - [TestMethod] + [Test] public void GetBytes_ShouldThrow_GivenNullEncoding() { - Assert.ThrowsException(() => "Hello World".GetBytes(null!)); + Assert.Throws(() => _ = "Hello World".GetBytes(null!)); } - [TestMethod] + [Test] public void IsEmoji_ShouldReturnTrue_GivenBasicEmoji() { - Assert.IsTrue("😀".IsEmoji()); - Assert.IsTrue("🤓".IsEmoji()); - Assert.IsTrue("🟦".IsEmoji()); - Assert.IsTrue("🟧".IsEmoji()); - Assert.IsTrue("🟨".IsEmoji()); - Assert.IsTrue("🟩".IsEmoji()); - Assert.IsTrue("🟪".IsEmoji()); - Assert.IsTrue("🟫".IsEmoji()); - Assert.IsTrue("📱".IsEmoji()); - Assert.IsTrue("🎨".IsEmoji()); + Assert.Multiple(() => + { + Assert.That("😀".IsEmoji()); + Assert.That("🤓".IsEmoji()); + Assert.That("🟦".IsEmoji()); + Assert.That("🟧".IsEmoji()); + Assert.That("🟨".IsEmoji()); + Assert.That("🟩".IsEmoji()); + Assert.That("🟪".IsEmoji()); + Assert.That("🟫".IsEmoji()); + Assert.That("📱".IsEmoji()); + Assert.That("🎨".IsEmoji()); + }); } - [TestMethod] + [Test] public void IsEmoji_ShouldReturnTrue_GivenMultiByteEmoji() { string[] regionalIndicatorCodes = Enumerable.Range(0, 26) @@ -368,129 +398,141 @@ public class StringTests for (var j = 0; j < 26; j++) { string flag = (regionalIndicatorCodes[i] + regionalIndicatorCodes[j]); - Assert.IsTrue(flag.IsEmoji()); + Assert.That(flag.IsEmoji()); } } - [TestMethod] + [Test] public void IsEmoji_ShouldReturnFalse_GivenNonEmoji() { - Assert.IsFalse("Hello World".IsEmoji()); - Assert.IsFalse("Hello".IsEmoji()); - Assert.IsFalse("World".IsEmoji()); + Assert.Multiple(() => + { + Assert.That("Hello World".IsEmoji(), Is.False); + Assert.That("Hello".IsEmoji(), Is.False); + Assert.That("World".IsEmoji(), Is.False); + }); } - [TestMethod] + [Test] public void IsEmoji_ShouldThrowArgumentNullException_GivenNullInput() { string value = null!; - Assert.ThrowsException(() => value.IsEmoji()); + Assert.Throws(() => _ = value.IsEmoji()); } - [TestMethod] + [Test] public void IsEmpty_ShouldReturnTrue_GivenEmptyString() { - Assert.IsTrue("".IsEmpty()); - Assert.IsTrue(string.Empty.IsEmpty()); + Assert.Multiple(() => + { + Assert.That("".IsEmpty()); + Assert.That(string.Empty.IsEmpty()); + }); } - [TestMethod] + [Test] public void IsEmpty_ShouldReturnFalse_GivenWhiteSpaceString() { - Assert.IsFalse(" ".IsEmpty()); + Assert.That(" ".IsEmpty(), Is.False); } - [TestMethod] + [Test] public void IsEmpty_ShouldReturnFalse_GivenNonEmptyString() { - Assert.IsFalse("Hello World".IsEmpty()); + Assert.That("Hello World".IsEmpty(), Is.False); } - [TestMethod] + [Test] public void IsEmpty_ShouldThrowArgumentNullException_GivenNullString() { - string? value = null; - Assert.ThrowsException(() => value!.IsEmpty()); + string value = null!; + Assert.Throws(() => _ = value.IsEmpty()); } - [TestMethod] + [Test] public void IsLower_ShouldReturnTrue_GivenLowercaseString() { - Assert.IsTrue("hello world".IsLower()); + Assert.That("hello world".IsLower()); } - [TestMethod] + [Test] public void IsLower_ShouldReturnFalse_GivenMixedCaseString() { - Assert.IsFalse("Hello World".IsLower()); + Assert.That("Hello World".IsLower(), Is.False); } - [TestMethod] + [Test] public void IsLower_ShouldReturnFalse_GivenUppercaseString() { - Assert.IsFalse("HELLO WORLD".IsLower()); + Assert.That("HELLO WORLD".IsLower(), Is.False); } - [TestMethod] + [Test] public void IsLower_ShouldThrow_GivenNull() { - string? value = null; - Assert.ThrowsException(() => value!.IsLower()); + string value = null!; + Assert.Throws(() => _ = value.IsLower()); } - [TestMethod] + [Test] public void IsNullOrEmpty_ShouldReturnTrue_GivenEmptyString() { - Assert.IsTrue("".IsNullOrEmpty()); - Assert.IsTrue(string.Empty.IsNullOrEmpty()); + Assert.Multiple(() => + { + Assert.That("".IsNullOrEmpty()); + Assert.That(string.Empty.IsNullOrEmpty()); + }); } - [TestMethod] + [Test] public void IsNullOrEmpty_ShouldReturnFalse_GivenWhiteSpaceString() { - Assert.IsFalse(" ".IsNullOrEmpty()); + Assert.That(" ".IsNullOrEmpty(), Is.False); } - [TestMethod] + [Test] public void IsNullOrEmpty_ShouldReturnFalse_GivenNonEmptyString() { - Assert.IsFalse("Hello World".IsNullOrEmpty()); + Assert.That("Hello World".IsNullOrEmpty(), Is.False); } - [TestMethod] + [Test] public void IsNullOrEmpty_ShouldReturnTrue_GivenNullString() { - string? value = null; - Assert.IsTrue(value.IsNullOrEmpty()); + string value = null!; + Assert.That(value.IsNullOrEmpty()); } - [TestMethod] + [Test] public void IsNullOrWhiteSpace_ShouldReturnTrue_GivenEmptyString() { - Assert.IsTrue("".IsNullOrWhiteSpace()); - Assert.IsTrue(string.Empty.IsNullOrWhiteSpace()); + Assert.Multiple(() => + { + Assert.That("".IsNullOrWhiteSpace()); + Assert.That(string.Empty.IsNullOrWhiteSpace()); + }); } - [TestMethod] + [Test] public void IsNullOrWhiteSpace_ShouldReturnTrue_GivenWhiteSpaceString() { - Assert.IsTrue(" ".IsNullOrWhiteSpace()); + Assert.That(" ".IsNullOrWhiteSpace()); } - [TestMethod] + [Test] public void IsNullOrWhiteSpace_ShouldReturnFalse_GivenNonEmptyString() { - Assert.IsFalse("Hello World".IsNullOrWhiteSpace()); + Assert.That("Hello World".IsNullOrWhiteSpace(), Is.False); } - [TestMethod] + [Test] public void IsNullOrWhiteSpace_ShouldReturnTrue_GivenNullString() { - string? value = null; - Assert.IsTrue(value.IsNullOrWhiteSpace()); + string value = null!; + Assert.That(value.IsNullOrWhiteSpace()); } - [TestMethod] + [Test] public void IsPalindrome_ShouldBeCorrect_GivenString() { const string inputA = "Race car"; @@ -500,271 +542,295 @@ public class StringTests const string inputE = "Y"; const string inputF = "1"; - Assert.IsTrue(inputA.IsPalindrome(), inputA); - Assert.IsTrue(inputB.IsPalindrome(), inputB); - Assert.IsTrue(inputC.IsPalindrome(), inputC); - Assert.IsFalse(inputD.IsPalindrome(), inputD); - Assert.IsTrue(inputE.IsPalindrome(), inputE); - Assert.IsTrue(inputF.IsPalindrome(), inputF); + Assert.Multiple(() => + { + Assert.That(inputA.IsPalindrome()); + Assert.That(inputB.IsPalindrome()); + Assert.That(inputC.IsPalindrome()); + Assert.That(inputD.IsPalindrome(), Is.False); + Assert.That(inputE.IsPalindrome()); + Assert.That(inputF.IsPalindrome()); + }); } - [TestMethod] + [Test] public void IsPalindrome_ShouldReturnFalse_GivenEmptyString() { - Assert.IsFalse(string.Empty.IsPalindrome()); + Assert.That(string.Empty.IsPalindrome(), Is.False); } - [TestMethod] + [Test] public void IsPalindrome_ShouldThrow_GivenNull() { - Assert.ThrowsException(() => ((string?)null)!.IsPalindrome()); + Assert.Throws(() => _ = ((string?)null)!.IsPalindrome()); } - [TestMethod] + [Test] public void IsUpper_ShouldReturnFalse_GivenLowercaseString() { - Assert.IsFalse("hello world".IsUpper()); + Assert.That("hello world".IsUpper(), Is.False); } - [TestMethod] + [Test] public void IsUpper_ShouldReturnFalse_GivenMixedCaseString() { - Assert.IsFalse("Hello World".IsUpper()); + Assert.That("Hello World".IsUpper(), Is.False); } - [TestMethod] + [Test] public void IsUpper_ShouldReturnTrue_GivenUppercaseString() { - Assert.IsTrue("HELLO WORLD".IsUpper()); + Assert.That("HELLO WORLD".IsUpper()); } - [TestMethod] + [Test] public void IsUpper_ShouldThrow_GivenNull() { string? value = null; - Assert.ThrowsException(() => value!.IsUpper()); + Assert.Throws(() => _ = value!.IsUpper()); } - [TestMethod] + [Test] public void IsWhiteSpace_ShouldReturnTrue_GivenEmptyString() { - Assert.IsTrue("".IsWhiteSpace()); - Assert.IsTrue(string.Empty.IsWhiteSpace()); + Assert.Multiple(() => + { + Assert.That("".IsWhiteSpace()); + Assert.That(string.Empty.IsWhiteSpace()); + }); } - [TestMethod] + [Test] public void IsWhiteSpace_ShouldReturnTrue_GivenWhiteSpaceString() { - Assert.IsTrue(" ".IsWhiteSpace()); + Assert.That(" ".IsWhiteSpace()); } - [TestMethod] + [Test] public void IsWhiteSpace_ShouldReturnFalse_GivenNonEmptyString() { - Assert.IsFalse("Hello World".IsWhiteSpace()); + Assert.That("Hello World".IsWhiteSpace(), Is.False); } - [TestMethod] + [Test] public void IsWhiteSpace_ShouldThrowArgumentNullException_GivenNullString() { - string? value = null; - Assert.ThrowsException(() => value!.IsWhiteSpace()); + string value = null!; + Assert.Throws(() => _ = value.IsWhiteSpace()); } - [TestMethod] + [Test] public void Randomize_ShouldReorder_GivenString() { const string input = "Hello World"; var random = new Random(1); - Assert.AreEqual("le rooldeoH", input.Randomize(input.Length, random)); + Assert.That(input.Randomize(input.Length, random), Is.EqualTo("le rooldeoH")); } - [TestMethod] + [Test] public void Randomize_ShouldReturnEmptyString_GivenLength1() { - Assert.AreEqual(string.Empty, "Hello World".Randomize(0)); + Assert.That("Hello World".Randomize(0), Is.EqualTo(string.Empty)); } - [TestMethod] + [Test] public void Randomize_ShouldThrow_GivenNull() { - string? value = null; - Assert.ThrowsException(() => value!.Randomize(1)); + string value = null!; + Assert.Throws(() => _ = value.Randomize(1)); } - [TestMethod] + [Test] public void Randomize_ShouldThrow_GivenNegativeLength() { - Assert.ThrowsException(() => string.Empty.Randomize(-1)); + Assert.Throws(() => string.Empty.Randomize(-1)); } - [TestMethod] + [Test] public void Repeat_ShouldReturnRepeatedString_GivenString() { const string expected = "aaaaaaaaaa"; string actual = "a".Repeat(10); - Assert.AreEqual(expected, actual); + Assert.That(actual, Is.EqualTo(expected)); } - [TestMethod] + [Test] public void Repeat_ShouldReturnEmptyString_GivenCount0() { - Assert.AreEqual(string.Empty, "a".Repeat(0)); + Assert.That("a".Repeat(0), Is.EqualTo(string.Empty)); } - [TestMethod] + [Test] public void Repeat_ShouldReturnItself_GivenCount1() { string repeated = "a".Repeat(1); - Assert.AreEqual(1, repeated.Length); - Assert.AreEqual("a", repeated); + Assert.That(repeated.Length, Is.EqualTo(1)); + Assert.That(repeated, Is.EqualTo("a")); } - [TestMethod] + [Test] public void Repeat_ShouldThrow_GivenNegativeCount() { - Assert.ThrowsException(() => "a".Repeat(-1)); + Assert.Throws(() => _ = "a".Repeat(-1)); } - [TestMethod] + [Test] public void Repeat_ShouldThrow_GivenNull() { - string? value = null; - Assert.ThrowsException(() => value!.Repeat(0)); + string value = null!; + Assert.Throws(() => _ = value.Repeat(0)); } - [TestMethod] + [Test] public void Reverse_ShouldBeCorrect() { const string input = "Hello World"; const string expected = "dlroW olleH"; - string result = input.Reverse(); - Assert.AreEqual(string.Empty.Reverse(), string.Empty); - Assert.AreEqual(" ".Reverse(), " "); - Assert.AreEqual(expected, result); + Assert.Multiple(() => + { + Assert.That(string.Empty.Reverse(), Is.EqualTo(string.Empty)); + Assert.That(" ".Reverse(), Is.EqualTo(" ")); + Assert.That(result, Is.EqualTo(expected)); + }); } - [TestMethod] + [Test] public void Reverse_ShouldThrow_GivenNull() { - string? value = null; - Assert.ThrowsException(() => value!.Reverse()); + string value = null!; + Assert.Throws(() => _ = value.Reverse()); } - [TestMethod] + [Test] public void Shuffled_ShouldReorder_GivenString() { const string alphabet = "abcdefghijklmnopqrstuvwxyz"; string shuffled = alphabet; - - Assert.AreEqual(alphabet, shuffled); + Assert.That(shuffled, Is.EqualTo(alphabet)); shuffled = alphabet.Shuffled(); - - Assert.AreNotEqual(alphabet, shuffled); + Assert.That(shuffled, Is.Not.EqualTo(alphabet)); } - [TestMethod] + [Test] public void Shuffled_ShouldThrow_GivenNull() { - string? value = null; - Assert.ThrowsException(() => value!.Shuffled()); + string value = null!; + Assert.Throws(() => _ = value.Shuffled()); } - [TestMethod] + [Test] public void Split_ShouldYieldCorrectStrings_GivenString() { string[] chunks = "Hello World".Split(2).ToArray(); - Assert.AreEqual(6, chunks.Length); - Assert.AreEqual("He", chunks[0]); - Assert.AreEqual("ll", chunks[1]); - Assert.AreEqual("o ", chunks[2]); - Assert.AreEqual("Wo", chunks[3]); - Assert.AreEqual("rl", chunks[4]); - Assert.AreEqual("d", chunks[5]); + Assert.Multiple(() => + { + Assert.That(chunks, Has.Length.EqualTo(6)); + Assert.That(chunks[0], Is.EqualTo("He")); + Assert.That(chunks[1], Is.EqualTo("ll")); + Assert.That(chunks[2], Is.EqualTo("o ")); + Assert.That(chunks[3], Is.EqualTo("Wo")); + Assert.That(chunks[4], Is.EqualTo("rl")); + Assert.That(chunks[5], Is.EqualTo("d")); + }); } - [TestMethod] + [Test] public void Split_ShouldYieldEmptyString_GivenChunkSize0() { string[] chunks = "Hello World".Split(0).ToArray(); - Assert.AreEqual(1, chunks.Length); - Assert.AreEqual(string.Empty, chunks[0]); + Assert.Multiple(() => + { + Assert.That(chunks, Has.Length.EqualTo(1)); + Assert.That(chunks[0], Is.EqualTo(string.Empty)); + }); } - [TestMethod] + [Test] public void Split_ShouldThrow_GivenNullString() { - string? value = null; + string value = null!; // forcing enumeration with ToArray is required for the exception to be thrown - Assert.ThrowsException(() => value!.Split(0).ToArray()); + Assert.Throws(() => _ = value.Split(0).ToArray()); } - [TestMethod] + [Test] public void StartsWithAny_ShouldReturnFalse_GivenNullInput() { - string? value = null; - Assert.IsFalse(value.StartsWithAny()); - Assert.IsFalse(value.StartsWithAny(StringComparison.Ordinal)); + string value = null!; + Assert.Multiple(() => + { + Assert.That(value.StartsWithAny(), Is.False); + Assert.That(value.StartsWithAny(StringComparison.Ordinal), Is.False); + }); } - [TestMethod] + [Test] public void StartsWithAny_ShouldReturnFalse_GivenEmptyInput() { - Assert.IsFalse(string.Empty.StartsWithAny()); - Assert.IsFalse(string.Empty.StartsWithAny(StringComparison.Ordinal)); + Assert.Multiple(() => + { + Assert.That(string.Empty.StartsWithAny(), Is.False); + Assert.That(string.Empty.StartsWithAny(StringComparison.Ordinal), Is.False); + }); } - [TestMethod] + [Test] public void StartsWithAny_ShouldReturnFalse_GivenValuesThatDontMatch() { const string value = "Hello World"; - Assert.IsFalse(value.StartsWithAny("World", "Goodbye")); - Assert.IsFalse(value.StartsWithAny(StringComparison.Ordinal, "World", "Goodbye")); + Assert.Multiple(() => + { + Assert.That(value.StartsWithAny("World", "Goodbye"), Is.False); + Assert.That(value.StartsWithAny(StringComparison.Ordinal, "World", "Goodbye"), Is.False); + }); } - [TestMethod] + [Test] public void StartsWithAny_ShouldReturnTrue_GivenValuesThatMatch() { const string value = "Hello World"; - Assert.IsTrue(value.StartsWithAny("World", "Hello")); - Assert.IsTrue(value.StartsWithAny(StringComparison.Ordinal, "World", "Hello")); + Assert.Multiple(() => + { + Assert.That(value.StartsWithAny("World", "Hello")); + Assert.That(value.StartsWithAny(StringComparison.Ordinal, "World", "Hello")); + }); } - [TestMethod] + [Test] public void StartsWithAny_ShouldReturnTrue_GivenValuesThatMatch_WithIgnoreCaseComparison() { const string value = "Hello World"; - Assert.IsTrue(value.StartsWithAny(StringComparison.OrdinalIgnoreCase, "WORLD", "HELLO")); + Assert.That(value.StartsWithAny(StringComparison.OrdinalIgnoreCase, "WORLD", "HELLO")); } - [TestMethod] + [Test] public void StartsWithAny_ShouldReturnFalse_GivenEmptyValues() { const string input = "Hello World"; - Assert.IsFalse(input.StartsWithAny()); + Assert.That(input.StartsWithAny(), Is.False); } - [TestMethod] + [Test] public void StartsWithAny_ShouldThrowArgumentNullException_GivenNullValues() { - Assert.ThrowsException(() => string.Empty.StartsWithAny(null!)); - Assert.ThrowsException(() => string.Empty.StartsWithAny(StringComparison.Ordinal, null!)); + Assert.Throws(() => string.Empty.StartsWithAny(null!)); + Assert.Throws(() => string.Empty.StartsWithAny(StringComparison.Ordinal, null!)); } - [TestMethod] + [Test] public void StartsWithAny_ShouldThrowArgumentNullException_GivenANullValue() { var values = new[] {"Hello", null!, "World"}; - Assert.ThrowsException(() => "Foobar".StartsWithAny(values)); - Assert.ThrowsException(() => "Foobar".StartsWithAny(StringComparison.Ordinal, values)); + Assert.Throws(() => "Foobar".StartsWithAny(values)); + Assert.Throws(() => "Foobar".StartsWithAny(StringComparison.Ordinal, values)); } - [TestMethod] + [Test] public void WithEmptyAlternative_ShouldBeCorrect() { const string inputA = "Hello World"; @@ -778,23 +844,28 @@ public class StringTests string resultC = inputC.WithEmptyAlternative(alternative); string resultD = inputD.WithEmptyAlternative(alternative); - Assert.AreEqual(resultA, inputA); - Assert.AreEqual(resultB, inputB); - Assert.AreEqual(resultC, alternative); - Assert.AreEqual(resultD, alternative); - Assert.AreEqual(alternative, ((string?)null).WithEmptyAlternative(alternative)); + Assert.Multiple(() => + { + Assert.That(resultA, Is.EqualTo(inputA)); + Assert.That(resultB, Is.EqualTo(inputB)); + Assert.That(resultC, Is.EqualTo(alternative)); + Assert.That(resultD, Is.EqualTo(alternative)); + Assert.That(((string?)null).WithEmptyAlternative(alternative), Is.EqualTo(alternative)); + }); } - [TestMethod] + [Test] public void WithWhiteSpaceAlternative_ShouldBeCorrect() { const string input = " "; const string alternative = "ALTERNATIVE"; string result = input.WithWhiteSpaceAlternative(alternative); - - Assert.AreEqual(result, alternative); - Assert.AreEqual(alternative, ((string?)null).WithWhiteSpaceAlternative(alternative)); + Assert.Multiple(() => + { + Assert.That(result, Is.EqualTo(alternative)); + Assert.That(((string?)null).WithWhiteSpaceAlternative(alternative), Is.EqualTo(alternative)); + }); } #if NET5_0_OR_GREATER diff --git a/X10D.Tests/src/Time/ByteTests.cs b/X10D.Tests/src/Time/ByteTests.cs index 705a149..c046241 100644 --- a/X10D.Tests/src/Time/ByteTests.cs +++ b/X10D.Tests/src/Time/ByteTests.cs @@ -1,73 +1,90 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Time; namespace X10D.Tests.Time; -[TestClass] +[TestFixture] public class ByteTests { - [TestMethod] + [Test] public void FromUnixTimeMilliseconds_ShouldBeEpoch_GivenZero() { - Assert.AreEqual(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc), ((byte)0).FromUnixTimeMilliseconds()); + DateTimeOffset expected = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + Assert.That(((byte)0).FromUnixTimeMilliseconds(), Is.EqualTo(expected)); } - [TestMethod] + [Test] public void FromUnixTimeSeconds_ShouldBeEpoch_GivenZero() { - Assert.AreEqual(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc), ((byte)0).FromUnixTimeSeconds()); + DateTimeOffset expected = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + Assert.That(((byte)0).FromUnixTimeSeconds(), Is.EqualTo(expected)); } - [TestMethod] + [Test] public void IsLeapYear_ShouldBeFalse_GivenMultipleOf100() { - Assert.IsFalse(((byte)100).IsLeapYear()); - Assert.IsFalse(((byte)200).IsLeapYear()); + Assert.Multiple(() => + { + Assert.That(((byte)100).IsLeapYear(), Is.False); + Assert.That(((byte)200).IsLeapYear(), Is.False); + }); } - [TestMethod] + [Test] public void IsLeapYear_ShouldBeFalse_GivenOddNumber() { - Assert.IsFalse(((byte)1).IsLeapYear()); - Assert.IsFalse(((byte)101).IsLeapYear()); - Assert.IsFalse(((byte)201).IsLeapYear()); + Assert.Multiple(() => + { + Assert.That(((byte)1).IsLeapYear(), Is.False); + Assert.That(((byte)101).IsLeapYear(), Is.False); + Assert.That(((byte)201).IsLeapYear(), Is.False); + }); } - [TestMethod] + [Test] public void IsLeapYear_ShouldBeTrue_GivenMultipleOf4() { - Assert.IsTrue(((byte)4).IsLeapYear()); - Assert.IsTrue(((byte)104).IsLeapYear()); - Assert.IsTrue(((byte)204).IsLeapYear()); + Assert.Multiple(() => + { + Assert.That(((byte)4).IsLeapYear()); + Assert.That(((byte)104).IsLeapYear()); + Assert.That(((byte)204).IsLeapYear()); + }); } - [TestMethod] + [Test] public void IsLeapYear_ShouldThrow_GivenZero() { - Assert.ThrowsException(() => ((byte)0).IsLeapYear()); + Assert.Throws(() => _ = ((byte)0).IsLeapYear()); } - [TestMethod] + [Test] public void TicksMillisecondsSecondsMinutesDaysHoursWeeks_ShouldBePositive_GivenOne() { - Assert.IsTrue(((byte)1).Ticks() > TimeSpan.Zero); - Assert.IsTrue(((byte)1).Milliseconds() > TimeSpan.Zero); - Assert.IsTrue(((byte)1).Seconds() > TimeSpan.Zero); - Assert.IsTrue(((byte)1).Minutes() > TimeSpan.Zero); - Assert.IsTrue(((byte)1).Days() > TimeSpan.Zero); - Assert.IsTrue(((byte)1).Hours() > TimeSpan.Zero); - Assert.IsTrue(((byte)1).Weeks() > TimeSpan.Zero); + Assert.Multiple(() => + { + Assert.That(((byte)1).Ticks(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(((byte)1).Milliseconds(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(((byte)1).Seconds(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(((byte)1).Minutes(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(((byte)1).Days(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(((byte)1).Hours(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(((byte)1).Weeks(), Is.GreaterThan(TimeSpan.Zero)); + }); } - [TestMethod] + [Test] public void TicksMillisecondsSecondsMinutesDaysHoursWeeks_ShouldBeZero_GivenZero() { - Assert.AreEqual(TimeSpan.Zero, ((byte)0).Ticks()); - Assert.AreEqual(TimeSpan.Zero, ((byte)0).Milliseconds()); - Assert.AreEqual(TimeSpan.Zero, ((byte)0).Seconds()); - Assert.AreEqual(TimeSpan.Zero, ((byte)0).Minutes()); - Assert.AreEqual(TimeSpan.Zero, ((byte)0).Days()); - Assert.AreEqual(TimeSpan.Zero, ((byte)0).Hours()); - Assert.AreEqual(TimeSpan.Zero, ((byte)0).Weeks()); + Assert.Multiple(() => + { + Assert.That(((byte)0).Ticks(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(((byte)0).Milliseconds(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(((byte)0).Seconds(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(((byte)0).Minutes(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(((byte)0).Days(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(((byte)0).Hours(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(((byte)0).Weeks(), Is.EqualTo(TimeSpan.Zero)); + }); } } diff --git a/X10D.Tests/src/Time/CharSpanTests.cs b/X10D.Tests/src/Time/CharSpanTests.cs index 6a3f4cf..ec35528 100644 --- a/X10D.Tests/src/Time/CharSpanTests.cs +++ b/X10D.Tests/src/Time/CharSpanTests.cs @@ -1,12 +1,12 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Time; namespace X10D.Tests.Time; -[TestClass] +[TestFixture] public class CharSpanTests { - [TestMethod] + [Test] public void ToTimeSpan_ShouldReturnCorrectTimeSpan_GivenSpanOfCharacters() { ReadOnlySpan value = "1y 1mo 1w 1d 1h 1m 1s 1ms".AsSpan(); @@ -20,12 +20,12 @@ public class CharSpanTests expected += TimeSpan.FromDays(30); expected += TimeSpan.FromDays(365); - Assert.AreEqual(expected, value.ToTimeSpan()); + Assert.That(value.ToTimeSpan(), Is.EqualTo(expected)); } - [TestMethod] + [Test] public void ToTimeSpan_ShouldReturnZero_GivenInvalidSpanOfCharacters() { - Assert.AreEqual(TimeSpan.Zero, "Hello World".AsSpan().ToTimeSpan()); + Assert.That("Hello World".AsSpan().ToTimeSpan(), Is.EqualTo(TimeSpan.Zero)); } } diff --git a/X10D.Tests/src/Time/DateOnlyTests.cs b/X10D.Tests/src/Time/DateOnlyTests.cs index d58b9dc..5135446 100644 --- a/X10D.Tests/src/Time/DateOnlyTests.cs +++ b/X10D.Tests/src/Time/DateOnlyTests.cs @@ -1,13 +1,13 @@ #if NET6_0_OR_GREATER -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Time; namespace X10D.Tests.Time; -[TestClass] +[TestFixture] public class DateOnlyTests { - [TestMethod] + [Test] public void Age_ShouldBe17_Given31December1991Birthday_And30December2017Date() { var reference = new DateOnly(2017, 12, 30); @@ -15,10 +15,10 @@ public class DateOnlyTests int age = birthday.Age(reference); - Assert.AreEqual(17, age); + Assert.That(age, Is.EqualTo(17)); } - [TestMethod] + [Test] public void Age_ShouldBe18_Given31December1991Birthday_And1January2018Date() { var reference = new DateOnly(2018, 1, 1); @@ -26,10 +26,10 @@ public class DateOnlyTests int age = birthday.Age(reference); - Assert.AreEqual(18, age); + Assert.That(age, Is.EqualTo(18)); } - [TestMethod] + [Test] public void Age_ShouldBe18_Given31December1991Birthday_And31December2017Date() { var reference = new DateOnly(2017, 12, 31); @@ -37,137 +37,140 @@ public class DateOnlyTests int age = birthday.Age(reference); - Assert.AreEqual(18, age); + Assert.That(age, Is.EqualTo(18)); } - [TestMethod] + [Test] public void Deconstruct_ShouldDeconstructToTuple_GivenDateOnly() { var date = new DateOnly(2017, 12, 31); (int year, int month, int day) = date; - Assert.AreEqual(2017, year); - Assert.AreEqual(12, month); - Assert.AreEqual(31, day); + Assert.That(year, Is.EqualTo(2017)); + Assert.That(month, Is.EqualTo(12)); + Assert.That(day, Is.EqualTo(31)); } - [TestMethod] + [Test] public void First_ShouldBeSaturday_Given1Jan2000() { var date = new DateOnly(2000, 1, 1); - Assert.AreEqual(new DateOnly(2000, 1, 1), date.First(DayOfWeek.Saturday)); - Assert.AreEqual(new DateOnly(2000, 1, 2), date.First(DayOfWeek.Sunday)); - Assert.AreEqual(new DateOnly(2000, 1, 3), date.First(DayOfWeek.Monday)); - Assert.AreEqual(new DateOnly(2000, 1, 4), date.First(DayOfWeek.Tuesday)); - Assert.AreEqual(new DateOnly(2000, 1, 5), date.First(DayOfWeek.Wednesday)); - Assert.AreEqual(new DateOnly(2000, 1, 6), date.First(DayOfWeek.Thursday)); - Assert.AreEqual(new DateOnly(2000, 1, 7), date.First(DayOfWeek.Friday)); + Assert.Multiple(() => + { + Assert.That(date.First(DayOfWeek.Saturday), Is.EqualTo(new DateOnly(2000, 1, 1))); + Assert.That(date.First(DayOfWeek.Sunday), Is.EqualTo(new DateOnly(2000, 1, 2))); + Assert.That(date.First(DayOfWeek.Monday), Is.EqualTo(new DateOnly(2000, 1, 3))); + Assert.That(date.First(DayOfWeek.Tuesday), Is.EqualTo(new DateOnly(2000, 1, 4))); + Assert.That(date.First(DayOfWeek.Wednesday), Is.EqualTo(new DateOnly(2000, 1, 5))); + Assert.That(date.First(DayOfWeek.Thursday), Is.EqualTo(new DateOnly(2000, 1, 6))); + Assert.That(date.First(DayOfWeek.Friday), Is.EqualTo(new DateOnly(2000, 1, 7))); + }); } - [TestMethod] + [Test] public void FirstDayOfMonth_ShouldBe1st_GivenToday() { DateOnly today = DateOnly.FromDateTime(DateTime.Now.Date); - Assert.AreEqual(new DateOnly(today.Year, today.Month, 1), today.FirstDayOfMonth()); + Assert.That(today.FirstDayOfMonth(), Is.EqualTo(new DateOnly(today.Year, today.Month, 1))); } - [TestMethod] + [Test] public void GetIso8601WeekOfYear_ShouldReturn1_Given4January1970() { var date = new DateOnly(1970, 1, 4); int iso8601WeekOfYear = date.GetIso8601WeekOfYear(); - Assert.AreEqual(1, iso8601WeekOfYear); + Assert.That(iso8601WeekOfYear, Is.EqualTo(1)); } - [TestMethod] + [Test] public void GetIso8601WeekOfYear_ShouldReturn1_Given31December1969() { var date = new DateOnly(1969, 12, 31); int iso8601WeekOfYear = date.GetIso8601WeekOfYear(); - Assert.AreEqual(1, iso8601WeekOfYear); + Assert.That(iso8601WeekOfYear, Is.EqualTo(1)); } - [TestMethod] + [Test] public void GetIso8601WeekOfYear_ShouldReturn53_Given31December1970() { var date = new DateOnly(1970, 12, 31); int iso8601WeekOfYear = date.GetIso8601WeekOfYear(); - Assert.AreEqual(53, iso8601WeekOfYear); + Assert.That(iso8601WeekOfYear, Is.EqualTo(53)); } - [TestMethod] + [Test] public void IsLeapYear_ShouldBeFalse_Given1999() { var date = new DateOnly(1999, 1, 1); - Assert.IsFalse(date.IsLeapYear()); + Assert.That(date.IsLeapYear(), Is.False); } - [TestMethod] + [Test] public void IsLeapYear_ShouldBeTrue_Given2000() { var date = new DateOnly(2000, 1, 1); - Assert.IsTrue(date.IsLeapYear()); + Assert.That(date.IsLeapYear()); } - [TestMethod] + [Test] public void IsLeapYear_ShouldBeFalse_Given2001() { var date = new DateOnly(2001, 1, 1); - Assert.IsFalse(date.IsLeapYear()); + Assert.That(date.IsLeapYear(), Is.False); } - [TestMethod] + [Test] public void IsLeapYear_ShouldBeFalse_Given2100() { var date = new DateOnly(2100, 1, 1); - Assert.IsFalse(date.IsLeapYear()); + Assert.That(date.IsLeapYear(), Is.False); } - [TestMethod] + [Test] public void LastSaturday_ShouldBe29th_Given1Jan2000() { var date = new DateOnly(2000, 1, 1); - Assert.AreEqual(new DateOnly(2000, 1, 29), date.Last(DayOfWeek.Saturday)); - Assert.AreEqual(new DateOnly(2000, 1, 30), date.Last(DayOfWeek.Sunday)); - Assert.AreEqual(new DateOnly(2000, 1, 31), date.Last(DayOfWeek.Monday)); - Assert.AreEqual(new DateOnly(2000, 1, 25), date.Last(DayOfWeek.Tuesday)); - Assert.AreEqual(new DateOnly(2000, 1, 26), date.Last(DayOfWeek.Wednesday)); - Assert.AreEqual(new DateOnly(2000, 1, 27), date.Last(DayOfWeek.Thursday)); - Assert.AreEqual(new DateOnly(2000, 1, 28), date.Last(DayOfWeek.Friday)); + Assert.That(date.Last(DayOfWeek.Saturday), Is.EqualTo(new DateOnly(2000, 1, 29))); + Assert.That(date.Last(DayOfWeek.Sunday), Is.EqualTo(new DateOnly(2000, 1, 30))); + Assert.That(date.Last(DayOfWeek.Monday), Is.EqualTo(new DateOnly(2000, 1, 31))); + Assert.That(date.Last(DayOfWeek.Tuesday), Is.EqualTo(new DateOnly(2000, 1, 25))); + Assert.That(date.Last(DayOfWeek.Wednesday), Is.EqualTo(new DateOnly(2000, 1, 26))); + Assert.That(date.Last(DayOfWeek.Thursday), Is.EqualTo(new DateOnly(2000, 1, 27))); + Assert.That(date.Last(DayOfWeek.Friday), Is.EqualTo(new DateOnly(2000, 1, 28))); } - [TestMethod] + [Test] public void LastDayOfMonth_ShouldBe28th_GivenFebruary1999() { var february = new DateOnly(1999, 2, 1); - Assert.AreEqual(new DateOnly(february.Year, february.Month, 28), february.LastDayOfMonth()); + Assert.That(february.LastDayOfMonth(), Is.EqualTo(new DateOnly(february.Year, february.Month, 28))); } - [TestMethod] + [Test] public void LastDayOfMonth_ShouldBe29th_GivenFebruary2000() { var february = new DateOnly(2000, 2, 1); - Assert.AreEqual(new DateOnly(february.Year, february.Month, 29), february.LastDayOfMonth()); + Assert.That(february.LastDayOfMonth(), Is.EqualTo(new DateOnly(february.Year, february.Month, 29))); } - [TestMethod] + [Test] public void LastDayOfMonth_ShouldBe28th_GivenFebruary2001() { var february = new DateOnly(2001, 2, 1); - Assert.AreEqual(new DateOnly(february.Year, february.Month, 28), february.LastDayOfMonth()); + Assert.That(february.LastDayOfMonth(), Is.EqualTo(new DateOnly(february.Year, february.Month, 28))); } - [TestMethod] + [Test] public void LastDayOfMonth_ShouldBe30th_GivenAprilJuneSeptemberNovember() { var april = new DateOnly(2000, 4, 1); @@ -175,13 +178,13 @@ public class DateOnlyTests var september = new DateOnly(2000, 9, 1); var november = new DateOnly(2000, 11, 1); - Assert.AreEqual(new DateOnly(april.Year, april.Month, 30), april.LastDayOfMonth()); - Assert.AreEqual(new DateOnly(june.Year, june.Month, 30), june.LastDayOfMonth()); - Assert.AreEqual(new DateOnly(september.Year, september.Month, 30), september.LastDayOfMonth()); - Assert.AreEqual(new DateOnly(november.Year, november.Month, 30), november.LastDayOfMonth()); + Assert.That(april.LastDayOfMonth(), Is.EqualTo(new DateOnly(april.Year, april.Month, 30))); + Assert.That(june.LastDayOfMonth(), Is.EqualTo(new DateOnly(june.Year, june.Month, 30))); + Assert.That(september.LastDayOfMonth(), Is.EqualTo(new DateOnly(september.Year, september.Month, 30))); + Assert.That(november.LastDayOfMonth(), Is.EqualTo(new DateOnly(november.Year, november.Month, 30))); } - [TestMethod] + [Test] public void LastDayOfMonth_ShouldBe31st_GivenJanuaryMarchMayJulyAugustOctoberDecember() { var january = new DateOnly(2000, 1, 1); @@ -192,39 +195,39 @@ public class DateOnlyTests var october = new DateOnly(2000, 10, 1); var december = new DateOnly(2000, 12, 1); - Assert.AreEqual(new DateOnly(january.Year, january.Month, 31), january.LastDayOfMonth()); - Assert.AreEqual(new DateOnly(march.Year, march.Month, 31), march.LastDayOfMonth()); - Assert.AreEqual(new DateOnly(may.Year, may.Month, 31), may.LastDayOfMonth()); - Assert.AreEqual(new DateOnly(july.Year, july.Month, 31), july.LastDayOfMonth()); - Assert.AreEqual(new DateOnly(august.Year, august.Month, 31), august.LastDayOfMonth()); - Assert.AreEqual(new DateOnly(october.Year, october.Month, 31), october.LastDayOfMonth()); - Assert.AreEqual(new DateOnly(december.Year, december.Month, 31), december.LastDayOfMonth()); + Assert.That(january.LastDayOfMonth(), Is.EqualTo(new DateOnly(january.Year, january.Month, 31))); + Assert.That(march.LastDayOfMonth(), Is.EqualTo(new DateOnly(march.Year, march.Month, 31))); + Assert.That(may.LastDayOfMonth(), Is.EqualTo(new DateOnly(may.Year, may.Month, 31))); + Assert.That(july.LastDayOfMonth(), Is.EqualTo(new DateOnly(july.Year, july.Month, 31))); + Assert.That(august.LastDayOfMonth(), Is.EqualTo(new DateOnly(august.Year, august.Month, 31))); + Assert.That(october.LastDayOfMonth(), Is.EqualTo(new DateOnly(october.Year, october.Month, 31))); + Assert.That(december.LastDayOfMonth(), Is.EqualTo(new DateOnly(december.Year, december.Month, 31))); } - [TestMethod] + [Test] public void NextSaturday_ShouldBe8th_Given1Jan2000() { var date = new DateOnly(2000, 1, 1); - Assert.AreEqual(new DateOnly(2000, 1, 8), date.Next(DayOfWeek.Saturday)); + Assert.That(date.Next(DayOfWeek.Saturday), Is.EqualTo(new DateOnly(2000, 1, 8))); } - [TestMethod] + [Test] public void ToUnixTimeMilliseconds_ShouldBe946684800000_Given1Jan2000() { var date = new DateOnly(2000, 1, 1); var time = new TimeOnly(0, 0, 0); - Assert.AreEqual(946684800000, date.ToUnixTimeMilliseconds(time)); + Assert.That(date.ToUnixTimeMilliseconds(time), Is.EqualTo(946684800000)); } - [TestMethod] + [Test] public void ToUnixTimeSeconds_ShouldBe946684800_Given1Jan2000() { var date = new DateOnly(2000, 1, 1); var time = new TimeOnly(0, 0, 0); - Assert.AreEqual(946684800, date.ToUnixTimeSeconds(time)); + Assert.That(date.ToUnixTimeSeconds(time), Is.EqualTo(946684800)); } } #endif diff --git a/X10D.Tests/src/Time/DateTimeOffsetTests.cs b/X10D.Tests/src/Time/DateTimeOffsetTests.cs index 971d58d..77c8fff 100644 --- a/X10D.Tests/src/Time/DateTimeOffsetTests.cs +++ b/X10D.Tests/src/Time/DateTimeOffsetTests.cs @@ -1,12 +1,12 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Time; namespace X10D.Tests.Time; -[TestClass] +[TestFixture] public class DateTimeOffsetTests { - [TestMethod] + [Test] public void Age_ShouldBe17_Given31December1991Birthday_And30December2017Date() { var reference = new DateTime(2017, 12, 30); @@ -14,10 +14,10 @@ public class DateTimeOffsetTests int age = birthday.Age(reference); - Assert.AreEqual(17, age); + Assert.That(age, Is.EqualTo(17)); } - [TestMethod] + [Test] public void Age_ShouldBe18_Given31December1991Birthday_And1January2018Date() { var reference = new DateTime(2018, 1, 1); @@ -25,10 +25,10 @@ public class DateTimeOffsetTests int age = birthday.Age(reference); - Assert.AreEqual(18, age); + Assert.That(age, Is.EqualTo(18)); } - [TestMethod] + [Test] public void Age_ShouldBe18_Given31December1991Birthday_And31December2017Date() { var reference = new DateTime(2017, 12, 31); @@ -36,126 +36,132 @@ public class DateTimeOffsetTests int age = birthday.Age(reference); - Assert.AreEqual(18, age); + Assert.That(age, Is.EqualTo(18)); } - [TestMethod] + [Test] public void First_ShouldBeSaturday_Given1Jan2000() { DateTimeOffset date = new DateTime(2000, 1, 1); - Assert.AreEqual(new DateTime(2000, 1, 1), date.First(DayOfWeek.Saturday)); - Assert.AreEqual(new DateTime(2000, 1, 2), date.First(DayOfWeek.Sunday)); - Assert.AreEqual(new DateTime(2000, 1, 3), date.First(DayOfWeek.Monday)); - Assert.AreEqual(new DateTime(2000, 1, 4), date.First(DayOfWeek.Tuesday)); - Assert.AreEqual(new DateTime(2000, 1, 5), date.First(DayOfWeek.Wednesday)); - Assert.AreEqual(new DateTime(2000, 1, 6), date.First(DayOfWeek.Thursday)); - Assert.AreEqual(new DateTime(2000, 1, 7), date.First(DayOfWeek.Friday)); + Assert.Multiple(() => + { + Assert.That(date.First(DayOfWeek.Saturday), Is.EqualTo((DateTimeOffset)new DateTime(2000, 1, 1))); + Assert.That(date.First(DayOfWeek.Sunday), Is.EqualTo((DateTimeOffset)new DateTime(2000, 1, 2))); + Assert.That(date.First(DayOfWeek.Monday), Is.EqualTo((DateTimeOffset)new DateTime(2000, 1, 3))); + Assert.That(date.First(DayOfWeek.Tuesday), Is.EqualTo((DateTimeOffset)new DateTime(2000, 1, 4))); + Assert.That(date.First(DayOfWeek.Wednesday), Is.EqualTo((DateTimeOffset)new DateTime(2000, 1, 5))); + Assert.That(date.First(DayOfWeek.Thursday), Is.EqualTo((DateTimeOffset)new DateTime(2000, 1, 6))); + Assert.That(date.First(DayOfWeek.Friday), Is.EqualTo((DateTimeOffset)new DateTime(2000, 1, 7))); + }); } - [TestMethod] + [Test] public void FirstDayOfMonth_ShouldBe1st_GivenToday() { DateTimeOffset today = DateTime.UtcNow.Date; var first = new DateTimeOffset(today.Year, today.Month, 1, 0, 0, 0, today.Offset); - Assert.AreEqual(first, today.FirstDayOfMonth()); + Assert.That(today.FirstDayOfMonth(), Is.EqualTo(first)); } - [TestMethod] + [Test] public void GetIso8601WeekOfYear_ShouldReturn1_Given4January1970() { DateTimeOffset date = new DateTime(1970, 1, 4); int iso8601WeekOfYear = date.GetIso8601WeekOfYear(); - Assert.AreEqual(1, iso8601WeekOfYear); + Assert.That(iso8601WeekOfYear, Is.EqualTo(1)); } - [TestMethod] + [Test] public void GetIso8601WeekOfYear_ShouldReturn1_Given31December1969() { DateTimeOffset date = new DateTime(1969, 12, 31); int iso8601WeekOfYear = date.GetIso8601WeekOfYear(); - Assert.AreEqual(1, iso8601WeekOfYear); + Assert.That(iso8601WeekOfYear, Is.EqualTo(1)); } - [TestMethod] + [Test] public void GetIso8601WeekOfYear_ShouldReturn53_Given31December1970() { DateTimeOffset date = new DateTime(1970, 12, 31); int iso8601WeekOfYear = date.GetIso8601WeekOfYear(); - Assert.AreEqual(53, iso8601WeekOfYear); + Assert.That(iso8601WeekOfYear, Is.EqualTo(53)); } - [TestMethod] + [Test] public void IsLeapYear_ShouldBeFalse_Given1999() { DateTimeOffset date = new DateTime(1999, 1, 1); - Assert.IsFalse(date.IsLeapYear()); + Assert.That(date.IsLeapYear(), Is.False); } - [TestMethod] + [Test] public void IsLeapYear_ShouldBeTrue_Given2000() { DateTimeOffset date = new DateTime(2000, 1, 1); - Assert.IsTrue(date.IsLeapYear()); + Assert.That(date.IsLeapYear()); } - [TestMethod] + [Test] public void IsLeapYear_ShouldBeFalse_Given2001() { DateTimeOffset date = new DateTime(2001, 1, 1); - Assert.IsFalse(date.IsLeapYear()); + Assert.That(date.IsLeapYear(), Is.False); } - [TestMethod] + [Test] public void IsLeapYear_ShouldBeFalse_Given2100() { DateTimeOffset date = new DateTime(2100, 1, 1); - Assert.IsFalse(date.IsLeapYear()); + Assert.That(date.IsLeapYear(), Is.False); } - [TestMethod] + [Test] public void LastSaturday_ShouldBe29th_Given1Jan2000() { DateTimeOffset date = new DateTime(2000, 1, 1); - Assert.AreEqual(new DateTime(2000, 1, 29), date.Last(DayOfWeek.Saturday)); - Assert.AreEqual(new DateTime(2000, 1, 30), date.Last(DayOfWeek.Sunday)); - Assert.AreEqual(new DateTime(2000, 1, 31), date.Last(DayOfWeek.Monday)); - Assert.AreEqual(new DateTime(2000, 1, 25), date.Last(DayOfWeek.Tuesday)); - Assert.AreEqual(new DateTime(2000, 1, 26), date.Last(DayOfWeek.Wednesday)); - Assert.AreEqual(new DateTime(2000, 1, 27), date.Last(DayOfWeek.Thursday)); - Assert.AreEqual(new DateTime(2000, 1, 28), date.Last(DayOfWeek.Friday)); + Assert.Multiple(() => + { + Assert.That(date.Last(DayOfWeek.Saturday), Is.EqualTo((DateTimeOffset)new DateTime(2000, 1, 29))); + Assert.That(date.Last(DayOfWeek.Sunday), Is.EqualTo((DateTimeOffset)new DateTime(2000, 1, 30))); + Assert.That(date.Last(DayOfWeek.Monday), Is.EqualTo((DateTimeOffset)new DateTime(2000, 1, 31))); + Assert.That(date.Last(DayOfWeek.Tuesday), Is.EqualTo((DateTimeOffset)new DateTime(2000, 1, 25))); + Assert.That(date.Last(DayOfWeek.Wednesday), Is.EqualTo((DateTimeOffset)new DateTime(2000, 1, 26))); + Assert.That(date.Last(DayOfWeek.Thursday), Is.EqualTo((DateTimeOffset)new DateTime(2000, 1, 27))); + Assert.That(date.Last(DayOfWeek.Friday), Is.EqualTo((DateTimeOffset)new DateTime(2000, 1, 28))); + }); } - [TestMethod] + [Test] public void LastDayOfMonth_ShouldBe28th_GivenFebruary1999() { DateTimeOffset february = new DateTime(1999, 2, 1); - Assert.AreEqual(new DateTime(february.Year, february.Month, 28), february.LastDayOfMonth()); + Assert.That(february.LastDayOfMonth(), Is.EqualTo((DateTimeOffset)new DateTime(february.Year, february.Month, 28))); } - [TestMethod] + [Test] public void LastDayOfMonth_ShouldBe29th_GivenFebruary2000() { DateTimeOffset february = new DateTime(2000, 2, 1); - Assert.AreEqual(new DateTime(february.Year, february.Month, 29), february.LastDayOfMonth()); + Assert.That(february.LastDayOfMonth(), Is.EqualTo((DateTimeOffset)new DateTime(february.Year, february.Month, 29))); } - [TestMethod] + [Test] public void LastDayOfMonth_ShouldBe28th_GivenFebruary2001() { DateTimeOffset february = new DateTime(2001, 2, 1); - Assert.AreEqual(new DateTime(february.Year, february.Month, 28), february.LastDayOfMonth()); + Assert.That(february.LastDayOfMonth(), Is.EqualTo((DateTimeOffset)new DateTime(february.Year, february.Month, 28))); } - [TestMethod] + [Test] public void LastDayOfMonth_ShouldBe30th_GivenAprilJuneSeptemberNovember() { DateTimeOffset april = new DateTime(2000, 4, 1); @@ -163,13 +169,13 @@ public class DateTimeOffsetTests DateTimeOffset september = new DateTime(2000, 9, 1); DateTimeOffset november = new DateTime(2000, 11, 1); - Assert.AreEqual(new DateTime(april.Year, april.Month, 30), april.LastDayOfMonth()); - Assert.AreEqual(new DateTime(june.Year, june.Month, 30), june.LastDayOfMonth()); - Assert.AreEqual(new DateTime(september.Year, september.Month, 30), september.LastDayOfMonth()); - Assert.AreEqual(new DateTime(november.Year, november.Month, 30), november.LastDayOfMonth()); + Assert.That(april.LastDayOfMonth(), Is.EqualTo((DateTimeOffset)new DateTime(april.Year, april.Month, 30))); + Assert.That(june.LastDayOfMonth(), Is.EqualTo((DateTimeOffset)new DateTime(june.Year, june.Month, 30))); + Assert.That(september.LastDayOfMonth(), Is.EqualTo((DateTimeOffset)new DateTime(september.Year, september.Month, 30))); + Assert.That(november.LastDayOfMonth(), Is.EqualTo((DateTimeOffset)new DateTime(november.Year, november.Month, 30))); } - [TestMethod] + [Test] public void LastDayOfMonth_ShouldBe31st_GivenJanuaryMarchMayJulyAugustOctoberDecember() { DateTimeOffset january = new DateTime(2000, 1, 1); @@ -180,20 +186,20 @@ public class DateTimeOffsetTests DateTimeOffset october = new DateTime(2000, 10, 1); DateTimeOffset december = new DateTime(2000, 12, 1); - Assert.AreEqual(new DateTime(january.Year, january.Month, 31), january.LastDayOfMonth()); - Assert.AreEqual(new DateTime(march.Year, march.Month, 31), march.LastDayOfMonth()); - Assert.AreEqual(new DateTime(may.Year, may.Month, 31), may.LastDayOfMonth()); - Assert.AreEqual(new DateTime(july.Year, july.Month, 31), july.LastDayOfMonth()); - Assert.AreEqual(new DateTime(august.Year, august.Month, 31), august.LastDayOfMonth()); - Assert.AreEqual(new DateTime(october.Year, october.Month, 31), october.LastDayOfMonth()); - Assert.AreEqual(new DateTime(december.Year, december.Month, 31), december.LastDayOfMonth()); + Assert.That(january.LastDayOfMonth(), Is.EqualTo((DateTimeOffset)new DateTime(january.Year, january.Month, 31))); + Assert.That(march.LastDayOfMonth(), Is.EqualTo((DateTimeOffset)new DateTime(march.Year, march.Month, 31))); + Assert.That(may.LastDayOfMonth(), Is.EqualTo((DateTimeOffset)new DateTime(may.Year, may.Month, 31))); + Assert.That(july.LastDayOfMonth(), Is.EqualTo((DateTimeOffset)new DateTime(july.Year, july.Month, 31))); + Assert.That(august.LastDayOfMonth(), Is.EqualTo((DateTimeOffset)new DateTime(august.Year, august.Month, 31))); + Assert.That(october.LastDayOfMonth(), Is.EqualTo((DateTimeOffset)new DateTime(october.Year, october.Month, 31))); + Assert.That(december.LastDayOfMonth(), Is.EqualTo((DateTimeOffset)new DateTime(december.Year, december.Month, 31))); } - [TestMethod] + [Test] public void NextSaturday_ShouldBe8th_Given1Jan2000() { DateTimeOffset date = new DateTime(2000, 1, 1); - Assert.AreEqual(new DateTime(2000, 1, 8), date.Next(DayOfWeek.Saturday)); + Assert.That(date.Next(DayOfWeek.Saturday), Is.EqualTo((DateTimeOffset)new DateTime(2000, 1, 8))); } } diff --git a/X10D.Tests/src/Time/DateTimeTests.cs b/X10D.Tests/src/Time/DateTimeTests.cs index 7fc9f50..ed834b3 100644 --- a/X10D.Tests/src/Time/DateTimeTests.cs +++ b/X10D.Tests/src/Time/DateTimeTests.cs @@ -1,12 +1,12 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Time; namespace X10D.Tests.Time; -[TestClass] +[TestFixture] public class DateTimeTests { - [TestMethod] + [Test] public void Age_ShouldBe17_Given31December1991Birthday_And30December2017Date() { var reference = new DateTime(2017, 12, 30); @@ -14,10 +14,10 @@ public class DateTimeTests int age = birthday.Age(reference); - Assert.AreEqual(17, age); + Assert.That(age, Is.EqualTo(17)); } - [TestMethod] + [Test] public void Age_ShouldBe18_Given31December1991Birthday_And1January2018Date() { var reference = new DateTime(2018, 1, 1); @@ -25,10 +25,10 @@ public class DateTimeTests int age = birthday.Age(reference); - Assert.AreEqual(18, age); + Assert.That(age, Is.EqualTo(18)); } - [TestMethod] + [Test] public void Age_ShouldBe18_Given31December1991Birthday_And31December2017Date() { var reference = new DateTime(2017, 12, 31); @@ -36,125 +36,127 @@ public class DateTimeTests int age = birthday.Age(reference); - Assert.AreEqual(18, age); + Assert.That(age, Is.EqualTo(18)); } - [TestMethod] + [Test] public void First_ShouldBeSaturday_Given1Jan2000() { var date = new DateTime(2000, 1, 1); - Assert.AreEqual(new DateTime(2000, 1, 1), date.First(DayOfWeek.Saturday)); - Assert.AreEqual(new DateTime(2000, 1, 2), date.First(DayOfWeek.Sunday)); - Assert.AreEqual(new DateTime(2000, 1, 3), date.First(DayOfWeek.Monday)); - Assert.AreEqual(new DateTime(2000, 1, 4), date.First(DayOfWeek.Tuesday)); - Assert.AreEqual(new DateTime(2000, 1, 5), date.First(DayOfWeek.Wednesday)); - Assert.AreEqual(new DateTime(2000, 1, 6), date.First(DayOfWeek.Thursday)); - Assert.AreEqual(new DateTime(2000, 1, 7), date.First(DayOfWeek.Friday)); + Assert.That(date.First(DayOfWeek.Saturday), Is.EqualTo(new DateTime(2000, 1, 1))); + Assert.That(date.First(DayOfWeek.Sunday), Is.EqualTo(new DateTime(2000, 1, 2))); + Assert.That(date.First(DayOfWeek.Monday), Is.EqualTo(new DateTime(2000, 1, 3))); + Assert.That(date.First(DayOfWeek.Tuesday), Is.EqualTo(new DateTime(2000, 1, 4))); + Assert.That(date.First(DayOfWeek.Wednesday), Is.EqualTo(new DateTime(2000, 1, 5))); + Assert.That(date.First(DayOfWeek.Thursday), Is.EqualTo(new DateTime(2000, 1, 6))); + Assert.That(date.First(DayOfWeek.Friday), Is.EqualTo(new DateTime(2000, 1, 7))); } - [TestMethod] + [Test] public void FirstDayOfMonth_ShouldBe1st_GivenToday() { DateTime today = DateTime.Now.Date; - Assert.AreEqual(new DateTime(today.Year, today.Month, 1), today.FirstDayOfMonth()); + Assert.That(today.FirstDayOfMonth(), Is.EqualTo(new DateTime(today.Year, today.Month, 1))); } - [TestMethod] + [Test] public void GetIso8601WeekOfYear_ShouldReturn1_Given4January1970() { var date = new DateTime(1970, 1, 4); int iso8601WeekOfYear = date.GetIso8601WeekOfYear(); - Assert.AreEqual(1, iso8601WeekOfYear); + Assert.That(iso8601WeekOfYear, Is.EqualTo(1)); } - [TestMethod] + [Test] public void GetIso8601WeekOfYear_ShouldReturn1_Given31December1969() { var date = new DateTime(1969, 12, 31); int iso8601WeekOfYear = date.GetIso8601WeekOfYear(); - Assert.AreEqual(1, iso8601WeekOfYear); + Assert.That(iso8601WeekOfYear, Is.EqualTo(1)); } - [TestMethod] + [Test] public void GetIso8601WeekOfYear_ShouldReturn53_Given31December1970() { var date = new DateTime(1970, 12, 31); int iso8601WeekOfYear = date.GetIso8601WeekOfYear(); - Assert.AreEqual(53, iso8601WeekOfYear); + Assert.That(iso8601WeekOfYear, Is.EqualTo(53)); } - [TestMethod] + [Test] public void IsLeapYear_ShouldBeFalse_Given1999() { var date = new DateTime(1999, 1, 1); - Assert.IsFalse(date.IsLeapYear()); + Assert.That(date.IsLeapYear(), Is.False); } - [TestMethod] + [Test] public void IsLeapYear_ShouldBeTrue_Given2000() { var date = new DateTime(2000, 1, 1); - Assert.IsTrue(date.IsLeapYear()); + Assert.That(date.IsLeapYear()); } - [TestMethod] + [Test] public void IsLeapYear_ShouldBeFalse_Given2001() { var date = new DateTime(2001, 1, 1); - Assert.IsFalse(date.IsLeapYear()); + Assert.That(date.IsLeapYear(), Is.False); } - [TestMethod] + [Test] public void IsLeapYear_ShouldBeFalse_Given2100() { var date = new DateTime(2100, 1, 1); - Assert.IsFalse(date.IsLeapYear()); + Assert.That(date.IsLeapYear(), Is.False); } - [TestMethod] + [Test] public void LastSaturday_ShouldBe29th_Given1Jan2000() { var date = new DateTime(2000, 1, 1); - - Assert.AreEqual(new DateTime(2000, 1, 29), date.Last(DayOfWeek.Saturday)); - Assert.AreEqual(new DateTime(2000, 1, 30), date.Last(DayOfWeek.Sunday)); - Assert.AreEqual(new DateTime(2000, 1, 31), date.Last(DayOfWeek.Monday)); - Assert.AreEqual(new DateTime(2000, 1, 25), date.Last(DayOfWeek.Tuesday)); - Assert.AreEqual(new DateTime(2000, 1, 26), date.Last(DayOfWeek.Wednesday)); - Assert.AreEqual(new DateTime(2000, 1, 27), date.Last(DayOfWeek.Thursday)); - Assert.AreEqual(new DateTime(2000, 1, 28), date.Last(DayOfWeek.Friday)); + Assert.Multiple(() => + { + Assert.That(date.Last(DayOfWeek.Saturday), Is.EqualTo(new DateTime(2000, 1, 29))); + Assert.That(date.Last(DayOfWeek.Sunday), Is.EqualTo(new DateTime(2000, 1, 30))); + Assert.That(date.Last(DayOfWeek.Monday), Is.EqualTo(new DateTime(2000, 1, 31))); + Assert.That(date.Last(DayOfWeek.Tuesday), Is.EqualTo(new DateTime(2000, 1, 25))); + Assert.That(date.Last(DayOfWeek.Wednesday), Is.EqualTo(new DateTime(2000, 1, 26))); + Assert.That(date.Last(DayOfWeek.Thursday), Is.EqualTo(new DateTime(2000, 1, 27))); + Assert.That(date.Last(DayOfWeek.Friday), Is.EqualTo(new DateTime(2000, 1, 28))); + }); } - [TestMethod] + [Test] public void LastDayOfMonth_ShouldBe28th_GivenFebruary1999() { var february = new DateTime(1999, 2, 1); - Assert.AreEqual(new DateTime(february.Year, february.Month, 28), february.LastDayOfMonth()); + Assert.That(february.LastDayOfMonth(), Is.EqualTo(new DateTime(february.Year, february.Month, 28))); } - [TestMethod] + [Test] public void LastDayOfMonth_ShouldBe29th_GivenFebruary2000() { var february = new DateTime(2000, 2, 1); - Assert.AreEqual(new DateTime(february.Year, february.Month, 29), february.LastDayOfMonth()); + Assert.That(february.LastDayOfMonth(), Is.EqualTo(new DateTime(february.Year, february.Month, 29))); } - [TestMethod] + [Test] public void LastDayOfMonth_ShouldBe28th_GivenFebruary2001() { var february = new DateTime(2001, 2, 1); - Assert.AreEqual(new DateTime(february.Year, february.Month, 28), february.LastDayOfMonth()); + Assert.That(february.LastDayOfMonth(), Is.EqualTo(new DateTime(february.Year, february.Month, 28))); } - [TestMethod] + [Test] public void LastDayOfMonth_ShouldBe30th_GivenAprilJuneSeptemberNovember() { var april = new DateTime(2000, 4, 1); @@ -162,13 +164,16 @@ public class DateTimeTests var september = new DateTime(2000, 9, 1); var november = new DateTime(2000, 11, 1); - Assert.AreEqual(new DateTime(april.Year, april.Month, 30), april.LastDayOfMonth()); - Assert.AreEqual(new DateTime(june.Year, june.Month, 30), june.LastDayOfMonth()); - Assert.AreEqual(new DateTime(september.Year, september.Month, 30), september.LastDayOfMonth()); - Assert.AreEqual(new DateTime(november.Year, november.Month, 30), november.LastDayOfMonth()); + Assert.Multiple(() => + { + Assert.That(april.LastDayOfMonth(), Is.EqualTo(new DateTime(april.Year, april.Month, 30))); + Assert.That(june.LastDayOfMonth(), Is.EqualTo(new DateTime(june.Year, june.Month, 30))); + Assert.That(september.LastDayOfMonth(), Is.EqualTo(new DateTime(september.Year, september.Month, 30))); + Assert.That(november.LastDayOfMonth(), Is.EqualTo(new DateTime(november.Year, november.Month, 30))); + }); } - [TestMethod] + [Test] public void LastDayOfMonth_ShouldBe31st_GivenJanuaryMarchMayJulyAugustOctoberDecember() { var january = new DateTime(2000, 1, 1); @@ -179,36 +184,39 @@ public class DateTimeTests var october = new DateTime(2000, 10, 1); var december = new DateTime(2000, 12, 1); - Assert.AreEqual(new DateTime(january.Year, january.Month, 31), january.LastDayOfMonth()); - Assert.AreEqual(new DateTime(march.Year, march.Month, 31), march.LastDayOfMonth()); - Assert.AreEqual(new DateTime(may.Year, may.Month, 31), may.LastDayOfMonth()); - Assert.AreEqual(new DateTime(july.Year, july.Month, 31), july.LastDayOfMonth()); - Assert.AreEqual(new DateTime(august.Year, august.Month, 31), august.LastDayOfMonth()); - Assert.AreEqual(new DateTime(october.Year, october.Month, 31), october.LastDayOfMonth()); - Assert.AreEqual(new DateTime(december.Year, december.Month, 31), december.LastDayOfMonth()); + Assert.Multiple(() => + { + Assert.That(january.LastDayOfMonth(), Is.EqualTo(new DateTime(january.Year, january.Month, 31))); + Assert.That(march.LastDayOfMonth(), Is.EqualTo(new DateTime(march.Year, march.Month, 31))); + Assert.That(may.LastDayOfMonth(), Is.EqualTo(new DateTime(may.Year, may.Month, 31))); + Assert.That(july.LastDayOfMonth(), Is.EqualTo(new DateTime(july.Year, july.Month, 31))); + Assert.That(august.LastDayOfMonth(), Is.EqualTo(new DateTime(august.Year, august.Month, 31))); + Assert.That(october.LastDayOfMonth(), Is.EqualTo(new DateTime(october.Year, october.Month, 31))); + Assert.That(december.LastDayOfMonth(), Is.EqualTo(new DateTime(december.Year, december.Month, 31))); + }); } - [TestMethod] + [Test] public void NextSaturday_ShouldBe8th_Given1Jan2000() { var date = new DateTime(2000, 1, 1); - Assert.AreEqual(new DateTime(2000, 1, 8), date.Next(DayOfWeek.Saturday)); + Assert.That(date.Next(DayOfWeek.Saturday), Is.EqualTo(new DateTime(2000, 1, 8))); } - [TestMethod] + [Test] public void ToUnixTimeMilliseconds_ShouldBe946684800000_Given1Jan2000() { var date = new DateTime(2000, 1, 1); - Assert.AreEqual(946684800000, date.ToUnixTimeMilliseconds()); + Assert.That(date.ToUnixTimeMilliseconds(), Is.EqualTo(946684800000)); } - [TestMethod] + [Test] public void ToUnixTimeSeconds_ShouldBe946684800_Given1Jan2000() { var date = new DateTime(2000, 1, 1); - Assert.AreEqual(946684800, date.ToUnixTimeSeconds()); + Assert.That(date.ToUnixTimeSeconds(), Is.EqualTo(946684800)); } } diff --git a/X10D.Tests/src/Time/DecimalTests.cs b/X10D.Tests/src/Time/DecimalTests.cs index cd8cf8b..6ca948c 100644 --- a/X10D.Tests/src/Time/DecimalTests.cs +++ b/X10D.Tests/src/Time/DecimalTests.cs @@ -1,41 +1,41 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Time; namespace X10D.Tests.Time; -[TestClass] +[TestFixture] public class DecimalTests { - [TestMethod] + [Test] public void TicksMillisecondsSecondsMinutesDaysHoursWeeks_ShouldBeZero_GivenZero() { - Assert.AreEqual(TimeSpan.Zero, 0m.Milliseconds()); - Assert.AreEqual(TimeSpan.Zero, 0m.Seconds()); - Assert.AreEqual(TimeSpan.Zero, 0m.Minutes()); - Assert.AreEqual(TimeSpan.Zero, 0m.Days()); - Assert.AreEqual(TimeSpan.Zero, 0m.Hours()); - Assert.AreEqual(TimeSpan.Zero, 0m.Weeks()); + Assert.That(0m.Milliseconds(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(0m.Seconds(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(0m.Minutes(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(0m.Days(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(0m.Hours(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(0m.Weeks(), Is.EqualTo(TimeSpan.Zero)); } - [TestMethod] + [Test] public void TicksMillisecondsSecondsMinutesDaysHoursWeeks_ShouldBePositive_GivenOne() { - Assert.IsTrue(1m.Milliseconds() > TimeSpan.Zero); - Assert.IsTrue(1m.Seconds() > TimeSpan.Zero); - Assert.IsTrue(1m.Minutes() > TimeSpan.Zero); - Assert.IsTrue(1m.Days() > TimeSpan.Zero); - Assert.IsTrue(1m.Hours() > TimeSpan.Zero); - Assert.IsTrue(1m.Weeks() > TimeSpan.Zero); + Assert.That(1m.Milliseconds() > TimeSpan.Zero); + Assert.That(1m.Seconds() > TimeSpan.Zero); + Assert.That(1m.Minutes() > TimeSpan.Zero); + Assert.That(1m.Days() > TimeSpan.Zero); + Assert.That(1m.Hours() > TimeSpan.Zero); + Assert.That(1m.Weeks() > TimeSpan.Zero); } - [TestMethod] + [Test] public void TicksMillisecondsSecondsMinutesDaysHoursWeeks_ShouldBeNegative_GivenMinusOne() { - Assert.IsTrue((-1m).Milliseconds() < TimeSpan.Zero); - Assert.IsTrue((-1m).Seconds() < TimeSpan.Zero); - Assert.IsTrue((-1m).Minutes() < TimeSpan.Zero); - Assert.IsTrue((-1m).Days() < TimeSpan.Zero); - Assert.IsTrue((-1m).Hours() < TimeSpan.Zero); - Assert.IsTrue((-1m).Weeks() < TimeSpan.Zero); + Assert.That((-1m).Milliseconds() < TimeSpan.Zero); + Assert.That((-1m).Seconds() < TimeSpan.Zero); + Assert.That((-1m).Minutes() < TimeSpan.Zero); + Assert.That((-1m).Days() < TimeSpan.Zero); + Assert.That((-1m).Hours() < TimeSpan.Zero); + Assert.That((-1m).Weeks() < TimeSpan.Zero); } } diff --git a/X10D.Tests/src/Time/DoubleTests.cs b/X10D.Tests/src/Time/DoubleTests.cs index 799c1b1..32164c9 100644 --- a/X10D.Tests/src/Time/DoubleTests.cs +++ b/X10D.Tests/src/Time/DoubleTests.cs @@ -1,17 +1,17 @@ #if NET5_0_OR_GREATER -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Time; namespace X10D.Tests.Time; -[TestClass] +[TestFixture] public class DoubleTests { private Half _negativeOne; private Half _one; private Half _zero; - [TestInitialize] + [SetUp] public void Initialize() { _negativeOne = (Half)(-1); @@ -19,37 +19,37 @@ public class DoubleTests _zero = (Half)0; } - [TestMethod] + [Test] public void TicksMillisecondsSecondsMinutesDaysHoursWeeks_ShouldBeZero_GivenZero() { - Assert.AreEqual(TimeSpan.Zero, _zero.Milliseconds()); - Assert.AreEqual(TimeSpan.Zero, _zero.Seconds()); - Assert.AreEqual(TimeSpan.Zero, _zero.Minutes()); - Assert.AreEqual(TimeSpan.Zero, _zero.Days()); - Assert.AreEqual(TimeSpan.Zero, _zero.Hours()); - Assert.AreEqual(TimeSpan.Zero, _zero.Weeks()); + Assert.That(_zero.Milliseconds(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(_zero.Seconds(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(_zero.Minutes(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(_zero.Days(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(_zero.Hours(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(_zero.Weeks(), Is.EqualTo(TimeSpan.Zero)); } - [TestMethod] + [Test] public void TicksMillisecondsSecondsMinutesDaysHoursWeeks_ShouldBePositive_GivenOne() { - Assert.IsTrue(_one.Milliseconds() > TimeSpan.Zero); - Assert.IsTrue(_one.Seconds() > TimeSpan.Zero); - Assert.IsTrue(_one.Minutes() > TimeSpan.Zero); - Assert.IsTrue(_one.Days() > TimeSpan.Zero); - Assert.IsTrue(_one.Hours() > TimeSpan.Zero); - Assert.IsTrue(_one.Weeks() > TimeSpan.Zero); + Assert.That(_one.Milliseconds() > TimeSpan.Zero); + Assert.That(_one.Seconds() > TimeSpan.Zero); + Assert.That(_one.Minutes() > TimeSpan.Zero); + Assert.That(_one.Days() > TimeSpan.Zero); + Assert.That(_one.Hours() > TimeSpan.Zero); + Assert.That(_one.Weeks() > TimeSpan.Zero); } - [TestMethod] + [Test] public void TicksMillisecondsSecondsMinutesDaysHoursWeeks_ShouldBeNegative_GivenMinusOne() { - Assert.IsTrue((_negativeOne).Milliseconds() < TimeSpan.Zero); - Assert.IsTrue((_negativeOne).Seconds() < TimeSpan.Zero); - Assert.IsTrue((_negativeOne).Minutes() < TimeSpan.Zero); - Assert.IsTrue((_negativeOne).Days() < TimeSpan.Zero); - Assert.IsTrue((_negativeOne).Hours() < TimeSpan.Zero); - Assert.IsTrue((_negativeOne).Weeks() < TimeSpan.Zero); + Assert.That((_negativeOne).Milliseconds() < TimeSpan.Zero); + Assert.That((_negativeOne).Seconds() < TimeSpan.Zero); + Assert.That((_negativeOne).Minutes() < TimeSpan.Zero); + Assert.That((_negativeOne).Days() < TimeSpan.Zero); + Assert.That((_negativeOne).Hours() < TimeSpan.Zero); + Assert.That((_negativeOne).Weeks() < TimeSpan.Zero); } } #endif diff --git a/X10D.Tests/src/Time/HalfTests.cs b/X10D.Tests/src/Time/HalfTests.cs index a70aed2..7e8acc7 100644 --- a/X10D.Tests/src/Time/HalfTests.cs +++ b/X10D.Tests/src/Time/HalfTests.cs @@ -1,41 +1,41 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Time; namespace X10D.Tests.Time; -[TestClass] +[TestFixture] public class HalfTests { - [TestMethod] + [Test] public void TicksMillisecondsSecondsMinutesDaysHoursWeeks_ShouldBeZero_GivenZero() { - Assert.AreEqual(TimeSpan.Zero, 0.0.Milliseconds()); - Assert.AreEqual(TimeSpan.Zero, 0.0.Seconds()); - Assert.AreEqual(TimeSpan.Zero, 0.0.Minutes()); - Assert.AreEqual(TimeSpan.Zero, 0.0.Days()); - Assert.AreEqual(TimeSpan.Zero, 0.0.Hours()); - Assert.AreEqual(TimeSpan.Zero, 0.0.Weeks()); + Assert.That(0.0.Milliseconds(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(0.0.Seconds(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(0.0.Minutes(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(0.0.Days(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(0.0.Hours(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(0.0.Weeks(), Is.EqualTo(TimeSpan.Zero)); } - [TestMethod] + [Test] public void TicksMillisecondsSecondsMinutesDaysHoursWeeks_ShouldBePositive_GivenOne() { - Assert.IsTrue(1.0.Milliseconds() > TimeSpan.Zero); - Assert.IsTrue(1.0.Seconds() > TimeSpan.Zero); - Assert.IsTrue(1.0.Minutes() > TimeSpan.Zero); - Assert.IsTrue(1.0.Days() > TimeSpan.Zero); - Assert.IsTrue(1.0.Hours() > TimeSpan.Zero); - Assert.IsTrue(1.0.Weeks() > TimeSpan.Zero); + Assert.That(1.0.Milliseconds() > TimeSpan.Zero); + Assert.That(1.0.Seconds() > TimeSpan.Zero); + Assert.That(1.0.Minutes() > TimeSpan.Zero); + Assert.That(1.0.Days() > TimeSpan.Zero); + Assert.That(1.0.Hours() > TimeSpan.Zero); + Assert.That(1.0.Weeks() > TimeSpan.Zero); } - [TestMethod] + [Test] public void TicksMillisecondsSecondsMinutesDaysHoursWeeks_ShouldBeNegative_GivenMinusOne() { - Assert.IsTrue((-1.0).Milliseconds() < TimeSpan.Zero); - Assert.IsTrue((-1.0).Seconds() < TimeSpan.Zero); - Assert.IsTrue((-1.0).Minutes() < TimeSpan.Zero); - Assert.IsTrue((-1.0).Days() < TimeSpan.Zero); - Assert.IsTrue((-1.0).Hours() < TimeSpan.Zero); - Assert.IsTrue((-1.0).Weeks() < TimeSpan.Zero); + Assert.That((-1.0).Milliseconds() < TimeSpan.Zero); + Assert.That((-1.0).Seconds() < TimeSpan.Zero); + Assert.That((-1.0).Minutes() < TimeSpan.Zero); + Assert.That((-1.0).Days() < TimeSpan.Zero); + Assert.That((-1.0).Hours() < TimeSpan.Zero); + Assert.That((-1.0).Weeks() < TimeSpan.Zero); } } diff --git a/X10D.Tests/src/Time/Int16Tests.cs b/X10D.Tests/src/Time/Int16Tests.cs index f2434fe..58ed0e9 100644 --- a/X10D.Tests/src/Time/Int16Tests.cs +++ b/X10D.Tests/src/Time/Int16Tests.cs @@ -1,90 +1,107 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Time; namespace X10D.Tests.Time; -[TestClass] +[TestFixture] public class Int16Tests { - [TestMethod] + [Test] public void FromUnixTimeMilliseconds_ShouldBeEpoch_GivenZero() { - Assert.AreEqual(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc), ((short)0).FromUnixTimeMilliseconds()); + DateTimeOffset expected = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + Assert.That(((short)0).FromUnixTimeMilliseconds(), Is.EqualTo(expected)); } - [TestMethod] + [Test] public void FromUnixTimeSeconds_ShouldBeEpoch_GivenZero() { - Assert.AreEqual(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc), ((short)0).FromUnixTimeSeconds()); + DateTimeOffset expected = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + Assert.That(((short)0).FromUnixTimeSeconds(), Is.EqualTo(expected)); } - [TestMethod] + [Test] public void IsLeapYear_ShouldBeFalse_GivenMultipleOf100() { - Assert.IsFalse(((short)100).IsLeapYear()); - Assert.IsFalse(((short)-100).IsLeapYear()); - Assert.IsFalse(((short)1900).IsLeapYear()); - Assert.IsFalse(((short)2100).IsLeapYear()); + Assert.Multiple(() => + { + Assert.That(((short)100).IsLeapYear(), Is.False); + Assert.That(((short)-100).IsLeapYear(), Is.False); + Assert.That(((short)1900).IsLeapYear(), Is.False); + Assert.That(((short)2100).IsLeapYear(), Is.False); + }); } - [TestMethod] + [Test] public void IsLeapYear_ShouldBeFalse_GivenOddNumber() { - Assert.IsFalse(((short)1).IsLeapYear()); - Assert.IsFalse(((short)101).IsLeapYear()); - Assert.IsFalse(((short)-101).IsLeapYear()); + Assert.That(((short)1).IsLeapYear(), Is.False); + Assert.That(((short)101).IsLeapYear(), Is.False); + Assert.That(((short)-101).IsLeapYear(), Is.False); } - [TestMethod] + [Test] public void IsLeapYear_ShouldBeTrue_GivenMultipleOf4Or400() { - Assert.IsTrue(((short)-401).IsLeapYear()); - Assert.IsTrue(((short)-105).IsLeapYear()); - Assert.IsTrue(((short)4).IsLeapYear()); - Assert.IsTrue(((short)104).IsLeapYear()); - Assert.IsTrue(((short)400).IsLeapYear()); - Assert.IsTrue(((short)2000).IsLeapYear()); + Assert.Multiple(() => + { + Assert.That(((short)-401).IsLeapYear()); + Assert.That(((short)-105).IsLeapYear()); + Assert.That(((short)4).IsLeapYear()); + Assert.That(((short)104).IsLeapYear()); + Assert.That(((short)400).IsLeapYear()); + Assert.That(((short)2000).IsLeapYear()); + }); } - [TestMethod] + [Test] public void IsLeapYear_ShouldThrow_GivenZero() { - Assert.ThrowsException(() => ((short)0).IsLeapYear()); + Assert.Throws(() => _ = ((short)0).IsLeapYear()); } - [TestMethod] + [Test] public void TicksMillisecondsSecondsMinutesDaysHoursWeeks_ShouldBeNegative_GivenMinusOne() { - Assert.IsTrue(((short)-1).Ticks() < TimeSpan.Zero); - Assert.IsTrue(((short)-1).Milliseconds() < TimeSpan.Zero); - Assert.IsTrue(((short)-1).Seconds() < TimeSpan.Zero); - Assert.IsTrue(((short)-1).Minutes() < TimeSpan.Zero); - Assert.IsTrue(((short)-1).Days() < TimeSpan.Zero); - Assert.IsTrue(((short)-1).Hours() < TimeSpan.Zero); - Assert.IsTrue(((short)-1).Weeks() < TimeSpan.Zero); + Assert.Multiple(() => + { + Assert.That(((short)-1).Ticks(), Is.LessThan(TimeSpan.Zero)); + Assert.That(((short)-1).Milliseconds(), Is.LessThan(TimeSpan.Zero)); + Assert.That(((short)-1).Seconds(), Is.LessThan(TimeSpan.Zero)); + Assert.That(((short)-1).Minutes(), Is.LessThan(TimeSpan.Zero)); + Assert.That(((short)-1).Days(), Is.LessThan(TimeSpan.Zero)); + Assert.That(((short)-1).Hours(), Is.LessThan(TimeSpan.Zero)); + Assert.That(((short)-1).Weeks(), Is.LessThan(TimeSpan.Zero)); + }); } - [TestMethod] + [Test] public void TicksMillisecondsSecondsMinutesDaysHoursWeeks_ShouldBePositive_GivenOne() { - Assert.IsTrue(((short)1).Ticks() > TimeSpan.Zero); - Assert.IsTrue(((short)1).Milliseconds() > TimeSpan.Zero); - Assert.IsTrue(((short)1).Seconds() > TimeSpan.Zero); - Assert.IsTrue(((short)1).Minutes() > TimeSpan.Zero); - Assert.IsTrue(((short)1).Days() > TimeSpan.Zero); - Assert.IsTrue(((short)1).Hours() > TimeSpan.Zero); - Assert.IsTrue(((short)1).Weeks() > TimeSpan.Zero); + Assert.Multiple(() => + { + Assert.That(((short)1).Ticks(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(((short)1).Milliseconds(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(((short)1).Seconds(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(((short)1).Minutes(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(((short)1).Days(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(((short)1).Hours(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(((short)1).Weeks(), Is.GreaterThan(TimeSpan.Zero)); + }); } - [TestMethod] + [Test] public void TicksMillisecondsSecondsMinutesDaysHoursWeeks_ShouldBeZero_GivenZero() { - Assert.AreEqual(TimeSpan.Zero, ((short)0).Ticks()); - Assert.AreEqual(TimeSpan.Zero, ((short)0).Milliseconds()); - Assert.AreEqual(TimeSpan.Zero, ((short)0).Seconds()); - Assert.AreEqual(TimeSpan.Zero, ((short)0).Minutes()); - Assert.AreEqual(TimeSpan.Zero, ((short)0).Days()); - Assert.AreEqual(TimeSpan.Zero, ((short)0).Hours()); - Assert.AreEqual(TimeSpan.Zero, ((short)0).Weeks()); + Assert.Multiple(() => + { + Assert.That(((short)0).Ticks(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(((short)0).Milliseconds(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(((short)0).Seconds(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(((short)0).Minutes(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(((short)0).Days(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(((short)0).Hours(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(((short)0).Weeks(), Is.EqualTo(TimeSpan.Zero)); + }); } } diff --git a/X10D.Tests/src/Time/Int32Tests.cs b/X10D.Tests/src/Time/Int32Tests.cs index 7d6670b..6cbad58 100644 --- a/X10D.Tests/src/Time/Int32Tests.cs +++ b/X10D.Tests/src/Time/Int32Tests.cs @@ -1,90 +1,110 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Time; namespace X10D.Tests.Time; -[TestClass] +[TestFixture] public class Int32Tests { - [TestMethod] + [Test] public void FromUnixTimeMilliseconds_ShouldBeEpoch_GivenZero() { - Assert.AreEqual(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc), 0.FromUnixTimeMilliseconds()); + DateTimeOffset expected = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + Assert.That(0.FromUnixTimeMilliseconds(), Is.EqualTo(expected)); } - [TestMethod] + [Test] public void FromUnixTimeSeconds_ShouldBeEpoch_GivenZero() { - Assert.AreEqual(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc), 0.FromUnixTimeSeconds()); + DateTimeOffset expected = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + Assert.That(0.FromUnixTimeSeconds(), Is.EqualTo(expected)); } - [TestMethod] + [Test] public void IsLeapYear_ShouldBeFalse_GivenMultipleOf100() { - Assert.IsFalse(100.IsLeapYear()); - Assert.IsFalse((-100).IsLeapYear()); - Assert.IsFalse(1900.IsLeapYear()); - Assert.IsFalse(2100.IsLeapYear()); + Assert.Multiple(() => + { + Assert.That(100.IsLeapYear(), Is.False); + Assert.That((-100).IsLeapYear(), Is.False); + Assert.That(1900.IsLeapYear(), Is.False); + Assert.That(2100.IsLeapYear(), Is.False); + }); } - [TestMethod] + [Test] public void IsLeapYear_ShouldBeFalse_GivenOddNumber() { - Assert.IsFalse(1.IsLeapYear()); - Assert.IsFalse(101.IsLeapYear()); - Assert.IsFalse((-101).IsLeapYear()); + Assert.Multiple(() => + { + Assert.That(1.IsLeapYear(), Is.False); + Assert.That(101.IsLeapYear(), Is.False); + Assert.That((-101).IsLeapYear(), Is.False); + }); } - [TestMethod] + [Test] public void IsLeapYear_ShouldBeTrue_GivenMultipleOf4Or400() { - Assert.IsTrue((-401).IsLeapYear()); - Assert.IsTrue((-105).IsLeapYear()); - Assert.IsTrue(4.IsLeapYear()); - Assert.IsTrue(104.IsLeapYear()); - Assert.IsTrue(400.IsLeapYear()); - Assert.IsTrue(2000.IsLeapYear()); + Assert.Multiple(() => + { + Assert.That((-401).IsLeapYear()); + Assert.That((-105).IsLeapYear()); + Assert.That(4.IsLeapYear()); + Assert.That(104.IsLeapYear()); + Assert.That(400.IsLeapYear()); + Assert.That(2000.IsLeapYear()); + }); } - [TestMethod] + [Test] public void IsLeapYear_ShouldThrow_GivenZero() { - Assert.ThrowsException(() => 0.IsLeapYear()); + Assert.Throws(() => _ = 0.IsLeapYear()); } - [TestMethod] + [Test] public void TicksMillisecondsSecondsMinutesDaysHoursWeeks_ShouldBeNegative_GivenMinusOne() { - Assert.IsTrue((-1).Ticks() < TimeSpan.Zero); - Assert.IsTrue((-1).Milliseconds() < TimeSpan.Zero); - Assert.IsTrue((-1).Seconds() < TimeSpan.Zero); - Assert.IsTrue((-1).Minutes() < TimeSpan.Zero); - Assert.IsTrue((-1).Days() < TimeSpan.Zero); - Assert.IsTrue((-1).Hours() < TimeSpan.Zero); - Assert.IsTrue((-1).Weeks() < TimeSpan.Zero); + Assert.Multiple(() => + { + Assert.That((-1).Ticks(), Is.LessThan(TimeSpan.Zero)); + Assert.That((-1).Milliseconds(), Is.LessThan(TimeSpan.Zero)); + Assert.That((-1).Seconds(), Is.LessThan(TimeSpan.Zero)); + Assert.That((-1).Minutes(), Is.LessThan(TimeSpan.Zero)); + Assert.That((-1).Days(), Is.LessThan(TimeSpan.Zero)); + Assert.That((-1).Hours(), Is.LessThan(TimeSpan.Zero)); + Assert.That((-1).Weeks(), Is.LessThan(TimeSpan.Zero)); + }); } - [TestMethod] + [Test] public void TicksMillisecondsSecondsMinutesDaysHoursWeeks_ShouldBePositive_GivenOne() { - Assert.IsTrue(1.Ticks() > TimeSpan.Zero); - Assert.IsTrue(1.Milliseconds() > TimeSpan.Zero); - Assert.IsTrue(1.Seconds() > TimeSpan.Zero); - Assert.IsTrue(1.Minutes() > TimeSpan.Zero); - Assert.IsTrue(1.Days() > TimeSpan.Zero); - Assert.IsTrue(1.Hours() > TimeSpan.Zero); - Assert.IsTrue(1.Weeks() > TimeSpan.Zero); + Assert.Multiple(() => + { + Assert.That(1.Ticks(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(1.Milliseconds(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(1.Seconds(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(1.Minutes(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(1.Days(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(1.Hours(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(1.Weeks(), Is.GreaterThan(TimeSpan.Zero)); + }); } - [TestMethod] + [Test] public void TicksMillisecondsSecondsMinutesDaysHoursWeeks_ShouldBeZero_GivenZero() { - Assert.AreEqual(TimeSpan.Zero, 0.Ticks()); - Assert.AreEqual(TimeSpan.Zero, 0.Milliseconds()); - Assert.AreEqual(TimeSpan.Zero, 0.Seconds()); - Assert.AreEqual(TimeSpan.Zero, 0.Minutes()); - Assert.AreEqual(TimeSpan.Zero, 0.Days()); - Assert.AreEqual(TimeSpan.Zero, 0.Hours()); - Assert.AreEqual(TimeSpan.Zero, 0.Weeks()); + Assert.Multiple(() => + { + Assert.That(0.Ticks(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(0.Milliseconds(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(0.Seconds(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(0.Minutes(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(0.Days(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(0.Hours(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(0.Weeks(), Is.EqualTo(TimeSpan.Zero)); + }); } } diff --git a/X10D.Tests/src/Time/Int64Tests.cs b/X10D.Tests/src/Time/Int64Tests.cs index f0459eb..9b83e67 100644 --- a/X10D.Tests/src/Time/Int64Tests.cs +++ b/X10D.Tests/src/Time/Int64Tests.cs @@ -1,90 +1,110 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Time; namespace X10D.Tests.Time; -[TestClass] +[TestFixture] public class Int64Tests { - [TestMethod] + [Test] public void FromUnixTimeMilliseconds_ShouldBeEpoch_GivenZero() { - Assert.AreEqual(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc), 0L.FromUnixTimeMilliseconds()); + DateTimeOffset expected = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + Assert.That(0L.FromUnixTimeMilliseconds(), Is.EqualTo(expected)); } - [TestMethod] + [Test] public void FromUnixTimeSeconds_ShouldBeEpoch_GivenZero() { - Assert.AreEqual(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc), 0L.FromUnixTimeSeconds()); + DateTimeOffset expected = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + Assert.That(0L.FromUnixTimeSeconds(), Is.EqualTo(expected)); } - [TestMethod] + [Test] public void IsLeapYear_ShouldBeFalse_GivenMultipleOf100() { - Assert.IsFalse(100L.IsLeapYear()); - Assert.IsFalse((-100L).IsLeapYear()); - Assert.IsFalse(1900L.IsLeapYear()); - Assert.IsFalse(2100L.IsLeapYear()); + Assert.Multiple(() => + { + Assert.That(100L.IsLeapYear(), Is.False); + Assert.That((-100L).IsLeapYear(), Is.False); + Assert.That(1900L.IsLeapYear(), Is.False); + Assert.That(2100L.IsLeapYear(), Is.False); + }); } - [TestMethod] + [Test] public void IsLeapYear_ShouldBeFalse_GivenOddNumber() { - Assert.IsFalse(1L.IsLeapYear()); - Assert.IsFalse(101L.IsLeapYear()); - Assert.IsFalse((-101L).IsLeapYear()); + Assert.Multiple(() => + { + Assert.That(1L.IsLeapYear(), Is.False); + Assert.That(101L.IsLeapYear(), Is.False); + Assert.That((-101L).IsLeapYear(), Is.False); + }); } - [TestMethod] + [Test] public void IsLeapYear_ShouldBeTrue_GivenMultipleOf4Or400() { - Assert.IsTrue((-401L).IsLeapYear()); - Assert.IsTrue((-105L).IsLeapYear()); - Assert.IsTrue(4L.IsLeapYear()); - Assert.IsTrue(104L.IsLeapYear()); - Assert.IsTrue(400L.IsLeapYear()); - Assert.IsTrue(2000L.IsLeapYear()); + Assert.Multiple(() => + { + Assert.That((-401L).IsLeapYear()); + Assert.That((-105L).IsLeapYear()); + Assert.That(4L.IsLeapYear()); + Assert.That(104L.IsLeapYear()); + Assert.That(400L.IsLeapYear()); + Assert.That(2000L.IsLeapYear()); + }); } - [TestMethod] + [Test] public void IsLeapYear_ShouldThrow_GivenZero() { - Assert.ThrowsException(() => 0L.IsLeapYear()); + Assert.Throws(() => _ = 0L.IsLeapYear()); } - [TestMethod] + [Test] public void TicksMillisecondsSecondsMinutesDaysHoursWeeks_ShouldBeNegative_GivenMinusOne() { - Assert.IsTrue((-1L).Ticks() < TimeSpan.Zero); - Assert.IsTrue((-1L).Milliseconds() < TimeSpan.Zero); - Assert.IsTrue((-1L).Seconds() < TimeSpan.Zero); - Assert.IsTrue((-1L).Minutes() < TimeSpan.Zero); - Assert.IsTrue((-1L).Days() < TimeSpan.Zero); - Assert.IsTrue((-1L).Hours() < TimeSpan.Zero); - Assert.IsTrue((-1L).Weeks() < TimeSpan.Zero); + Assert.Multiple(() => + { + Assert.That((-1L).Ticks(), Is.LessThan(TimeSpan.Zero)); + Assert.That((-1L).Milliseconds(), Is.LessThan(TimeSpan.Zero)); + Assert.That((-1L).Seconds(), Is.LessThan(TimeSpan.Zero)); + Assert.That((-1L).Minutes(), Is.LessThan(TimeSpan.Zero)); + Assert.That((-1L).Days(), Is.LessThan(TimeSpan.Zero)); + Assert.That((-1L).Hours(), Is.LessThan(TimeSpan.Zero)); + Assert.That((-1L).Weeks(), Is.LessThan(TimeSpan.Zero)); + }); } - [TestMethod] + [Test] public void TicksMillisecondsSecondsMinutesDaysHoursWeeks_ShouldBePositive_GivenOne() { - Assert.IsTrue(1L.Ticks() > TimeSpan.Zero); - Assert.IsTrue(1L.Milliseconds() > TimeSpan.Zero); - Assert.IsTrue(1L.Seconds() > TimeSpan.Zero); - Assert.IsTrue(1L.Minutes() > TimeSpan.Zero); - Assert.IsTrue(1L.Days() > TimeSpan.Zero); - Assert.IsTrue(1L.Hours() > TimeSpan.Zero); - Assert.IsTrue(1L.Weeks() > TimeSpan.Zero); + Assert.Multiple(() => + { + Assert.That(1L.Ticks(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(1L.Milliseconds(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(1L.Seconds(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(1L.Minutes(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(1L.Days(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(1L.Hours(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(1L.Weeks(), Is.GreaterThan(TimeSpan.Zero)); + }); } - [TestMethod] + [Test] public void TicksMillisecondsSecondsMinutesDaysHoursWeeks_ShouldBeZero_GivenZero() { - Assert.AreEqual(TimeSpan.Zero, 0L.Ticks()); - Assert.AreEqual(TimeSpan.Zero, 0L.Milliseconds()); - Assert.AreEqual(TimeSpan.Zero, 0L.Seconds()); - Assert.AreEqual(TimeSpan.Zero, 0L.Minutes()); - Assert.AreEqual(TimeSpan.Zero, 0L.Days()); - Assert.AreEqual(TimeSpan.Zero, 0L.Hours()); - Assert.AreEqual(TimeSpan.Zero, 0L.Weeks()); + Assert.Multiple(() => + { + Assert.That(0L.Ticks(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(0L.Milliseconds(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(0L.Seconds(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(0L.Minutes(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(0L.Days(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(0L.Hours(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(0L.Weeks(), Is.EqualTo(TimeSpan.Zero)); + }); } } diff --git a/X10D.Tests/src/Time/SByteTests.cs b/X10D.Tests/src/Time/SByteTests.cs index 8189c6f..278469b 100644 --- a/X10D.Tests/src/Time/SByteTests.cs +++ b/X10D.Tests/src/Time/SByteTests.cs @@ -1,86 +1,106 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Time; namespace X10D.Tests.Time; -[TestClass] +[TestFixture] [CLSCompliant(false)] public class SByteTests { - [TestMethod] + [Test] public void FromUnixTimeMilliseconds_ShouldBeEpoch_GivenZero() { - Assert.AreEqual(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc), ((sbyte)0).FromUnixTimeMilliseconds()); + DateTimeOffset expected = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + Assert.That(((sbyte)0).FromUnixTimeMilliseconds(), Is.EqualTo(expected)); } - [TestMethod] + [Test] public void FromUnixTimeSeconds_ShouldBeEpoch_GivenZero() { - Assert.AreEqual(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc), ((sbyte)0).FromUnixTimeSeconds()); + DateTimeOffset expected = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + Assert.That(((sbyte)0).FromUnixTimeSeconds(), Is.EqualTo(expected)); } - [TestMethod] + [Test] public void IsLeapYear_ShouldBeFalse_GivenMultipleOf100() { - Assert.IsFalse(((sbyte)100).IsLeapYear()); - Assert.IsFalse(((sbyte)-100).IsLeapYear()); + Assert.Multiple(() => + { + Assert.That(((sbyte)100).IsLeapYear(), Is.False); + Assert.That(((sbyte)-100).IsLeapYear(), Is.False); + }); } - [TestMethod] + [Test] public void IsLeapYear_ShouldBeFalse_GivenOddNumber() { - Assert.IsFalse(((sbyte)1).IsLeapYear()); - Assert.IsFalse(((sbyte)101).IsLeapYear()); - Assert.IsFalse(((sbyte)-101).IsLeapYear()); + Assert.Multiple(() => + { + Assert.That(((sbyte)1).IsLeapYear(), Is.False); + Assert.That(((sbyte)101).IsLeapYear(), Is.False); + Assert.That(((sbyte)-101).IsLeapYear(), Is.False); + }); } - [TestMethod] + [Test] public void IsLeapYear_ShouldBeTrue_GivenMultipleOf4() { - Assert.IsTrue(((sbyte)4).IsLeapYear()); - Assert.IsTrue(((sbyte)104).IsLeapYear()); - Assert.IsTrue(((sbyte)-105).IsLeapYear()); + Assert.Multiple(() => + { + Assert.That(((sbyte)4).IsLeapYear()); + Assert.That(((sbyte)104).IsLeapYear()); + Assert.That(((sbyte)-105).IsLeapYear()); + }); } - [TestMethod] + [Test] public void IsLeapYear_ShouldThrow_GivenZero() { - Assert.ThrowsException(() => ((sbyte)0).IsLeapYear()); + Assert.Throws(() => _ = ((sbyte)0).IsLeapYear()); } - [TestMethod] + [Test] public void TicksMillisecondsSecondsMinutesDaysHoursWeeks_ShouldBeZero_GivenZero() { - Assert.AreEqual(TimeSpan.Zero, ((sbyte)0).Ticks()); - Assert.AreEqual(TimeSpan.Zero, ((sbyte)0).Milliseconds()); - Assert.AreEqual(TimeSpan.Zero, ((sbyte)0).Seconds()); - Assert.AreEqual(TimeSpan.Zero, ((sbyte)0).Minutes()); - Assert.AreEqual(TimeSpan.Zero, ((sbyte)0).Days()); - Assert.AreEqual(TimeSpan.Zero, ((sbyte)0).Hours()); - Assert.AreEqual(TimeSpan.Zero, ((sbyte)0).Weeks()); + Assert.Multiple(() => + { + Assert.That(((sbyte)0).Ticks(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(((sbyte)0).Milliseconds(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(((sbyte)0).Seconds(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(((sbyte)0).Minutes(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(((sbyte)0).Days(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(((sbyte)0).Hours(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(((sbyte)0).Weeks(), Is.EqualTo(TimeSpan.Zero)); + }); } - [TestMethod] + [Test] public void TicksMillisecondsSecondsMinutesDaysHoursWeeks_ShouldBePositive_GivenOne() { - Assert.IsTrue(((sbyte)1).Ticks() > TimeSpan.Zero); - Assert.IsTrue(((sbyte)1).Milliseconds() > TimeSpan.Zero); - Assert.IsTrue(((sbyte)1).Seconds() > TimeSpan.Zero); - Assert.IsTrue(((sbyte)1).Minutes() > TimeSpan.Zero); - Assert.IsTrue(((sbyte)1).Days() > TimeSpan.Zero); - Assert.IsTrue(((sbyte)1).Hours() > TimeSpan.Zero); - Assert.IsTrue(((sbyte)1).Weeks() > TimeSpan.Zero); + Assert.Multiple(() => + { + Assert.That(((sbyte)1).Ticks(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(((sbyte)1).Milliseconds(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(((sbyte)1).Seconds(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(((sbyte)1).Minutes(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(((sbyte)1).Days(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(((sbyte)1).Hours(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(((sbyte)1).Weeks(), Is.GreaterThan(TimeSpan.Zero)); + }); } - [TestMethod] + [Test] public void TicksMillisecondsSecondsMinutesDaysHoursWeeks_ShouldBeNegative_GivenMinusOne() { - Assert.IsTrue(((sbyte)-1).Ticks() < TimeSpan.Zero); - Assert.IsTrue(((sbyte)-1).Milliseconds() < TimeSpan.Zero); - Assert.IsTrue(((sbyte)-1).Seconds() < TimeSpan.Zero); - Assert.IsTrue(((sbyte)-1).Minutes() < TimeSpan.Zero); - Assert.IsTrue(((sbyte)-1).Days() < TimeSpan.Zero); - Assert.IsTrue(((sbyte)-1).Hours() < TimeSpan.Zero); - Assert.IsTrue(((sbyte)-1).Weeks() < TimeSpan.Zero); + Assert.Multiple(() => + { + Assert.That(((sbyte)-1).Ticks(), Is.LessThan(TimeSpan.Zero)); + Assert.That(((sbyte)-1).Milliseconds(), Is.LessThan(TimeSpan.Zero)); + Assert.That(((sbyte)-1).Seconds(), Is.LessThan(TimeSpan.Zero)); + Assert.That(((sbyte)-1).Minutes(), Is.LessThan(TimeSpan.Zero)); + Assert.That(((sbyte)-1).Days(), Is.LessThan(TimeSpan.Zero)); + Assert.That(((sbyte)-1).Hours(), Is.LessThan(TimeSpan.Zero)); + Assert.That(((sbyte)-1).Weeks(), Is.LessThan(TimeSpan.Zero)); + }); } } diff --git a/X10D.Tests/src/Time/SingleTests.cs b/X10D.Tests/src/Time/SingleTests.cs index 6feb82f..cc2f39b 100644 --- a/X10D.Tests/src/Time/SingleTests.cs +++ b/X10D.Tests/src/Time/SingleTests.cs @@ -1,41 +1,41 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Time; namespace X10D.Tests.Time; -[TestClass] +[TestFixture] public class SingleTests { - [TestMethod] + [Test] public void TicksMillisecondsSecondsMinutesDaysHoursWeeks_ShouldBeZero_GivenZero() { - Assert.AreEqual(TimeSpan.Zero, 0f.Milliseconds()); - Assert.AreEqual(TimeSpan.Zero, 0f.Seconds()); - Assert.AreEqual(TimeSpan.Zero, 0f.Minutes()); - Assert.AreEqual(TimeSpan.Zero, 0f.Days()); - Assert.AreEqual(TimeSpan.Zero, 0f.Hours()); - Assert.AreEqual(TimeSpan.Zero, 0f.Weeks()); + Assert.That(0f.Milliseconds(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(0f.Seconds(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(0f.Minutes(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(0f.Days(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(0f.Hours(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(0f.Weeks(), Is.EqualTo(TimeSpan.Zero)); } - [TestMethod] + [Test] public void TicksMillisecondsSecondsMinutesDaysHoursWeeks_ShouldBePositive_GivenOne() { - Assert.IsTrue(1f.Milliseconds() > TimeSpan.Zero); - Assert.IsTrue(1f.Seconds() > TimeSpan.Zero); - Assert.IsTrue(1f.Minutes() > TimeSpan.Zero); - Assert.IsTrue(1f.Days() > TimeSpan.Zero); - Assert.IsTrue(1f.Hours() > TimeSpan.Zero); - Assert.IsTrue(1f.Weeks() > TimeSpan.Zero); + Assert.That(1f.Milliseconds() > TimeSpan.Zero); + Assert.That(1f.Seconds() > TimeSpan.Zero); + Assert.That(1f.Minutes() > TimeSpan.Zero); + Assert.That(1f.Days() > TimeSpan.Zero); + Assert.That(1f.Hours() > TimeSpan.Zero); + Assert.That(1f.Weeks() > TimeSpan.Zero); } - [TestMethod] + [Test] public void TicksMillisecondsSecondsMinutesDaysHoursWeeks_ShouldBeNegative_GivenMinusOne() { - Assert.IsTrue((-1f).Milliseconds() < TimeSpan.Zero); - Assert.IsTrue((-1f).Seconds() < TimeSpan.Zero); - Assert.IsTrue((-1f).Minutes() < TimeSpan.Zero); - Assert.IsTrue((-1f).Days() < TimeSpan.Zero); - Assert.IsTrue((-1f).Hours() < TimeSpan.Zero); - Assert.IsTrue((-1f).Weeks() < TimeSpan.Zero); + Assert.That((-1f).Milliseconds() < TimeSpan.Zero); + Assert.That((-1f).Seconds() < TimeSpan.Zero); + Assert.That((-1f).Minutes() < TimeSpan.Zero); + Assert.That((-1f).Days() < TimeSpan.Zero); + Assert.That((-1f).Hours() < TimeSpan.Zero); + Assert.That((-1f).Weeks() < TimeSpan.Zero); } } diff --git a/X10D.Tests/src/Time/StringTests.cs b/X10D.Tests/src/Time/StringTests.cs index 9b5e68c..8cad134 100644 --- a/X10D.Tests/src/Time/StringTests.cs +++ b/X10D.Tests/src/Time/StringTests.cs @@ -1,12 +1,12 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Time; namespace X10D.Tests.Time; -[TestClass] +[TestFixture] public class StringTests { - [TestMethod] + [Test] public void ToTimeSpan_ShouldReturnCorrectTimeSpan_GivenString() { const string value = "1y 1mo 1w 1d 1h 1m 1s 1ms"; @@ -20,19 +20,19 @@ public class StringTests expected += TimeSpan.FromDays(30); expected += TimeSpan.FromDays(365); - Assert.AreEqual(expected, value.ToTimeSpan()); + Assert.That(value.ToTimeSpan(), Is.EqualTo(expected)); } - [TestMethod] + [Test] public void ToTimeSpan_ShouldReturnZero_GivenInvalidString() { - Assert.AreEqual(TimeSpan.Zero, "Hello World".ToTimeSpan()); + Assert.That("Hello World".ToTimeSpan(), Is.EqualTo(TimeSpan.Zero)); } - [TestMethod] + [Test] public void ToTimeSpan_ShouldThrow_GivenNullString() { string? value = null; - Assert.ThrowsException(() => value!.ToTimeSpan()); + Assert.Throws(() => value!.ToTimeSpan()); } } diff --git a/X10D.Tests/src/Time/TimeSpanParserTests.cs b/X10D.Tests/src/Time/TimeSpanParserTests.cs index f1ba85c..aa065ce 100644 --- a/X10D.Tests/src/Time/TimeSpanParserTests.cs +++ b/X10D.Tests/src/Time/TimeSpanParserTests.cs @@ -1,64 +1,85 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Time; namespace X10D.Tests.Time; -[TestClass] +[TestFixture] public class TimeSpanParserTests { - [TestMethod] + [Test] public void TryParse_ShouldReturnTrue_GivenWellFormedTimeSpan() { bool result = TimeSpanParser.TryParse("3d6h", out TimeSpan timeSpan); - Assert.IsTrue(result); - Assert.AreEqual(TimeSpan.FromDays(3) + TimeSpan.FromHours(6), timeSpan); + Assert.Multiple(() => + { + Assert.That(result); + Assert.That(timeSpan, Is.EqualTo(TimeSpan.FromDays(3) + TimeSpan.FromHours(6))); + }); } - [TestMethod] + [Test] public void TryParse_ShouldReturnFalse_GivenMalformedTimeSpan() { bool result = TimeSpanParser.TryParse("asdf", out TimeSpan timeSpan); - Assert.IsFalse(result); - Assert.AreEqual(default, timeSpan); + Assert.Multiple(() => + { + Assert.That(result, Is.False); + Assert.That(timeSpan, Is.EqualTo(default(TimeSpan))); + }); } - [TestMethod] + [Test] public void TryParse_ShouldReturnFalse_GivenEmptySpan() { bool result = TimeSpanParser.TryParse(ReadOnlySpan.Empty, out TimeSpan timeSpan); - Assert.IsFalse(result); - Assert.AreEqual(default, timeSpan); + Assert.Multiple(() => + { + Assert.That(result, Is.False); + Assert.That(timeSpan, Is.EqualTo(default(TimeSpan))); + }); } - [TestMethod] + [Test] public void TryParse_ShouldReturnFalse_GivenWhiteSpaceSpan() { bool result = TimeSpanParser.TryParse(" ".AsSpan(), out TimeSpan timeSpan); - Assert.IsFalse(result); - Assert.AreEqual(default, timeSpan); + Assert.Multiple(() => + { + Assert.That(result, Is.False); + Assert.That(timeSpan, Is.EqualTo(default(TimeSpan))); + }); } - [TestMethod] + [Test] public void TryParse_ShouldReturnFalse_GivenEmptyString() { bool result = TimeSpanParser.TryParse(string.Empty, out TimeSpan timeSpan); - Assert.IsFalse(result); - Assert.AreEqual(default, timeSpan); + Assert.Multiple(() => + { + Assert.That(result, Is.False); + Assert.That(timeSpan, Is.EqualTo(default(TimeSpan))); + }); } - [TestMethod] + [Test] public void TryParse_ShouldReturnFalse_GivenWhiteSpaceString() { bool result = TimeSpanParser.TryParse(" ", out TimeSpan timeSpan); - Assert.IsFalse(result); - Assert.AreEqual(default, timeSpan); + Assert.Multiple(() => + { + Assert.That(result, Is.False); + Assert.That(timeSpan, Is.EqualTo(default(TimeSpan))); + }); } - [TestMethod] + [Test] public void TryParse_ShouldReturnFalse_GivenNull() { bool result = TimeSpanParser.TryParse(null, out TimeSpan timeSpan); - Assert.IsFalse(result); - Assert.AreEqual(default, timeSpan); + Assert.Multiple(() => + { + Assert.That(result, Is.False); + Assert.That(timeSpan, Is.EqualTo(default(TimeSpan))); + }); } } diff --git a/X10D.Tests/src/Time/TimeSpanTests.cs b/X10D.Tests/src/Time/TimeSpanTests.cs index cc34618..20456d5 100644 --- a/X10D.Tests/src/Time/TimeSpanTests.cs +++ b/X10D.Tests/src/Time/TimeSpanTests.cs @@ -1,42 +1,42 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Time; namespace X10D.Tests.Time; -[TestClass] +[TestFixture] public class TimeSpanTests { private TimeSpan _timeSpan; - [TestInitialize] + [SetUp] public void Initialize() { _timeSpan = new TimeSpan(1, 2, 3, 4, 5); } - [TestMethod] + [Test] public void Ago_ShouldBeInPast_GivenNow() { - Assert.IsTrue(_timeSpan.Ago() < DateTime.Now); + Assert.That(_timeSpan.Ago() < DateTime.Now); } - [TestMethod] + [Test] public void FromNow_ShouldBeInFuture_GivenNow() { - Assert.IsTrue(_timeSpan.FromNow() > DateTime.Now); + Assert.That(_timeSpan.FromNow() > DateTime.Now); } - [TestMethod] + [Test] public void Ago_ShouldBeYesterday_GivenYesterday() { DateTime yesterday = DateTime.Now.AddDays(-1); - Assert.AreEqual(yesterday.Date, 1.Days().Ago().Date); + Assert.That(1.Days().Ago().Date, Is.EqualTo(yesterday.Date)); } - [TestMethod] + [Test] public void FromNow_ShouldBeTomorrow_GivenTomorrow() { DateTime tomorrow = DateTime.Now.AddDays(1); - Assert.AreEqual(tomorrow.Date, 1.Days().FromNow().Date); + Assert.That(1.Days().FromNow().Date, Is.EqualTo(tomorrow.Date)); } } diff --git a/X10D.Tests/src/Time/UInt16Tests.cs b/X10D.Tests/src/Time/UInt16Tests.cs index e63d596..64d327e 100644 --- a/X10D.Tests/src/Time/UInt16Tests.cs +++ b/X10D.Tests/src/Time/UInt16Tests.cs @@ -1,75 +1,92 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Time; namespace X10D.Tests.Time; -[TestClass] +[TestFixture] [CLSCompliant(false)] public class UInt16Tests { - [TestMethod] + [Test] public void FromUnixTimeMilliseconds_ShouldBeEpoch_GivenZero() { - Assert.AreEqual(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc), ((ushort)0).FromUnixTimeMilliseconds()); + DateTimeOffset expected = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + Assert.That(((ushort)0).FromUnixTimeMilliseconds(), Is.EqualTo(expected)); } - [TestMethod] + [Test] public void FromUnixTimeSeconds_ShouldBeEpoch_GivenZero() { - Assert.AreEqual(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc), ((ushort)0).FromUnixTimeSeconds()); + DateTimeOffset expected = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + Assert.That(((ushort)0).FromUnixTimeSeconds(), Is.EqualTo(expected)); } - [TestMethod] + [Test] public void IsLeapYear_ShouldBeFalse_GivenMultipleOf100() { - Assert.IsFalse(((ushort)100).IsLeapYear()); - Assert.IsFalse(((ushort)1900).IsLeapYear()); - Assert.IsFalse(((ushort)2100).IsLeapYear()); + Assert.Multiple(() => + { + Assert.That(((ushort)100).IsLeapYear(), Is.False); + Assert.That(((ushort)1900).IsLeapYear(), Is.False); + Assert.That(((ushort)2100).IsLeapYear(), Is.False); + }); } - [TestMethod] + [Test] public void IsLeapYear_ShouldBeFalse_GivenOddNumber() { - Assert.IsFalse(((ushort)1).IsLeapYear()); - Assert.IsFalse(((ushort)101).IsLeapYear()); + Assert.Multiple(() => + { + Assert.That(((ushort)1).IsLeapYear(), Is.False); + Assert.That(((ushort)101).IsLeapYear(), Is.False); + }); } - [TestMethod] + [Test] public void IsLeapYear_ShouldBeTrue_GivenMultipleOf4Or400() { - Assert.IsTrue(((ushort)4).IsLeapYear()); - Assert.IsTrue(((ushort)104).IsLeapYear()); - Assert.IsTrue(((ushort)400).IsLeapYear()); - Assert.IsTrue(((ushort)2000).IsLeapYear()); + Assert.Multiple(() => + { + Assert.That(((ushort)4).IsLeapYear()); + Assert.That(((ushort)104).IsLeapYear()); + Assert.That(((ushort)400).IsLeapYear()); + Assert.That(((ushort)2000).IsLeapYear()); + }); } - [TestMethod] + [Test] public void IsLeapYear_ShouldThrow_GivenZero() { - Assert.ThrowsException(() => ((ushort)0).IsLeapYear()); + Assert.Throws(() => ((ushort)0).IsLeapYear()); } - [TestMethod] + [Test] public void TicksMillisecondsSecondsMinutesDaysHoursWeeks_ShouldBePositive_GivenOne() { - Assert.IsTrue(((ushort)1).Ticks() > TimeSpan.Zero); - Assert.IsTrue(((ushort)1).Milliseconds() > TimeSpan.Zero); - Assert.IsTrue(((ushort)1).Seconds() > TimeSpan.Zero); - Assert.IsTrue(((ushort)1).Minutes() > TimeSpan.Zero); - Assert.IsTrue(((ushort)1).Days() > TimeSpan.Zero); - Assert.IsTrue(((ushort)1).Hours() > TimeSpan.Zero); - Assert.IsTrue(((ushort)1).Weeks() > TimeSpan.Zero); + Assert.Multiple(() => + { + Assert.That(((ushort)1).Ticks(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(((ushort)1).Milliseconds(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(((ushort)1).Seconds(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(((ushort)1).Minutes(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(((ushort)1).Days(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(((ushort)1).Hours(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(((ushort)1).Weeks(), Is.GreaterThan(TimeSpan.Zero)); + }); } - [TestMethod] + [Test] public void TicksMillisecondsSecondsMinutesDaysHoursWeeks_ShouldBeZero_GivenZero() { - Assert.AreEqual(TimeSpan.Zero, ((ushort)0).Ticks()); - Assert.AreEqual(TimeSpan.Zero, ((ushort)0).Milliseconds()); - Assert.AreEqual(TimeSpan.Zero, ((ushort)0).Seconds()); - Assert.AreEqual(TimeSpan.Zero, ((ushort)0).Minutes()); - Assert.AreEqual(TimeSpan.Zero, ((ushort)0).Days()); - Assert.AreEqual(TimeSpan.Zero, ((ushort)0).Hours()); - Assert.AreEqual(TimeSpan.Zero, ((ushort)0).Weeks()); + Assert.Multiple(() => + { + Assert.That(((ushort)0).Ticks(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(((ushort)0).Milliseconds(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(((ushort)0).Seconds(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(((ushort)0).Minutes(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(((ushort)0).Days(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(((ushort)0).Hours(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(((ushort)0).Weeks(), Is.EqualTo(TimeSpan.Zero)); + }); } } diff --git a/X10D.Tests/src/Time/UInt32Tests.cs b/X10D.Tests/src/Time/UInt32Tests.cs index 86eef87..0063fe2 100644 --- a/X10D.Tests/src/Time/UInt32Tests.cs +++ b/X10D.Tests/src/Time/UInt32Tests.cs @@ -1,75 +1,92 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Time; namespace X10D.Tests.Time; -[TestClass] +[TestFixture] [CLSCompliant(false)] public class UInt32Tests { - [TestMethod] + [Test] public void FromUnixTimeMilliseconds_ShouldBeEpoch_GivenZero() { - Assert.AreEqual(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc), 0U.FromUnixTimeMilliseconds()); + DateTimeOffset expected = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + Assert.That(0U.FromUnixTimeMilliseconds(), Is.EqualTo(expected)); } - [TestMethod] + [Test] public void FromUnixTimeSeconds_ShouldBeEpoch_GivenZero() { - Assert.AreEqual(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc), 0U.FromUnixTimeSeconds()); + DateTimeOffset expected = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + Assert.That(0U.FromUnixTimeSeconds(), Is.EqualTo(expected)); } - [TestMethod] + [Test] public void IsLeapYear_ShouldBeFalse_GivenMultipleOf100() { - Assert.IsFalse(100U.IsLeapYear()); - Assert.IsFalse(1900U.IsLeapYear()); - Assert.IsFalse(2100U.IsLeapYear()); + Assert.Multiple(() => + { + Assert.That(100U.IsLeapYear(), Is.False); + Assert.That(1900U.IsLeapYear(), Is.False); + Assert.That(2100U.IsLeapYear(), Is.False); + }); } - [TestMethod] + [Test] public void IsLeapYear_ShouldBeFalse_GivenOddNumber() { - Assert.IsFalse(1U.IsLeapYear()); - Assert.IsFalse(101U.IsLeapYear()); + Assert.Multiple(() => + { + Assert.That(1U.IsLeapYear(), Is.False); + Assert.That(101U.IsLeapYear(), Is.False); + }); } - [TestMethod] + [Test] public void IsLeapYear_ShouldBeTrue_GivenMultipleOf4Or400() { - Assert.IsTrue(4U.IsLeapYear()); - Assert.IsTrue(104U.IsLeapYear()); - Assert.IsTrue(400U.IsLeapYear()); - Assert.IsTrue(2000U.IsLeapYear()); + Assert.Multiple(() => + { + Assert.That(4U.IsLeapYear()); + Assert.That(104U.IsLeapYear()); + Assert.That(400U.IsLeapYear()); + Assert.That(2000U.IsLeapYear()); + }); } - [TestMethod] + [Test] public void IsLeapYear_ShouldThrow_GivenZero() { - Assert.ThrowsException(() => 0U.IsLeapYear()); + Assert.Throws(() => _ = 0U.IsLeapYear()); } - [TestMethod] + [Test] public void TicksMillisecondsSecondsMinutesDaysHoursWeeks_ShouldBePositive_GivenOne() { - Assert.IsTrue(1U.Ticks() > TimeSpan.Zero); - Assert.IsTrue(1U.Milliseconds() > TimeSpan.Zero); - Assert.IsTrue(1U.Seconds() > TimeSpan.Zero); - Assert.IsTrue(1U.Minutes() > TimeSpan.Zero); - Assert.IsTrue(1U.Days() > TimeSpan.Zero); - Assert.IsTrue(1U.Hours() > TimeSpan.Zero); - Assert.IsTrue(1U.Weeks() > TimeSpan.Zero); + Assert.Multiple(() => + { + Assert.That(1U.Ticks(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(1U.Milliseconds(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(1U.Seconds(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(1U.Minutes(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(1U.Days(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(1U.Hours(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(1U.Weeks(), Is.GreaterThan(TimeSpan.Zero)); + }); } - [TestMethod] + [Test] public void TicksMillisecondsSecondsMinutesDaysHoursWeeks_ShouldBeZero_GivenZero() { - Assert.AreEqual(TimeSpan.Zero, 0U.Ticks()); - Assert.AreEqual(TimeSpan.Zero, 0U.Milliseconds()); - Assert.AreEqual(TimeSpan.Zero, 0U.Seconds()); - Assert.AreEqual(TimeSpan.Zero, 0U.Minutes()); - Assert.AreEqual(TimeSpan.Zero, 0U.Days()); - Assert.AreEqual(TimeSpan.Zero, 0U.Hours()); - Assert.AreEqual(TimeSpan.Zero, 0U.Weeks()); + Assert.Multiple(() => + { + Assert.That(0U.Ticks(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(0U.Milliseconds(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(0U.Seconds(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(0U.Minutes(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(0U.Days(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(0U.Hours(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(0U.Weeks(), Is.EqualTo(TimeSpan.Zero)); + }); } } diff --git a/X10D.Tests/src/Time/UInt64Tests.cs b/X10D.Tests/src/Time/UInt64Tests.cs index 9720f3a..48642be 100644 --- a/X10D.Tests/src/Time/UInt64Tests.cs +++ b/X10D.Tests/src/Time/UInt64Tests.cs @@ -1,75 +1,92 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Time; namespace X10D.Tests.Time; -[TestClass] +[TestFixture] [CLSCompliant(false)] public class UInt64Tests { - [TestMethod] + [Test] public void FromUnixTimeMilliseconds_ShouldBeEpoch_GivenZero() { - Assert.AreEqual(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc), 0UL.FromUnixTimeMilliseconds()); + DateTimeOffset expected = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + Assert.That(0UL.FromUnixTimeMilliseconds(), Is.EqualTo(expected)); } - [TestMethod] + [Test] public void FromUnixTimeSeconds_ShouldBeEpoch_GivenZero() { - Assert.AreEqual(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc), 0UL.FromUnixTimeSeconds()); + DateTimeOffset expected = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + Assert.That(0UL.FromUnixTimeSeconds(), Is.EqualTo(expected)); } - [TestMethod] + [Test] public void IsLeapYear_ShouldBeFalse_GivenMultipleOf100() { - Assert.IsFalse(100UL.IsLeapYear()); - Assert.IsFalse(1900UL.IsLeapYear()); - Assert.IsFalse(2100UL.IsLeapYear()); + Assert.Multiple(() => + { + Assert.That(100UL.IsLeapYear(), Is.False); + Assert.That(1900UL.IsLeapYear(), Is.False); + Assert.That(2100UL.IsLeapYear(), Is.False); + }); } - [TestMethod] + [Test] public void IsLeapYear_ShouldBeFalse_GivenOddNumber() { - Assert.IsFalse(1UL.IsLeapYear()); - Assert.IsFalse(101UL.IsLeapYear()); + Assert.Multiple(() => + { + Assert.That(1UL.IsLeapYear(), Is.False); + Assert.That(101UL.IsLeapYear(), Is.False); + }); } - [TestMethod] + [Test] public void IsLeapYear_ShouldBeTrue_GivenMultipleOf4Or400() { - Assert.IsTrue(4UL.IsLeapYear()); - Assert.IsTrue(104UL.IsLeapYear()); - Assert.IsTrue(400UL.IsLeapYear()); - Assert.IsTrue(2000UL.IsLeapYear()); + Assert.Multiple(() => + { + Assert.That(4UL.IsLeapYear()); + Assert.That(104UL.IsLeapYear()); + Assert.That(400UL.IsLeapYear()); + Assert.That(2000UL.IsLeapYear()); + }); } - [TestMethod] + [Test] public void IsLeapYear_ShouldThrow_GivenZero() { - Assert.ThrowsException(() => 0UL.IsLeapYear()); + Assert.Throws(() => _ = 0UL.IsLeapYear()); } - [TestMethod] + [Test] public void TicksMillisecondsSecondsMinutesDaysHoursWeeks_ShouldBePositive_GivenOne() { - Assert.IsTrue(1UL.Ticks() > TimeSpan.Zero); - Assert.IsTrue(1UL.Milliseconds() > TimeSpan.Zero); - Assert.IsTrue(1UL.Seconds() > TimeSpan.Zero); - Assert.IsTrue(1UL.Minutes() > TimeSpan.Zero); - Assert.IsTrue(1UL.Days() > TimeSpan.Zero); - Assert.IsTrue(1UL.Hours() > TimeSpan.Zero); - Assert.IsTrue(1UL.Weeks() > TimeSpan.Zero); + Assert.Multiple(() => + { + Assert.That(1UL.Ticks(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(1UL.Milliseconds(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(1UL.Seconds(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(1UL.Minutes(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(1UL.Days(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(1UL.Hours(), Is.GreaterThan(TimeSpan.Zero)); + Assert.That(1UL.Weeks(), Is.GreaterThan(TimeSpan.Zero)); + }); } - [TestMethod] + [Test] public void TicksMillisecondsSecondsMinutesDaysHoursWeeks_ShouldBeZero_GivenZero() { - Assert.AreEqual(TimeSpan.Zero, 0UL.Ticks()); - Assert.AreEqual(TimeSpan.Zero, 0UL.Milliseconds()); - Assert.AreEqual(TimeSpan.Zero, 0UL.Seconds()); - Assert.AreEqual(TimeSpan.Zero, 0UL.Minutes()); - Assert.AreEqual(TimeSpan.Zero, 0UL.Days()); - Assert.AreEqual(TimeSpan.Zero, 0UL.Hours()); - Assert.AreEqual(TimeSpan.Zero, 0UL.Weeks()); + Assert.Multiple(() => + { + Assert.That(0UL.Ticks(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(0UL.Milliseconds(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(0UL.Seconds(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(0UL.Minutes(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(0UL.Days(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(0UL.Hours(), Is.EqualTo(TimeSpan.Zero)); + Assert.That(0UL.Weeks(), Is.EqualTo(TimeSpan.Zero)); + }); } } From dbeb13efcdeca67b4aedce37f6d5f88983183f2f Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Wed, 5 Apr 2023 22:49:16 +0100 Subject: [PATCH 007/102] test: fix expected/actual value swap (#76) --- X10D.Tests/src/Linq/ByteTests.cs | 8 ++++---- X10D.Tests/src/Linq/Int32Tests.cs | 4 ++-- X10D.Tests/src/Linq/Int64Tests.cs | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/X10D.Tests/src/Linq/ByteTests.cs b/X10D.Tests/src/Linq/ByteTests.cs index de2faca..ccaf696 100644 --- a/X10D.Tests/src/Linq/ByteTests.cs +++ b/X10D.Tests/src/Linq/ByteTests.cs @@ -54,7 +54,7 @@ public class ByteTests Assert.That(value, Is.EqualTo(current++)); } - Assert.That(end, Is.EqualTo(current)); + Assert.That(current, Is.EqualTo(end)); } [Test] @@ -69,7 +69,7 @@ public class ByteTests Assert.That(value, Is.EqualTo(current++)); } - Assert.That(end, Is.EqualTo(current)); + Assert.That(current, Is.EqualTo(end)); } [Test] @@ -84,7 +84,7 @@ public class ByteTests Assert.That(value, Is.EqualTo(current++)); } - Assert.That(end, Is.EqualTo(current)); + Assert.That(current, Is.EqualTo(end)); } [Test] @@ -99,6 +99,6 @@ public class ByteTests Assert.That(value, Is.EqualTo(current++)); } - Assert.That(end, Is.EqualTo(current)); + Assert.That(current, Is.EqualTo(end)); } } diff --git a/X10D.Tests/src/Linq/Int32Tests.cs b/X10D.Tests/src/Linq/Int32Tests.cs index 0113712..93b6f5a 100644 --- a/X10D.Tests/src/Linq/Int32Tests.cs +++ b/X10D.Tests/src/Linq/Int32Tests.cs @@ -61,7 +61,7 @@ public class Int32Tests Assert.That(value, Is.EqualTo(current++)); } - Assert.That(end, Is.EqualTo(current)); + Assert.That(current, Is.EqualTo(end)); } [Test] @@ -76,6 +76,6 @@ public class Int32Tests Assert.That(value, Is.EqualTo(current++)); } - Assert.That(end, Is.EqualTo(current)); + Assert.That(current, Is.EqualTo(end)); } } diff --git a/X10D.Tests/src/Linq/Int64Tests.cs b/X10D.Tests/src/Linq/Int64Tests.cs index 946a86d..61f1932 100644 --- a/X10D.Tests/src/Linq/Int64Tests.cs +++ b/X10D.Tests/src/Linq/Int64Tests.cs @@ -62,6 +62,6 @@ public class Int64Tests Assert.That(value, Is.EqualTo(current++)); } - Assert.That(end, Is.EqualTo(current)); + Assert.That(current, Is.EqualTo(end)); } } From 744f5e906baed6a8f5d81d6f84d62d4e96c5c5d7 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Wed, 5 Apr 2023 22:49:28 +0100 Subject: [PATCH 008/102] test: remove redundant quality checks (#76) --- X10D.Tests/src/Drawing/PolygonTests.cs | 39 ++++++++++---------------- 1 file changed, 15 insertions(+), 24 deletions(-) diff --git a/X10D.Tests/src/Drawing/PolygonTests.cs b/X10D.Tests/src/Drawing/PolygonTests.cs index 96aadec..9d36dde 100644 --- a/X10D.Tests/src/Drawing/PolygonTests.cs +++ b/X10D.Tests/src/Drawing/PolygonTests.cs @@ -86,14 +86,11 @@ public class PolygonTests var first = Polygon.Empty; var second = Polygon.Empty; - Assert.That(second, Is.EqualTo(first)); - Assert.That(first, Is.EqualTo(second)); - Assert.That(first.Equals(second)); - Assert.That(second.Equals(first)); - Assert.That(first == second); - Assert.That(second == first); - Assert.That(first != second, Is.False); - Assert.That(second != first, Is.False); + Assert.Multiple(() => + { + Assert.That(second, Is.EqualTo(first)); + Assert.That(first, Is.EqualTo(second)); + }); } [Test] @@ -102,14 +99,11 @@ public class PolygonTests Polygon first = CreateHexagon(); Polygon second = CreateHexagon(); - Assert.That(second, Is.EqualTo(first)); - Assert.That(first, Is.EqualTo(second)); - Assert.That(first.Equals(second)); - Assert.That(second.Equals(first)); - Assert.That(first == second); - Assert.That(second == first); - Assert.That(first != second, Is.False); - Assert.That(second != first, Is.False); + Assert.Multiple(() => + { + Assert.That(second, Is.EqualTo(first)); + Assert.That(first, Is.EqualTo(second)); + }); } [Test] @@ -118,14 +112,11 @@ public class PolygonTests Polygon first = CreateHexagon(); Polygon second = Polygon.Empty; - Assert.AreNotEqual(first, second); - Assert.AreNotEqual(second, first); - Assert.That(first.Equals(second), Is.False); - Assert.That(second.Equals(first), Is.False); - Assert.That(first == second, Is.False); - Assert.That(second == first, Is.False); - Assert.That(first != second); - Assert.That(second != first); + Assert.Multiple(() => + { + Assert.That(second, Is.Not.EqualTo(first)); + Assert.That(first, Is.Not.EqualTo(second)); + }); } [Test] From fcdcf54aa331ed29c2d6c45f5a111a8da5c6aedf Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Wed, 5 Apr 2023 22:51:04 +0100 Subject: [PATCH 009/102] test: use NUnit constraint API in X10D.Unity.Tests (#76) --- .../Assets/Tests/ComponentTests.cs | 4 +- .../Assets/Tests/Drawing/Color32Tests.cs | 74 ++++----- .../Assets/Tests/Drawing/ColorTests.cs | 74 ++++----- .../Assets/Tests/Drawing/PointFTests.cs | 4 +- .../Assets/Tests/Drawing/PointTests.cs | 8 +- .../Assets/Tests/Drawing/RandomTests.cs | 20 +-- .../Assets/Tests/Drawing/RectIntTests.cs | 16 +- .../Assets/Tests/Drawing/RectTests.cs | 8 +- .../Assets/Tests/Drawing/RectangleFTests.cs | 8 +- .../Assets/Tests/Drawing/RectangleTests.cs | 16 +- .../Assets/Tests/Drawing/SizeFTests.cs | 4 +- .../Assets/Tests/Drawing/SizeTests.cs | 8 +- .../Assets/Tests/GameObjectTests.cs | 36 ++--- .../Assets/Tests/Numerics/QuaternionTests.cs | 16 +- .../Assets/Tests/Numerics/RandomTests.cs | 4 +- .../Assets/Tests/Numerics/Vector2IntTests.cs | 44 +++--- .../Assets/Tests/Numerics/Vector2Tests.cs | 64 ++++---- .../Assets/Tests/Numerics/Vector3IntTests.cs | 67 ++++----- .../Assets/Tests/Numerics/Vector3Tests.cs | 94 ++++++------ .../Assets/Tests/Numerics/Vector4Tests.cs | 140 +++++++++--------- .../Assets/Tests/SingletonTests.cs | 12 +- .../Assets/Tests/TransformTests.cs | 20 +-- .../Assets/Tests/YieldInstructionTests.cs | 25 +--- 23 files changed, 378 insertions(+), 388 deletions(-) diff --git a/X10D.Unity.Tests/Assets/Tests/ComponentTests.cs b/X10D.Unity.Tests/Assets/Tests/ComponentTests.cs index c77f83e..e6c1431 100644 --- a/X10D.Unity.Tests/Assets/Tests/ComponentTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/ComponentTests.cs @@ -20,8 +20,8 @@ namespace X10D.Unity.Tests child.AddComponent(); Rigidbody[] components = rigidbody.GetComponentsInChildrenOnly(); - Assert.AreEqual(1, components.Length); - Assert.AreEqual(components[0].gameObject, child); + Assert.That(components.Length, Is.EqualTo(1)); + Assert.That(child, Is.EqualTo(components[0].gameObject)); yield break; } diff --git a/X10D.Unity.Tests/Assets/Tests/Drawing/Color32Tests.cs b/X10D.Unity.Tests/Assets/Tests/Drawing/Color32Tests.cs index b1c7b37..eb2e7c2 100644 --- a/X10D.Unity.Tests/Assets/Tests/Drawing/Color32Tests.cs +++ b/X10D.Unity.Tests/Assets/Tests/Drawing/Color32Tests.cs @@ -22,15 +22,15 @@ namespace X10D.Unity.Tests.Drawing byte a, r, g, b; (r, g, b) = White; - Assert.AreEqual(255, r); - Assert.AreEqual(255, g); - Assert.AreEqual(255, b); + Assert.That(r, Is.EqualTo(255)); + Assert.That(g, Is.EqualTo(255)); + Assert.That(b, Is.EqualTo(255)); (a, r, g, b) = Yellow; - Assert.AreEqual(255, a); - Assert.AreEqual(255, r); - Assert.AreEqual(255, g); - Assert.AreEqual(0, b); + Assert.That(a, Is.EqualTo(255)); + Assert.That(r, Is.EqualTo(255)); + Assert.That(g, Is.EqualTo(255)); + Assert.That(b, Is.EqualTo(0)); } [Test] @@ -38,30 +38,30 @@ namespace X10D.Unity.Tests.Drawing { // I know it's just casting... but aim for 100% coverage babyyyy - Assert.AreEqual(ConsoleColor.Red, ((Color32)Color.red).GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Green, ((Color32)Color.green).GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Blue, ((Color32)Color.blue).GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.White, ((Color32)Color.white).GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Black, ((Color32)Color.black).GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Yellow, ((Color32)Color.yellow).GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Cyan, ((Color32)Color.cyan).GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Magenta, ((Color32)Color.magenta).GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Gray, ((Color32)Color.gray).GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Gray, ((Color32)Color.grey).GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Black, ((Color32)Color.clear).GetClosestConsoleColor()); + Assert.That(((Color32)Color.red).GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Red)); + Assert.That(((Color32)Color.green).GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Green)); + Assert.That(((Color32)Color.blue).GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Blue)); + Assert.That(((Color32)Color.white).GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); + Assert.That(((Color32)Color.black).GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Black)); + Assert.That(((Color32)Color.yellow).GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Yellow)); + Assert.That(((Color32)Color.cyan).GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Cyan)); + Assert.That(((Color32)Color.magenta).GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Magenta)); + Assert.That(((Color32)Color.gray).GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Gray)); + Assert.That(((Color32)Color.grey).GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Gray)); + Assert.That(((Color32)Color.clear).GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Black)); } [Test] public void Inverted_ShouldReturnInvertedColor() { - Assert.AreEqual(White, Black.Inverted()); - Assert.AreEqual(Black, White.Inverted()); - Assert.AreEqual(Red, Cyan.Inverted()); - Assert.AreEqual(Cyan, Red.Inverted()); - Assert.AreEqual(Green, Magenta.Inverted()); - Assert.AreEqual(Magenta, Green.Inverted()); - Assert.AreEqual(Yellow, Blue.Inverted()); - Assert.AreEqual(Blue, Yellow.Inverted()); + Assert.That(Black.Inverted(), Is.EqualTo(White)); + Assert.That(White.Inverted(), Is.EqualTo(Black)); + Assert.That(Cyan.Inverted(), Is.EqualTo(Red)); + Assert.That(Red.Inverted(), Is.EqualTo(Cyan)); + Assert.That(Magenta.Inverted(), Is.EqualTo(Green)); + Assert.That(Green.Inverted(), Is.EqualTo(Magenta)); + Assert.That(Blue.Inverted(), Is.EqualTo(Yellow)); + Assert.That(Yellow.Inverted(), Is.EqualTo(Blue)); } [Test] @@ -70,7 +70,7 @@ namespace X10D.Unity.Tests.Drawing var expected = new Color32(0, 0, 0, 255); var actual = new Color32(255, 255, 255, 255).Inverted(); - Assert.AreEqual(expected, actual); + Assert.That(actual, Is.EqualTo(expected)); } [Test] @@ -79,7 +79,7 @@ namespace X10D.Unity.Tests.Drawing System.Drawing.Color expected = System.Drawing.Color.FromArgb(255, 255, 255); System.Drawing.Color actual = White.ToSystemDrawingColor(); - Assert.AreEqual(expected, actual); + Assert.That(actual, Is.EqualTo(expected)); } [Test] @@ -88,36 +88,36 @@ namespace X10D.Unity.Tests.Drawing Color32 expected = White; Color32 actual = System.Drawing.Color.FromArgb(255, 255, 255).ToUnityColor32(); - Assert.AreEqual(expected, actual); + Assert.That(actual, Is.EqualTo(expected)); } [Test] public void WithA0_ShouldReturnSameColor_GivenWhite() { var transparent = new Color32(255, 255, 255, 0); - Assert.AreEqual(transparent, White.WithA(0)); - Assert.AreEqual(transparent, transparent.WithA(0)); + Assert.That(White.WithA(0), Is.EqualTo(transparent)); + Assert.That(transparent.WithA(0), Is.EqualTo(transparent)); } [Test] public void WithB0_ShouldReturnYellow_GivenWhite() { - Assert.AreEqual(Yellow, White.WithB(0)); - Assert.AreEqual(Yellow, Yellow.WithB(0)); + Assert.That(White.WithB(0), Is.EqualTo(Yellow)); + Assert.That(Yellow.WithB(0), Is.EqualTo(Yellow)); } [Test] public void WithG0_ShouldReturnMagenta_GivenWhite() { - Assert.AreEqual(Magenta, White.WithG(0)); - Assert.AreEqual(Magenta, Magenta.WithG(0)); + Assert.That(White.WithG(0), Is.EqualTo(Magenta)); + Assert.That(Magenta.WithG(0), Is.EqualTo(Magenta)); } [Test] public void WithR0_ShouldReturnCyan_GivenWhite() { - Assert.AreEqual(Cyan, White.WithR(0)); - Assert.AreEqual(Cyan, Cyan.WithR(0)); + Assert.That(White.WithR(0), Is.EqualTo(Cyan)); + Assert.That(Cyan.WithR(0), Is.EqualTo(Cyan)); } } } diff --git a/X10D.Unity.Tests/Assets/Tests/Drawing/ColorTests.cs b/X10D.Unity.Tests/Assets/Tests/Drawing/ColorTests.cs index 9cdd4ee..c9d9182 100644 --- a/X10D.Unity.Tests/Assets/Tests/Drawing/ColorTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/Drawing/ColorTests.cs @@ -22,44 +22,44 @@ namespace X10D.Unity.Tests.Drawing float a, r, g, b; (r, g, b) = White; - Assert.AreEqual(1.0f, r); - Assert.AreEqual(1.0f, g); - Assert.AreEqual(1.0f, b); + Assert.That(r, Is.EqualTo(1.0f)); + Assert.That(g, Is.EqualTo(1.0f)); + Assert.That(b, Is.EqualTo(1.0f)); (a, r, g, b) = Yellow; - Assert.AreEqual(1.0f, a); - Assert.AreEqual(1.0f, r); - Assert.AreEqual(1.0f, g); - Assert.AreEqual(0.0f, b); + Assert.That(a, Is.EqualTo(1.0f)); + Assert.That(r, Is.EqualTo(1.0f)); + Assert.That(g, Is.EqualTo(1.0f)); + Assert.That(b, Is.EqualTo(0.0f)); } [Test] public void GetClosestConsoleColor_ShouldReturnClosestColor_GivenValidColor() { - Assert.AreEqual(ConsoleColor.Red, Color.red.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Green, Color.green.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Blue, Color.blue.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.White, Color.white.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Black, Color.black.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Yellow, Color.yellow.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Cyan, Color.cyan.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Magenta, Color.magenta.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Gray, Color.gray.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Gray, Color.grey.GetClosestConsoleColor()); - Assert.AreEqual(ConsoleColor.Black, Color.clear.GetClosestConsoleColor()); + Assert.That(Color.red.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Red)); + Assert.That(Color.green.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Green)); + Assert.That(Color.blue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Blue)); + Assert.That(Color.white.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); + Assert.That(Color.black.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Black)); + Assert.That(Color.yellow.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Yellow)); + Assert.That(Color.cyan.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Cyan)); + Assert.That(Color.magenta.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Magenta)); + Assert.That(Color.gray.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Gray)); + Assert.That(Color.grey.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Gray)); + Assert.That(Color.clear.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Black)); } [Test] public void Inverted_ShouldReturnInvertedColor() { - Assert.AreEqual(White, Black.Inverted()); - Assert.AreEqual(Black, White.Inverted()); - Assert.AreEqual(Red, Cyan.Inverted()); - Assert.AreEqual(Cyan, Red.Inverted()); - Assert.AreEqual(Green, Magenta.Inverted()); - Assert.AreEqual(Magenta, Green.Inverted()); - Assert.AreEqual(Yellow, Blue.Inverted()); - Assert.AreEqual(Blue, Yellow.Inverted()); + Assert.That(Black.Inverted(), Is.EqualTo(White)); + Assert.That(White.Inverted(), Is.EqualTo(Black)); + Assert.That(Cyan.Inverted(), Is.EqualTo(Red)); + Assert.That(Red.Inverted(), Is.EqualTo(Cyan)); + Assert.That(Magenta.Inverted(), Is.EqualTo(Green)); + Assert.That(Green.Inverted(), Is.EqualTo(Magenta)); + Assert.That(Blue.Inverted(), Is.EqualTo(Yellow)); + Assert.That(Yellow.Inverted(), Is.EqualTo(Blue)); } [Test] @@ -68,7 +68,7 @@ namespace X10D.Unity.Tests.Drawing var expected = new Color(0, 0, 0, 1); var actual = new Color(1, 1, 1, 1).Inverted(); - Assert.AreEqual(expected, actual); + Assert.That(actual, Is.EqualTo(expected)); } [Test] @@ -77,7 +77,7 @@ namespace X10D.Unity.Tests.Drawing System.Drawing.Color expected = System.Drawing.Color.FromArgb(255, 255, 255); System.Drawing.Color actual = White.ToSystemDrawingColor(); - Assert.AreEqual(expected, actual); + Assert.That(actual, Is.EqualTo(expected)); } [Test] @@ -86,36 +86,36 @@ namespace X10D.Unity.Tests.Drawing Color expected = White; Color actual = System.Drawing.Color.FromArgb(255, 255, 255).ToUnityColor(); - Assert.AreEqual(expected, actual); + Assert.That(actual, Is.EqualTo(expected)); } [Test] public void WithA0_ShouldReturnSameColor_GivenWhite() { var transparent = new Color(1, 1, 1, 0); - Assert.AreEqual(transparent, White.WithA(0)); - Assert.AreEqual(transparent, transparent.WithA(0)); + Assert.That(White.WithA(0), Is.EqualTo(transparent)); + Assert.That(transparent.WithA(0), Is.EqualTo(transparent)); } [Test] public void WithB0_ShouldReturnYellow_GivenWhite() { - Assert.AreEqual(Yellow, White.WithB(0)); - Assert.AreEqual(Yellow, Yellow.WithB(0)); + Assert.That(White.WithB(0), Is.EqualTo(Yellow)); + Assert.That(Yellow.WithB(0), Is.EqualTo(Yellow)); } [Test] public void WithG0_ShouldReturnMagenta_GivenWhite() { - Assert.AreEqual(Magenta, White.WithG(0)); - Assert.AreEqual(Magenta, Magenta.WithG(0)); + Assert.That(White.WithG(0), Is.EqualTo(Magenta)); + Assert.That(Magenta.WithG(0), Is.EqualTo(Magenta)); } [Test] public void WithR0_ShouldReturnCyan_GivenWhite() { - Assert.AreEqual(Cyan, White.WithR(0)); - Assert.AreEqual(Cyan, Cyan.WithR(0)); + Assert.That(White.WithR(0), Is.EqualTo(Cyan)); + Assert.That(Cyan.WithR(0), Is.EqualTo(Cyan)); } } } diff --git a/X10D.Unity.Tests/Assets/Tests/Drawing/PointFTests.cs b/X10D.Unity.Tests/Assets/Tests/Drawing/PointFTests.cs index bf949a3..13d0b36 100644 --- a/X10D.Unity.Tests/Assets/Tests/Drawing/PointFTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/Drawing/PointFTests.cs @@ -15,8 +15,8 @@ namespace X10D.Unity.Tests.Drawing var point = new PointF(random.NextSingle(), random.NextSingle()); var vector = point.ToUnityVector2(); - Assert.AreEqual(point.X, vector.x, 1e-6f); - Assert.AreEqual(point.Y, vector.y, 1e-6f); + Assert.That(vector.x, Is.EqualTo(point.X).Within(1e-6f)); + Assert.That(vector.y, Is.EqualTo(point.Y).Within(1e-6f)); } } } diff --git a/X10D.Unity.Tests/Assets/Tests/Drawing/PointTests.cs b/X10D.Unity.Tests/Assets/Tests/Drawing/PointTests.cs index 6db859c..ab8a428 100644 --- a/X10D.Unity.Tests/Assets/Tests/Drawing/PointTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/Drawing/PointTests.cs @@ -14,8 +14,8 @@ namespace X10D.Unity.Tests.Drawing var point = new Point(random.Next(), random.Next()); var vector = point.ToUnityVector2(); - Assert.AreEqual(point.X, vector.x); - Assert.AreEqual(point.Y, vector.y); + Assert.That(vector.x, Is.EqualTo(point.X)); + Assert.That(vector.y, Is.EqualTo(point.Y)); } [Test] @@ -25,8 +25,8 @@ namespace X10D.Unity.Tests.Drawing var point = new Point(random.Next(), random.Next()); var vector = point.ToUnityVector2Int(); - Assert.AreEqual(point.X, vector.x); - Assert.AreEqual(point.Y, vector.y); + Assert.That(vector.x, Is.EqualTo(point.X)); + Assert.That(vector.y, Is.EqualTo(point.Y)); } } } diff --git a/X10D.Unity.Tests/Assets/Tests/Drawing/RandomTests.cs b/X10D.Unity.Tests/Assets/Tests/Drawing/RandomTests.cs index 3bb5543..5f4e842 100644 --- a/X10D.Unity.Tests/Assets/Tests/Drawing/RandomTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/Drawing/RandomTests.cs @@ -15,10 +15,10 @@ namespace X10D.Unity.Tests.Drawing { var random = new Random(1234); var color = random.NextColorArgb(); - Assert.AreEqual(0.373868465f, color.r, 1e-6f); - Assert.AreEqual(0.391597569f, color.g, 1e-6f); - Assert.AreEqual(0.675019085f, color.b, 1e-6f); - Assert.AreEqual(0.234300315f, color.a, 1e-6f); + Assert.That(color.r, Is.EqualTo(0.373868465f).Within(1e-6f)); + Assert.That(color.g, Is.EqualTo(0.391597569f).Within(1e-6f)); + Assert.That(color.b, Is.EqualTo(0.675019085f).Within(1e-6f)); + Assert.That(color.a, Is.EqualTo(0.234300315f).Within(1e-6f)); } [Test] @@ -32,7 +32,7 @@ namespace X10D.Unity.Tests.Drawing public void NextColor32Argb_ShouldReturn331515e5_GivenSeed1234() { var random = new Random(1234); - Assert.AreEqual(new Color32(21, 21, 229, 51), random.NextColor32Argb()); + Assert.That(random.NextColor32Argb(), Is.EqualTo(new Color32(21, 21, 229, 51))); } [Test] @@ -47,10 +47,10 @@ namespace X10D.Unity.Tests.Drawing { var random = new Random(1234); var color = random.NextColorRgb(); - Assert.AreEqual(0.234300315f, color.r, 1e-6f); - Assert.AreEqual(0.373868465f, color.g, 1e-6f); - Assert.AreEqual(0.391597569f, color.b, 1e-6f); - Assert.AreEqual(1, color.a, 1e-6f); + Assert.That(color.r, Is.EqualTo(0.234300315f).Within(1e-6f)); + Assert.That(color.g, Is.EqualTo(0.373868465f).Within(1e-6f)); + Assert.That(color.b, Is.EqualTo(0.391597569f).Within(1e-6f)); + Assert.That(color.a, Is.EqualTo(1).Within(1e-6f)); } [Test] @@ -64,7 +64,7 @@ namespace X10D.Unity.Tests.Drawing public void NextColor32Rgb_ShouldReturn1515e5_GivenSeed1234() { var random = new Random(1234); - Assert.AreEqual(new Color32(21, 21, 229, 255), random.NextColor32Rgb()); + Assert.That(random.NextColor32Rgb(), Is.EqualTo(new Color32(21, 21, 229, 255))); } [Test] diff --git a/X10D.Unity.Tests/Assets/Tests/Drawing/RectIntTests.cs b/X10D.Unity.Tests/Assets/Tests/Drawing/RectIntTests.cs index cd8a576..2e5f759 100644 --- a/X10D.Unity.Tests/Assets/Tests/Drawing/RectIntTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/Drawing/RectIntTests.cs @@ -14,10 +14,10 @@ namespace X10D.Unity.Tests.Drawing var rect = new RectInt(random.Next(), random.Next(), random.Next(), random.Next()); var rectangle = rect.ToSystemRectangle(); - Assert.AreEqual(rect.x, rectangle.X); - Assert.AreEqual(rect.y, rectangle.Y); - Assert.AreEqual(rect.width, rectangle.Width); - Assert.AreEqual(rect.height, rectangle.Height); + Assert.That(rectangle.X, Is.EqualTo(rect.x)); + Assert.That(rectangle.Y, Is.EqualTo(rect.y)); + Assert.That(rectangle.Width, Is.EqualTo(rect.width)); + Assert.That(rectangle.Height, Is.EqualTo(rect.height)); } [Test] @@ -27,10 +27,10 @@ namespace X10D.Unity.Tests.Drawing var rect = new RectInt(random.Next(), random.Next(), random.Next(), random.Next()); var rectangle = rect.ToSystemRectangleF(); - Assert.AreEqual(rect.x, rectangle.X); - Assert.AreEqual(rect.y, rectangle.Y); - Assert.AreEqual(rect.width, rectangle.Width); - Assert.AreEqual(rect.height, rectangle.Height); + Assert.That(rectangle.X, Is.EqualTo(rect.x)); + Assert.That(rectangle.Y, Is.EqualTo(rect.y)); + Assert.That(rectangle.Width, Is.EqualTo(rect.width)); + Assert.That(rectangle.Height, Is.EqualTo(rect.height)); } } } diff --git a/X10D.Unity.Tests/Assets/Tests/Drawing/RectTests.cs b/X10D.Unity.Tests/Assets/Tests/Drawing/RectTests.cs index 52ce153..9cc688e 100644 --- a/X10D.Unity.Tests/Assets/Tests/Drawing/RectTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/Drawing/RectTests.cs @@ -15,10 +15,10 @@ namespace X10D.Unity.Tests.Drawing var rect = new Rect(random.NextSingle(), random.NextSingle(), random.NextSingle(), random.NextSingle()); var rectangle = rect.ToSystemRectangleF(); - Assert.AreEqual(rect.x, rectangle.X, 1e-6f); - Assert.AreEqual(rect.y, rectangle.Y, 1e-6f); - Assert.AreEqual(rect.width, rectangle.Width, 1e-6f); - Assert.AreEqual(rect.height, rectangle.Height, 1e-6f); + Assert.That(rectangle.X, Is.EqualTo(rect.x).Within(1e-6f)); + Assert.That(rectangle.Y, Is.EqualTo(rect.y).Within(1e-6f)); + Assert.That(rectangle.Width, Is.EqualTo(rect.width).Within(1e-6f)); + Assert.That(rectangle.Height, Is.EqualTo(rect.height).Within(1e-6f)); } } } diff --git a/X10D.Unity.Tests/Assets/Tests/Drawing/RectangleFTests.cs b/X10D.Unity.Tests/Assets/Tests/Drawing/RectangleFTests.cs index 0a99c36..fdcbaf6 100644 --- a/X10D.Unity.Tests/Assets/Tests/Drawing/RectangleFTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/Drawing/RectangleFTests.cs @@ -15,10 +15,10 @@ namespace X10D.Unity.Tests.Drawing var rectangle = new RectangleF(random.NextSingle(), random.NextSingle(), random.NextSingle(), random.NextSingle()); var rect = rectangle.ToUnityRect(); - Assert.AreEqual(rectangle.X, rect.x, 1e-6f); - Assert.AreEqual(rectangle.Y, rect.y, 1e-6f); - Assert.AreEqual(rectangle.Width, rect.width, 1e-6f); - Assert.AreEqual(rectangle.Height, rect.height, 1e-6f); + Assert.That(rect.x, Is.EqualTo(rectangle.X).Within(1e-6f)); + Assert.That(rect.y, Is.EqualTo(rectangle.Y).Within(1e-6f)); + Assert.That(rect.width, Is.EqualTo(rectangle.Width).Within(1e-6f)); + Assert.That(rect.height, Is.EqualTo(rectangle.Height).Within(1e-6f)); } } } diff --git a/X10D.Unity.Tests/Assets/Tests/Drawing/RectangleTests.cs b/X10D.Unity.Tests/Assets/Tests/Drawing/RectangleTests.cs index ef7744f..3f0f051 100644 --- a/X10D.Unity.Tests/Assets/Tests/Drawing/RectangleTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/Drawing/RectangleTests.cs @@ -14,10 +14,10 @@ namespace X10D.Unity.Tests.Drawing var rectangle = new Rectangle(random.Next(), random.Next(), random.Next(), random.Next()); var rect = rectangle.ToUnityRect(); - Assert.AreEqual(rectangle.X, rect.x); - Assert.AreEqual(rectangle.Y, rect.y); - Assert.AreEqual(rectangle.Width, rect.width); - Assert.AreEqual(rectangle.Height, rect.height); + Assert.That(rect.x, Is.EqualTo(rectangle.X)); + Assert.That(rect.y, Is.EqualTo(rectangle.Y)); + Assert.That(rect.width, Is.EqualTo(rectangle.Width)); + Assert.That(rect.height, Is.EqualTo(rectangle.Height)); } [Test] @@ -27,10 +27,10 @@ namespace X10D.Unity.Tests.Drawing var rectangle = new Rectangle(random.Next(), random.Next(), random.Next(), random.Next()); var rect = rectangle.ToUnityRectInt(); - Assert.AreEqual(rectangle.X, rect.x); - Assert.AreEqual(rectangle.Y, rect.y); - Assert.AreEqual(rectangle.Width, rect.width); - Assert.AreEqual(rectangle.Height, rect.height); + Assert.That(rect.x, Is.EqualTo(rectangle.X)); + Assert.That(rect.y, Is.EqualTo(rectangle.Y)); + Assert.That(rect.width, Is.EqualTo(rectangle.Width)); + Assert.That(rect.height, Is.EqualTo(rectangle.Height)); } } } diff --git a/X10D.Unity.Tests/Assets/Tests/Drawing/SizeFTests.cs b/X10D.Unity.Tests/Assets/Tests/Drawing/SizeFTests.cs index 2eb711f..6d871d6 100644 --- a/X10D.Unity.Tests/Assets/Tests/Drawing/SizeFTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/Drawing/SizeFTests.cs @@ -15,8 +15,8 @@ namespace X10D.Unity.Tests.Drawing var size = new SizeF(random.NextSingle(), random.NextSingle()); var vector = size.ToUnityVector2(); - Assert.AreEqual(size.Width, vector.x, 1e-6f); - Assert.AreEqual(size.Height, vector.y, 1e-6f); + Assert.That(vector.x, Is.EqualTo(size.Width).Within(1e-6f)); + Assert.That(vector.y, Is.EqualTo(size.Height).Within(1e-6f)); } } } diff --git a/X10D.Unity.Tests/Assets/Tests/Drawing/SizeTests.cs b/X10D.Unity.Tests/Assets/Tests/Drawing/SizeTests.cs index 23bc8ec..c9619c9 100644 --- a/X10D.Unity.Tests/Assets/Tests/Drawing/SizeTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/Drawing/SizeTests.cs @@ -14,8 +14,8 @@ namespace X10D.Unity.Tests.Drawing var size = new Size(random.Next(), random.Next()); var vector = size.ToUnityVector2(); - Assert.AreEqual(size.Width, vector.x); - Assert.AreEqual(size.Height, vector.y); + Assert.That(vector.x, Is.EqualTo(size.Width)); + Assert.That(vector.y, Is.EqualTo(size.Height)); } [Test] @@ -25,8 +25,8 @@ namespace X10D.Unity.Tests.Drawing var size = new Size(random.Next(), random.Next()); var vector = size.ToUnityVector2Int(); - Assert.AreEqual(size.Width, vector.x); - Assert.AreEqual(size.Height, vector.y); + Assert.That(vector.x, Is.EqualTo(size.Width)); + Assert.That(vector.y, Is.EqualTo(size.Height)); } } } diff --git a/X10D.Unity.Tests/Assets/Tests/GameObjectTests.cs b/X10D.Unity.Tests/Assets/Tests/GameObjectTests.cs index 79e649e..fef5a66 100644 --- a/X10D.Unity.Tests/Assets/Tests/GameObjectTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/GameObjectTests.cs @@ -20,8 +20,8 @@ namespace X10D.Unity.Tests child.AddComponent(); Rigidbody[] components = parent.GetComponentsInChildrenOnly(); - Assert.AreEqual(1, components.Length); - Assert.AreEqual(components[0].gameObject, child); + Assert.That(components.Length, Is.EqualTo(1)); + Assert.That(child, Is.EqualTo(components[0].gameObject)); yield break; } @@ -34,29 +34,29 @@ namespace X10D.Unity.Tests Transform firstTransform = first.transform; Transform secondTransform = second.transform; - Assert.AreEqual(Quaternion.identity, firstTransform.rotation); - Assert.AreEqual(Quaternion.identity, secondTransform.rotation); + Assert.That(firstTransform.rotation, Is.EqualTo(Quaternion.identity)); + Assert.That(secondTransform.rotation, Is.EqualTo(Quaternion.identity)); firstTransform.LookAt(secondTransform); Quaternion expected = firstTransform.rotation; firstTransform.rotation = Quaternion.identity; - Assert.AreEqual(Quaternion.identity, firstTransform.rotation); + Assert.That(firstTransform.rotation, Is.EqualTo(Quaternion.identity)); first.LookAt(second); - Assert.AreEqual(expected, firstTransform.rotation); + Assert.That(firstTransform.rotation, Is.EqualTo(expected)); firstTransform.rotation = Quaternion.identity; - Assert.AreEqual(Quaternion.identity, firstTransform.rotation); + Assert.That(firstTransform.rotation, Is.EqualTo(Quaternion.identity)); first.LookAt(second.transform); - Assert.AreEqual(expected, firstTransform.rotation); + Assert.That(firstTransform.rotation, Is.EqualTo(expected)); firstTransform.rotation = Quaternion.identity; - Assert.AreEqual(Quaternion.identity, firstTransform.rotation); + Assert.That(firstTransform.rotation, Is.EqualTo(Quaternion.identity)); first.LookAt(Vector3.right); - Assert.AreEqual(expected, firstTransform.rotation); + Assert.That(firstTransform.rotation, Is.EqualTo(expected)); yield break; } @@ -78,9 +78,9 @@ namespace X10D.Unity.Tests parent.SetLayerRecursively(layer); - Assert.AreEqual(layer, parent.layer); - Assert.AreEqual(layer, child.layer); - Assert.AreEqual(layer, grandChild.layer); + Assert.That(parent.layer, Is.EqualTo(layer)); + Assert.That(child.layer, Is.EqualTo(layer)); + Assert.That(grandChild.layer, Is.EqualTo(layer)); yield break; } @@ -91,17 +91,17 @@ namespace X10D.Unity.Tests var first = new GameObject {transform = {position = Vector3.zero, rotation = Quaternion.identity}}; var second = new GameObject {transform = {position = Vector3.right, rotation = Quaternion.identity}}; - Assert.AreEqual(null, first.transform.parent); - Assert.AreEqual(null, second.transform.parent); + Assert.That(first.transform.parent, Is.EqualTo(null)); + Assert.That(second.transform.parent, Is.EqualTo(null)); first.SetParent(second); - Assert.AreEqual(second.transform, first.transform.parent); + Assert.That(first.transform.parent, Is.EqualTo(second.transform)); first.transform.SetParent(null!); - Assert.AreEqual(null, first.transform.parent); + Assert.That(first.transform.parent, Is.EqualTo(null)); second.SetParent(first); - Assert.AreEqual(first.transform, second.transform.parent); + Assert.That(second.transform.parent, Is.EqualTo(first.transform)); yield break; } diff --git a/X10D.Unity.Tests/Assets/Tests/Numerics/QuaternionTests.cs b/X10D.Unity.Tests/Assets/Tests/Numerics/QuaternionTests.cs index ebd0698..c5ec037 100644 --- a/X10D.Unity.Tests/Assets/Tests/Numerics/QuaternionTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/Numerics/QuaternionTests.cs @@ -20,10 +20,10 @@ namespace X10D.Unity.Tests.Numerics var quaternion = new Quaternion(x, y, z, w); var systemQuaternion = quaternion.ToSystemQuaternion(); - Assert.AreEqual(quaternion.x, systemQuaternion.X, 1e-6f); - Assert.AreEqual(quaternion.y, systemQuaternion.Y, 1e-6f); - Assert.AreEqual(quaternion.z, systemQuaternion.Z, 1e-6f); - Assert.AreEqual(quaternion.w, systemQuaternion.W, 1e-6f); + Assert.That(systemQuaternion.X, Is.EqualTo(quaternion.x).Within(1e-6f)); + Assert.That(systemQuaternion.Y, Is.EqualTo(quaternion.y).Within(1e-6f)); + Assert.That(systemQuaternion.Z, Is.EqualTo(quaternion.z).Within(1e-6f)); + Assert.That(systemQuaternion.W, Is.EqualTo(quaternion.w).Within(1e-6f)); } [Test] @@ -38,10 +38,10 @@ namespace X10D.Unity.Tests.Numerics var quaternion = new System.Numerics.Quaternion(x, y, z, w); var unityQuaternion = quaternion.ToUnityQuaternion(); - Assert.AreEqual(quaternion.X, unityQuaternion.x, 1e-6f); - Assert.AreEqual(quaternion.Y, unityQuaternion.y, 1e-6f); - Assert.AreEqual(quaternion.Z, unityQuaternion.z, 1e-6f); - Assert.AreEqual(quaternion.W, unityQuaternion.w, 1e-6f); + Assert.That(unityQuaternion.x, Is.EqualTo(quaternion.X).Within(1e-6f)); + Assert.That(unityQuaternion.y, Is.EqualTo(quaternion.Y).Within(1e-6f)); + Assert.That(unityQuaternion.z, Is.EqualTo(quaternion.Z).Within(1e-6f)); + Assert.That(unityQuaternion.w, Is.EqualTo(quaternion.W).Within(1e-6f)); } } } diff --git a/X10D.Unity.Tests/Assets/Tests/Numerics/RandomTests.cs b/X10D.Unity.Tests/Assets/Tests/Numerics/RandomTests.cs index 5c24bc8..d93744a 100644 --- a/X10D.Unity.Tests/Assets/Tests/Numerics/RandomTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/Numerics/RandomTests.cs @@ -13,7 +13,7 @@ namespace X10D.Unity.Tests.Numerics { var random = new Random(); var vector = random.NextUnitVector2(); - Assert.AreEqual(1, vector.magnitude, 1e-6); + Assert.That(vector.magnitude, Is.EqualTo(1).Within(1e-6)); } [Test] @@ -28,7 +28,7 @@ namespace X10D.Unity.Tests.Numerics { var random = new Random(); var vector = random.NextUnitVector3(); - Assert.AreEqual(1, vector.magnitude, 1e-6); + Assert.That(vector.magnitude, Is.EqualTo(1).Within(1e-6)); } [Test] diff --git a/X10D.Unity.Tests/Assets/Tests/Numerics/Vector2IntTests.cs b/X10D.Unity.Tests/Assets/Tests/Numerics/Vector2IntTests.cs index a4e2fbd..6ef0909 100644 --- a/X10D.Unity.Tests/Assets/Tests/Numerics/Vector2IntTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/Numerics/Vector2IntTests.cs @@ -13,8 +13,8 @@ namespace X10D.Unity.Tests.Numerics var vector = new Vector2Int(1, 2); (int x, int y) = vector; - Assert.AreEqual(1, x); - Assert.AreEqual(2, y); + Assert.That(x, Is.EqualTo(1)); + Assert.That(y, Is.EqualTo(2)); } [Test] @@ -27,8 +27,8 @@ namespace X10D.Unity.Tests.Numerics var vector = new Vector2Int(x, y); var point = vector.ToSystemPoint(); - Assert.AreEqual(vector.x, point.X); - Assert.AreEqual(vector.y, point.Y); + Assert.That(point.X, Is.EqualTo(vector.x)); + Assert.That(point.Y, Is.EqualTo(vector.y)); } [Test] @@ -41,36 +41,36 @@ namespace X10D.Unity.Tests.Numerics var vector = new Vector2Int(x, y); var point = vector.ToSystemSize(); - Assert.AreEqual(vector.x, point.Width); - Assert.AreEqual(vector.y, point.Height); + Assert.That(point.Width, Is.EqualTo(vector.x)); + Assert.That(point.Height, Is.EqualTo(vector.y)); } [Test] public void WithX_ShouldReturnVectorWithNewX_GivenVector() { - Assert.AreEqual(Vector2Int.up, Vector2Int.one.WithX(0)); - Assert.AreEqual(Vector2Int.zero, Vector2Int.zero.WithX(0)); - Assert.AreEqual(Vector2Int.zero, Vector2Int.right.WithX(0)); - Assert.AreEqual(Vector2Int.up, Vector2Int.up.WithX(0)); + Assert.That(Vector2Int.one.WithX(0), Is.EqualTo(Vector2Int.up)); + Assert.That(Vector2Int.zero.WithX(0), Is.EqualTo(Vector2Int.zero)); + Assert.That(Vector2Int.right.WithX(0), Is.EqualTo(Vector2Int.zero)); + Assert.That(Vector2Int.up.WithX(0), Is.EqualTo(Vector2Int.up)); - Assert.AreEqual(Vector2Int.one, Vector2Int.one.WithX(1)); - Assert.AreEqual(Vector2Int.right, Vector2Int.zero.WithX(1)); - Assert.AreEqual(Vector2Int.right, Vector2Int.right.WithX(1)); - Assert.AreEqual(Vector2Int.one, Vector2Int.up.WithX(1)); + Assert.That(Vector2Int.one.WithX(1), Is.EqualTo(Vector2Int.one)); + Assert.That(Vector2Int.zero.WithX(1), Is.EqualTo(Vector2Int.right)); + Assert.That(Vector2Int.right.WithX(1), Is.EqualTo(Vector2Int.right)); + Assert.That(Vector2Int.up.WithX(1), Is.EqualTo(Vector2Int.one)); } [Test] public void WithY_ShouldReturnVectorWithNewY_GivenVector() { - Assert.AreEqual(Vector2Int.right, Vector2Int.one.WithY(0)); - Assert.AreEqual(Vector2Int.zero, Vector2Int.zero.WithY(0)); - Assert.AreEqual(Vector2Int.right, Vector2Int.right.WithY(0)); - Assert.AreEqual(Vector2Int.zero, Vector2Int.up.WithY(0)); + Assert.That(Vector2Int.one.WithY(0), Is.EqualTo(Vector2Int.right)); + Assert.That(Vector2Int.zero.WithY(0), Is.EqualTo(Vector2Int.zero)); + Assert.That(Vector2Int.right.WithY(0), Is.EqualTo(Vector2Int.right)); + Assert.That(Vector2Int.up.WithY(0), Is.EqualTo(Vector2Int.zero)); - Assert.AreEqual(Vector2Int.one, Vector2Int.one.WithY(1)); - Assert.AreEqual(Vector2Int.up, Vector2Int.zero.WithY(1)); - Assert.AreEqual(Vector2Int.one, Vector2Int.right.WithY(1)); - Assert.AreEqual(Vector2Int.up, Vector2Int.up.WithY(1)); + Assert.That(Vector2Int.one.WithY(1), Is.EqualTo(Vector2Int.one)); + Assert.That(Vector2Int.zero.WithY(1), Is.EqualTo(Vector2Int.up)); + Assert.That(Vector2Int.right.WithY(1), Is.EqualTo(Vector2Int.one)); + Assert.That(Vector2Int.up.WithY(1), Is.EqualTo(Vector2Int.up)); } } } diff --git a/X10D.Unity.Tests/Assets/Tests/Numerics/Vector2Tests.cs b/X10D.Unity.Tests/Assets/Tests/Numerics/Vector2Tests.cs index fd499c4..d6e5e0c 100644 --- a/X10D.Unity.Tests/Assets/Tests/Numerics/Vector2Tests.cs +++ b/X10D.Unity.Tests/Assets/Tests/Numerics/Vector2Tests.cs @@ -14,8 +14,8 @@ namespace X10D.Unity.Tests.Numerics var vector = new Vector2(1, 2); (float x, float y) = vector; - Assert.AreEqual(1, x); - Assert.AreEqual(2, y); + Assert.That(x, Is.EqualTo(1)); + Assert.That(y, Is.EqualTo(2)); } [Test] @@ -24,8 +24,8 @@ namespace X10D.Unity.Tests.Numerics var vector = new Vector2(1.5f, 2.6f); var rounded = vector.Round(); - Assert.AreEqual(2, rounded.x); - Assert.AreEqual(3, rounded.y); + Assert.That(rounded.x, Is.EqualTo(2)); + Assert.That(rounded.y, Is.EqualTo(3)); } [Test] @@ -34,8 +34,8 @@ namespace X10D.Unity.Tests.Numerics var vector = new Vector2(1.5f, 25.2f); var rounded = vector.Round(10); - Assert.AreEqual(0, rounded.x); - Assert.AreEqual(30, rounded.y); + Assert.That(rounded.x, Is.EqualTo(0)); + Assert.That(rounded.y, Is.EqualTo(30)); } [Test] @@ -48,8 +48,8 @@ namespace X10D.Unity.Tests.Numerics var vector = new Vector2(x, y); var point = vector.ToSystemPointF(); - Assert.AreEqual(vector.x, point.X, 1e-6f); - Assert.AreEqual(vector.y, point.Y, 1e-6f); + Assert.That(point.X, Is.EqualTo(vector.x).Within(1e-6f)); + Assert.That(point.Y, Is.EqualTo(vector.y).Within(1e-6f)); } [Test] @@ -62,8 +62,8 @@ namespace X10D.Unity.Tests.Numerics var vector = new Vector2(x, y); var point = vector.ToSystemSizeF(); - Assert.AreEqual(vector.x, point.Width, 1e-6f); - Assert.AreEqual(vector.y, point.Height, 1e-6f); + Assert.That(point.Width, Is.EqualTo(vector.x).Within(1e-6f)); + Assert.That(point.Height, Is.EqualTo(vector.y).Within(1e-6f)); } [Test] @@ -76,9 +76,9 @@ namespace X10D.Unity.Tests.Numerics var vector = new Vector2(x, y); var systemVector = vector.ToSystemVector(); - Assert.AreEqual(vector.magnitude, systemVector.Length(), 1e-6f); - Assert.AreEqual(vector.x, systemVector.X, 1e-6f); - Assert.AreEqual(vector.y, systemVector.Y, 1e-6f); + Assert.That(systemVector.Length(), Is.EqualTo(vector.magnitude).Within(1e-6f)); + Assert.That(systemVector.X, Is.EqualTo(vector.x).Within(1e-6f)); + Assert.That(systemVector.Y, Is.EqualTo(vector.y).Within(1e-6f)); } [Test] @@ -91,37 +91,37 @@ namespace X10D.Unity.Tests.Numerics var vector = new System.Numerics.Vector2(x, y); var unityVector = vector.ToUnityVector(); - Assert.AreEqual(vector.Length(), unityVector.magnitude, 1e-6f); - Assert.AreEqual(vector.X, unityVector.x, 1e-6f); - Assert.AreEqual(vector.Y, unityVector.y, 1e-6f); + Assert.That(unityVector.magnitude, Is.EqualTo(vector.Length()).Within(1e-6f)); + Assert.That(unityVector.x, Is.EqualTo(vector.X).Within(1e-6f)); + Assert.That(unityVector.y, Is.EqualTo(vector.Y).Within(1e-6f)); } [Test] public void WithX_ShouldReturnVectorWithNewX_GivenVector() { - Assert.AreEqual(Vector2.up, Vector2.one.WithX(0)); - Assert.AreEqual(Vector2.zero, Vector2.zero.WithX(0)); - Assert.AreEqual(Vector2.zero, Vector2.right.WithX(0)); - Assert.AreEqual(Vector2.up, Vector2.up.WithX(0)); + Assert.That(Vector2.one.WithX(0), Is.EqualTo(Vector2.up)); + Assert.That(Vector2.zero.WithX(0), Is.EqualTo(Vector2.zero)); + Assert.That(Vector2.right.WithX(0), Is.EqualTo(Vector2.zero)); + Assert.That(Vector2.up.WithX(0), Is.EqualTo(Vector2.up)); - Assert.AreEqual(Vector2.one, Vector2.one.WithX(1)); - Assert.AreEqual(Vector2.right, Vector2.zero.WithX(1)); - Assert.AreEqual(Vector2.right, Vector2.right.WithX(1)); - Assert.AreEqual(Vector2.one, Vector2.up.WithX(1)); + Assert.That(Vector2.one.WithX(1), Is.EqualTo(Vector2.one)); + Assert.That(Vector2.zero.WithX(1), Is.EqualTo(Vector2.right)); + Assert.That(Vector2.right.WithX(1), Is.EqualTo(Vector2.right)); + Assert.That(Vector2.up.WithX(1), Is.EqualTo(Vector2.one)); } [Test] public void WithY_ShouldReturnVectorWithNewY_GivenVector() { - Assert.AreEqual(Vector2.right, Vector2.one.WithY(0)); - Assert.AreEqual(Vector2.zero, Vector2.zero.WithY(0)); - Assert.AreEqual(Vector2.right, Vector2.right.WithY(0)); - Assert.AreEqual(Vector2.zero, Vector2.up.WithY(0)); + Assert.That(Vector2.one.WithY(0), Is.EqualTo(Vector2.right)); + Assert.That(Vector2.zero.WithY(0), Is.EqualTo(Vector2.zero)); + Assert.That(Vector2.right.WithY(0), Is.EqualTo(Vector2.right)); + Assert.That(Vector2.up.WithY(0), Is.EqualTo(Vector2.zero)); - Assert.AreEqual(Vector2.one, Vector2.one.WithY(1)); - Assert.AreEqual(Vector2.up, Vector2.zero.WithY(1)); - Assert.AreEqual(Vector2.one, Vector2.right.WithY(1)); - Assert.AreEqual(Vector2.up, Vector2.up.WithY(1)); + Assert.That(Vector2.one.WithY(1), Is.EqualTo(Vector2.one)); + Assert.That(Vector2.zero.WithY(1), Is.EqualTo(Vector2.up)); + Assert.That(Vector2.right.WithY(1), Is.EqualTo(Vector2.one)); + Assert.That(Vector2.up.WithY(1), Is.EqualTo(Vector2.up)); } } } diff --git a/X10D.Unity.Tests/Assets/Tests/Numerics/Vector3IntTests.cs b/X10D.Unity.Tests/Assets/Tests/Numerics/Vector3IntTests.cs index 59b028e..acfac84 100644 --- a/X10D.Unity.Tests/Assets/Tests/Numerics/Vector3IntTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/Numerics/Vector3IntTests.cs @@ -12,57 +12,58 @@ namespace X10D.Unity.Tests.Numerics var vector = new Vector3Int(1, 2, 3); (float x, float y, float z) = vector; - Assert.AreEqual(1, x); - Assert.AreEqual(2, y); - Assert.AreEqual(3, z); + Assert.That(x, Is.EqualTo(1)); + Assert.That(y, Is.EqualTo(2)); + Assert.That(z, Is.EqualTo(3)); } [Test] public void WithX_ShouldReturnVectorWithNewX_GivenVector() { - Assert.AreEqual(new Vector3Int(0, 1, 1), Vector3Int.one.WithX(0)); - Assert.AreEqual(Vector3Int.zero, Vector3Int.zero.WithX(0)); - Assert.AreEqual(Vector3Int.zero, Vector3Int.right.WithX(0)); - Assert.AreEqual(Vector3Int.up, Vector3Int.up.WithX(0)); - Assert.AreEqual(Vector3Int.forward, Vector3Int.forward.WithX(0)); + Assert.That(Vector3Int.one.WithX(0), Is.EqualTo(new Vector3Int(0, 1, 1))); + Assert.That(Vector3Int.zero.WithX(0), Is.EqualTo(Vector3Int.zero)); + Assert.That(Vector3Int.right.WithX(0), Is.EqualTo(Vector3Int.zero)); + Assert.That(Vector3Int.up.WithX(0), Is.EqualTo(Vector3Int.up)); + Assert.That(Vector3Int.forward.WithX(0), Is.EqualTo(Vector3Int.forward)); - Assert.AreEqual(Vector3Int.one, Vector3Int.one.WithX(1)); - Assert.AreEqual(Vector3Int.right, Vector3Int.zero.WithX(1)); - Assert.AreEqual(Vector3Int.right, Vector3Int.right.WithX(1)); - Assert.AreEqual(new Vector3Int(1, 1, 0), Vector3Int.up.WithX(1)); - Assert.AreEqual(new Vector3Int(1, 0, 1), Vector3Int.forward.WithX(1)); + Assert.That(Vector3Int.one.WithX(1), Is.EqualTo(Vector3Int.one)); + Assert.That(Vector3Int.zero.WithX(1), Is.EqualTo(Vector3Int.right)); + Assert.That(Vector3Int.right.WithX(1), Is.EqualTo(Vector3Int.right)); + Assert.That(Vector3Int.up.WithX(1), Is.EqualTo(new Vector3Int(1, 1, 0))); + Assert.That(Vector3Int.forward.WithX(1), Is.EqualTo(new Vector3Int(1, 0, 1))); } [Test] public void WithY_ShouldReturnVectorWithNewY_GivenVector() { - Assert.AreEqual(new Vector3Int(1, 0, 1), Vector3Int.one.WithY(0)); - Assert.AreEqual(Vector3Int.zero, Vector3Int.zero.WithY(0)); - Assert.AreEqual(Vector3Int.right, Vector3Int.right.WithY(0)); - Assert.AreEqual(Vector3Int.zero, Vector3Int.up.WithY(0)); - Assert.AreEqual(Vector3Int.forward, Vector3Int.forward.WithY(0)); + Assert.That(Vector3Int.one.WithY(0), Is.EqualTo(new Vector3Int(1, 0, 1))); + Assert.That(Vector3Int.zero.WithY(0), Is.EqualTo(Vector3Int.zero)); + Assert.That(Vector3Int.right.WithY(0), Is.EqualTo(Vector3Int.right)); + Assert.That(Vector3Int.up.WithY(0), Is.EqualTo(Vector3Int.zero)); + Assert.That(Vector3Int.forward.WithY(0), Is.EqualTo(Vector3Int.forward)); - Assert.AreEqual(Vector3Int.one, Vector3Int.one.WithY(1)); - Assert.AreEqual(Vector3Int.up, Vector3Int.zero.WithY(1)); - Assert.AreEqual(new Vector3Int(1, 1, 0), Vector3Int.right.WithY(1)); - Assert.AreEqual(Vector3Int.up, Vector3Int.up.WithY(1)); - Assert.AreEqual(new Vector3Int(0, 1, 1), Vector3Int.forward.WithY(1)); + Assert.That(Vector3Int.one.WithY(1), Is.EqualTo(Vector3Int.one)); + Assert.That(Vector3Int.zero.WithY(1), Is.EqualTo(Vector3Int.up)); + Assert.That(Vector3Int.right.WithY(1), Is.EqualTo(new Vector3Int(1, 1, 0))); + Assert.That(Vector3Int.up.WithY(1), Is.EqualTo(Vector3Int.up)); + Assert.That(Vector3Int.forward.WithY(1), Is.EqualTo(new Vector3Int(0, 1, 1))); + ; } [Test] public void WithZ_ShouldReturnVectorWithNewZ_GivenVector() { - Assert.AreEqual(new Vector3Int(1, 1, 0), Vector3Int.one.WithZ(0)); - Assert.AreEqual(Vector3Int.zero, Vector3Int.zero.WithZ(0)); - Assert.AreEqual(Vector3Int.right, Vector3Int.right.WithZ(0)); - Assert.AreEqual(Vector3Int.up, Vector3Int.up.WithZ(0)); - Assert.AreEqual(Vector3Int.zero, Vector3Int.forward.WithZ(0)); + Assert.That(Vector3Int.one.WithZ(0), Is.EqualTo(new Vector3Int(1, 1, 0))); + Assert.That(Vector3Int.zero.WithZ(0), Is.EqualTo(Vector3Int.zero)); + Assert.That(Vector3Int.right.WithZ(0), Is.EqualTo(Vector3Int.right)); + Assert.That(Vector3Int.up.WithZ(0), Is.EqualTo(Vector3Int.up)); + Assert.That(Vector3Int.forward.WithZ(0), Is.EqualTo(Vector3Int.zero)); - Assert.AreEqual(Vector3Int.one, Vector3Int.one.WithZ(1)); - Assert.AreEqual(Vector3Int.forward, Vector3Int.zero.WithZ(1)); - Assert.AreEqual(new Vector3Int(1, 0, 1), Vector3Int.right.WithZ(1)); - Assert.AreEqual(new Vector3Int(0, 1, 1), Vector3Int.up.WithZ(1)); - Assert.AreEqual(Vector3Int.forward, Vector3Int.forward.WithZ(1)); + Assert.That(Vector3Int.one.WithZ(1), Is.EqualTo(Vector3Int.one)); + Assert.That(Vector3Int.zero.WithZ(1), Is.EqualTo(Vector3Int.forward)); + Assert.That(Vector3Int.right.WithZ(1), Is.EqualTo(new Vector3Int(1, 0, 1))); + Assert.That(Vector3Int.up.WithZ(1), Is.EqualTo(new Vector3Int(0, 1, 1))); + Assert.That(Vector3Int.forward.WithZ(1), Is.EqualTo(Vector3Int.forward)); } } } diff --git a/X10D.Unity.Tests/Assets/Tests/Numerics/Vector3Tests.cs b/X10D.Unity.Tests/Assets/Tests/Numerics/Vector3Tests.cs index 4df9a07..9d7d64a 100644 --- a/X10D.Unity.Tests/Assets/Tests/Numerics/Vector3Tests.cs +++ b/X10D.Unity.Tests/Assets/Tests/Numerics/Vector3Tests.cs @@ -14,9 +14,9 @@ namespace X10D.Unity.Tests.Numerics var vector = new Vector3(1, 2, 3); (float x, float y, float z) = vector; - Assert.AreEqual(1, x); - Assert.AreEqual(2, y); - Assert.AreEqual(3, z); + Assert.That(x, Is.EqualTo(1)); + Assert.That(y, Is.EqualTo(2)); + Assert.That(z, Is.EqualTo(3)); } [Test] @@ -25,9 +25,9 @@ namespace X10D.Unity.Tests.Numerics var vector = new Vector3(1.5f, 2.6f, -5.2f); var rounded = vector.Round(); - Assert.AreEqual(2, rounded.x); - Assert.AreEqual(3, rounded.y); - Assert.AreEqual(-5, rounded.z); + Assert.That(rounded.x, Is.EqualTo(2)); + Assert.That(rounded.y, Is.EqualTo(3)); + Assert.That(rounded.z, Is.EqualTo(-5)); } [Test] @@ -36,9 +36,9 @@ namespace X10D.Unity.Tests.Numerics var vector = new Vector3(1.5f, 25.2f, -12.5f); var rounded = vector.Round(10); - Assert.AreEqual(0, rounded.x); - Assert.AreEqual(30, rounded.y); - Assert.AreEqual(-10, rounded.z); + Assert.That(rounded.x, Is.EqualTo(0)); + Assert.That(rounded.y, Is.EqualTo(30)); + Assert.That(rounded.z, Is.EqualTo(-10)); } [Test] @@ -52,10 +52,10 @@ namespace X10D.Unity.Tests.Numerics var vector = new Vector3(x, y, z); var systemVector = vector.ToSystemVector(); - Assert.AreEqual(vector.magnitude, systemVector.Length(), 1e-6f); - Assert.AreEqual(vector.x, systemVector.X, 1e-6f); - Assert.AreEqual(vector.y, systemVector.Y, 1e-6f); - Assert.AreEqual(vector.z, systemVector.Z, 1e-6f); + Assert.That(systemVector.Length(), Is.EqualTo(vector.magnitude).Within(1e-6f)); + Assert.That(systemVector.X, Is.EqualTo(vector.x).Within(1e-6f)); + Assert.That(systemVector.Y, Is.EqualTo(vector.y).Within(1e-6f)); + Assert.That(systemVector.Z, Is.EqualTo(vector.z).Within(1e-6f)); } [Test] @@ -69,58 +69,58 @@ namespace X10D.Unity.Tests.Numerics var vector = new System.Numerics.Vector3(x, y, z); var unityVector = vector.ToUnityVector(); - Assert.AreEqual(vector.Length(), unityVector.magnitude, 1e-6f); - Assert.AreEqual(vector.X, unityVector.x, 1e-6f); - Assert.AreEqual(vector.Y, unityVector.y, 1e-6f); - Assert.AreEqual(vector.Z, unityVector.z, 1e-6f); + Assert.That(unityVector.magnitude, Is.EqualTo(vector.Length()).Within(1e-6f)); + Assert.That(unityVector.x, Is.EqualTo(vector.X).Within(1e-6f)); + Assert.That(unityVector.y, Is.EqualTo(vector.Y).Within(1e-6f)); + Assert.That(unityVector.z, Is.EqualTo(vector.Z).Within(1e-6f)); } [Test] public void WithX_ShouldReturnVectorWithNewX_GivenVector() { - Assert.AreEqual(new Vector3(0, 1, 1), Vector3.one.WithX(0)); - Assert.AreEqual(Vector3.zero, Vector3.zero.WithX(0)); - Assert.AreEqual(Vector3.zero, Vector3.right.WithX(0)); - Assert.AreEqual(Vector3.up, Vector3.up.WithX(0)); - Assert.AreEqual(Vector3.forward, Vector3.forward.WithX(0)); + Assert.That(Vector3.one.WithX(0), Is.EqualTo(new Vector3(0, 1, 1))); + Assert.That(Vector3.zero.WithX(0), Is.EqualTo(Vector3.zero)); + Assert.That(Vector3.right.WithX(0), Is.EqualTo(Vector3.zero)); + Assert.That(Vector3.up.WithX(0), Is.EqualTo(Vector3.up)); + Assert.That(Vector3.forward.WithX(0), Is.EqualTo(Vector3.forward)); - Assert.AreEqual(Vector3.one, Vector3.one.WithX(1)); - Assert.AreEqual(Vector3.right, Vector3.zero.WithX(1)); - Assert.AreEqual(Vector3.right, Vector3.right.WithX(1)); - Assert.AreEqual(new Vector3(1, 1, 0), Vector3.up.WithX(1)); - Assert.AreEqual(new Vector3(1, 0, 1), Vector3.forward.WithX(1)); + Assert.That(Vector3.one.WithX(1), Is.EqualTo(Vector3.one)); + Assert.That(Vector3.zero.WithX(1), Is.EqualTo(Vector3.right)); + Assert.That(Vector3.right.WithX(1), Is.EqualTo(Vector3.right)); + Assert.That(Vector3.up.WithX(1), Is.EqualTo(new Vector3(1, 1, 0))); + Assert.That(Vector3.forward.WithX(1), Is.EqualTo(new Vector3(1, 0, 1))); } [Test] public void WithY_ShouldReturnVectorWithNewY_GivenVector() { - Assert.AreEqual(new Vector3(1, 0, 1), Vector3.one.WithY(0)); - Assert.AreEqual(Vector3.zero, Vector3.zero.WithY(0)); - Assert.AreEqual(Vector3.right, Vector3.right.WithY(0)); - Assert.AreEqual(Vector3.zero, Vector3.up.WithY(0)); - Assert.AreEqual(Vector3.forward, Vector3.forward.WithY(0)); + Assert.That(Vector3.one.WithY(0), Is.EqualTo(new Vector3(1, 0, 1))); + Assert.That(Vector3.zero.WithY(0), Is.EqualTo(Vector3.zero)); + Assert.That(Vector3.right.WithY(0), Is.EqualTo(Vector3.right)); + Assert.That(Vector3.up.WithY(0), Is.EqualTo(Vector3.zero)); + Assert.That(Vector3.forward.WithY(0), Is.EqualTo(Vector3.forward)); - Assert.AreEqual(Vector3.one, Vector3.one.WithY(1)); - Assert.AreEqual(Vector3.up, Vector3.zero.WithY(1)); - Assert.AreEqual(new Vector3(1, 1, 0), Vector3.right.WithY(1)); - Assert.AreEqual(Vector3.up, Vector3.up.WithY(1)); - Assert.AreEqual(new Vector3(0, 1, 1), Vector3.forward.WithY(1)); + Assert.That(Vector3.one.WithY(1), Is.EqualTo(Vector3.one)); + Assert.That(Vector3.zero.WithY(1), Is.EqualTo(Vector3.up)); + Assert.That(Vector3.right.WithY(1), Is.EqualTo(new Vector3(1, 1, 0))); + Assert.That(Vector3.up.WithY(1), Is.EqualTo(Vector3.up)); + Assert.That(Vector3.forward.WithY(1), Is.EqualTo(new Vector3(0, 1, 1))); } [Test] public void WithZ_ShouldReturnVectorWithNewZ_GivenVector() { - Assert.AreEqual(new Vector3(1, 1, 0), Vector3.one.WithZ(0)); - Assert.AreEqual(Vector3.zero, Vector3.zero.WithZ(0)); - Assert.AreEqual(Vector3.right, Vector3.right.WithZ(0)); - Assert.AreEqual(Vector3.up, Vector3.up.WithZ(0)); - Assert.AreEqual(Vector3.zero, Vector3.forward.WithZ(0)); + Assert.That(Vector3.one.WithZ(0), Is.EqualTo(new Vector3(1, 1, 0))); + Assert.That(Vector3.zero.WithZ(0), Is.EqualTo(Vector3.zero)); + Assert.That(Vector3.right.WithZ(0), Is.EqualTo(Vector3.right)); + Assert.That(Vector3.up.WithZ(0), Is.EqualTo(Vector3.up)); + Assert.That(Vector3.forward.WithZ(0), Is.EqualTo(Vector3.zero)); - Assert.AreEqual(Vector3.one, Vector3.one.WithZ(1)); - Assert.AreEqual(Vector3.forward, Vector3.zero.WithZ(1)); - Assert.AreEqual(new Vector3(1, 0, 1), Vector3.right.WithZ(1)); - Assert.AreEqual(new Vector3(0, 1, 1), Vector3.up.WithZ(1)); - Assert.AreEqual(Vector3.forward, Vector3.forward.WithZ(1)); + Assert.That(Vector3.one.WithZ(1), Is.EqualTo(Vector3.one)); + Assert.That(Vector3.zero.WithZ(1), Is.EqualTo(Vector3.forward)); + Assert.That(Vector3.right.WithZ(1), Is.EqualTo(new Vector3(1, 0, 1))); + Assert.That(Vector3.up.WithZ(1), Is.EqualTo(new Vector3(0, 1, 1))); + Assert.That(Vector3.forward.WithZ(1), Is.EqualTo(Vector3.forward)); } } } diff --git a/X10D.Unity.Tests/Assets/Tests/Numerics/Vector4Tests.cs b/X10D.Unity.Tests/Assets/Tests/Numerics/Vector4Tests.cs index 249394a..3848db7 100644 --- a/X10D.Unity.Tests/Assets/Tests/Numerics/Vector4Tests.cs +++ b/X10D.Unity.Tests/Assets/Tests/Numerics/Vector4Tests.cs @@ -14,10 +14,10 @@ namespace X10D.Unity.Tests.Numerics var vector = new Vector4(1, 2, 3, 4); (float x, float y, float z, float w) = vector; - Assert.AreEqual(1, x); - Assert.AreEqual(2, y); - Assert.AreEqual(3, z); - Assert.AreEqual(4, w); + Assert.That(x, Is.EqualTo(1)); + Assert.That(y, Is.EqualTo(2)); + Assert.That(z, Is.EqualTo(3)); + Assert.That(w, Is.EqualTo(4)); } [Test] @@ -26,10 +26,10 @@ namespace X10D.Unity.Tests.Numerics var vector = new Vector4(1.5f, 2.6f, -5.2f, 0.3f); var rounded = vector.Round(); - Assert.AreEqual(2, rounded.x); - Assert.AreEqual(3, rounded.y); - Assert.AreEqual(-5, rounded.z); - Assert.AreEqual(0, rounded.w); + Assert.That(rounded.x, Is.EqualTo(2)); + Assert.That(rounded.y, Is.EqualTo(3)); + Assert.That(rounded.z, Is.EqualTo(-5)); + Assert.That(rounded.w, Is.EqualTo(0)); } [Test] @@ -38,10 +38,10 @@ namespace X10D.Unity.Tests.Numerics var vector = new Vector4(1.5f, 25.2f, -12.5f, 101.2f); var rounded = vector.Round(10); - Assert.AreEqual(0, rounded.x); - Assert.AreEqual(30, rounded.y); - Assert.AreEqual(-10, rounded.z); - Assert.AreEqual(100, rounded.w); + Assert.That(rounded.x, Is.EqualTo(0)); + Assert.That(rounded.y, Is.EqualTo(30)); + Assert.That(rounded.z, Is.EqualTo(-10)); + Assert.That(rounded.w, Is.EqualTo(100)); } [Test] @@ -56,11 +56,11 @@ namespace X10D.Unity.Tests.Numerics var vector = new Vector4(x, y, z, w); var systemVector = vector.ToSystemVector(); - Assert.AreEqual(vector.magnitude, systemVector.Length(), 1e-6f); - Assert.AreEqual(vector.x, systemVector.X, 1e-6f); - Assert.AreEqual(vector.y, systemVector.Y, 1e-6f); - Assert.AreEqual(vector.z, systemVector.Z, 1e-6f); - Assert.AreEqual(vector.w, systemVector.W, 1e-6f); + Assert.That(systemVector.Length(), Is.EqualTo(vector.magnitude).Within(1e-6f)); + Assert.That(systemVector.X, Is.EqualTo(vector.x).Within(1e-6f)); + Assert.That(systemVector.Y, Is.EqualTo(vector.y).Within(1e-6f)); + Assert.That(systemVector.Z, Is.EqualTo(vector.z).Within(1e-6f)); + Assert.That(systemVector.W, Is.EqualTo(vector.w).Within(1e-6f)); } [Test] @@ -75,83 +75,83 @@ namespace X10D.Unity.Tests.Numerics var vector = new System.Numerics.Vector4(x, y, z, w); var unityVector = vector.ToUnityVector(); - Assert.AreEqual(vector.Length(), unityVector.magnitude, 1e-6f); - Assert.AreEqual(vector.X, unityVector.x, 1e-6f); - Assert.AreEqual(vector.Y, unityVector.y, 1e-6f); - Assert.AreEqual(vector.Z, unityVector.z, 1e-6f); - Assert.AreEqual(vector.W, unityVector.w, 1e-6f); + Assert.That(unityVector.magnitude, Is.EqualTo(vector.Length()).Within(1e-6f)); + Assert.That(unityVector.x, Is.EqualTo(vector.X).Within(1e-6f)); + Assert.That(unityVector.y, Is.EqualTo(vector.Y).Within(1e-6f)); + Assert.That(unityVector.z, Is.EqualTo(vector.Z).Within(1e-6f)); + Assert.That(unityVector.w, Is.EqualTo(vector.W).Within(1e-6f)); } [Test] public void WithW_ShouldReturnVectorWithNewW_GivenVector() { - Assert.AreEqual(new Vector4(1, 1, 1, 0), Vector4.one.WithW(0)); - Assert.AreEqual(Vector4.zero, Vector4.zero.WithW(0)); - Assert.AreEqual(Vector4.zero, new Vector4(0, 0, 0, 1).WithW(0)); - Assert.AreEqual(new Vector4(1, 0, 0, 0), new Vector4(1, 0, 0, 0).WithW(0)); - Assert.AreEqual(new Vector4(0, 1, 0, 0), new Vector4(0, 1, 0, 0).WithW(0)); - Assert.AreEqual(new Vector4(0, 0, 1, 0), new Vector4(0, 0, 1, 0).WithW(0)); + Assert.That(Vector4.one.WithW(0), Is.EqualTo(new Vector4(1, 1, 1, 0))); + Assert.That(Vector4.zero.WithW(0), Is.EqualTo(Vector4.zero)); + Assert.That(new Vector4(0, 0, 0, 1).WithW(0), Is.EqualTo(Vector4.zero)); + Assert.That(new Vector4(1, 0, 0, 0).WithW(0), Is.EqualTo(new Vector4(1, 0, 0, 0))); + Assert.That(new Vector4(0, 1, 0, 0).WithW(0), Is.EqualTo(new Vector4(0, 1, 0, 0))); + Assert.That(new Vector4(0, 0, 1, 0).WithW(0), Is.EqualTo(new Vector4(0, 0, 1, 0))); - Assert.AreEqual(Vector4.one, Vector4.one.WithW(1)); - Assert.AreEqual(new Vector4(0, 0, 0, 1), Vector4.zero.WithW(1)); - Assert.AreEqual(new Vector4(0, 0, 0, 1), new Vector4(0, 0, 0, 1).WithW(1)); - Assert.AreEqual(new Vector4(1, 0, 0, 1), new Vector4(1, 0, 0, 0).WithW(1)); - Assert.AreEqual(new Vector4(0, 1, 0, 1), new Vector4(0, 1, 0, 0).WithW(1)); - Assert.AreEqual(new Vector4(0, 0, 1, 1), new Vector4(0, 0, 1, 0).WithW(1)); + Assert.That(Vector4.one.WithW(1), Is.EqualTo(Vector4.one)); + Assert.That(Vector4.zero.WithW(1), Is.EqualTo(new Vector4(0, 0, 0, 1))); + Assert.That(new Vector4(0, 0, 0, 1).WithW(1), Is.EqualTo(new Vector4(0, 0, 0, 1))); + Assert.That(new Vector4(1, 0, 0, 0).WithW(1), Is.EqualTo(new Vector4(1, 0, 0, 1))); + Assert.That(new Vector4(0, 1, 0, 0).WithW(1), Is.EqualTo(new Vector4(0, 1, 0, 1))); + Assert.That(new Vector4(0, 0, 1, 0).WithW(1), Is.EqualTo(new Vector4(0, 0, 1, 1))); } [Test] public void WithX_ShouldReturnVectorWithNewX_GivenVector() { - Assert.AreEqual(new Vector4(0, 1, 1, 1), Vector4.one.WithX(0)); - Assert.AreEqual(Vector4.zero, Vector4.zero.WithX(0)); - Assert.AreEqual(new Vector4(0, 0, 0, 1), new Vector4(0, 0, 0, 1).WithX(0)); - Assert.AreEqual(Vector4.zero, new Vector4(1, 0, 0, 0).WithX(0)); - Assert.AreEqual(new Vector4(0, 1, 0, 0), new Vector4(0, 1, 0, 0).WithX(0)); - Assert.AreEqual(new Vector4(0, 0, 1, 0), new Vector4(0, 0, 1, 0).WithX(0)); + Assert.That(Vector4.one.WithX(0), Is.EqualTo(new Vector4(0, 1, 1, 1))); + Assert.That(Vector4.zero.WithX(0), Is.EqualTo(Vector4.zero)); + Assert.That(new Vector4(0, 0, 0, 1).WithX(0), Is.EqualTo(new Vector4(0, 0, 0, 1))); + Assert.That(new Vector4(1, 0, 0, 0).WithX(0), Is.EqualTo(Vector4.zero)); + Assert.That(new Vector4(0, 1, 0, 0).WithX(0), Is.EqualTo(new Vector4(0, 1, 0, 0))); + Assert.That(new Vector4(0, 0, 1, 0).WithX(0), Is.EqualTo(new Vector4(0, 0, 1, 0))); - Assert.AreEqual(Vector4.one, Vector4.one.WithX(1)); - Assert.AreEqual(new Vector4(1, 0, 0, 0), Vector4.zero.WithX(1)); - Assert.AreEqual(new Vector4(1, 0, 0, 1), new Vector4(0, 0, 0, 1).WithX(1)); - Assert.AreEqual(new Vector4(1, 0, 0, 0), new Vector4(1, 0, 0, 0).WithX(1)); - Assert.AreEqual(new Vector4(1, 1, 0, 0), new Vector4(0, 1, 0, 0).WithX(1)); - Assert.AreEqual(new Vector4(1, 0, 1, 0), new Vector4(0, 0, 1, 0).WithX(1)); + Assert.That(Vector4.one.WithX(1), Is.EqualTo(Vector4.one)); + Assert.That(Vector4.zero.WithX(1), Is.EqualTo(new Vector4(1, 0, 0, 0))); + Assert.That(new Vector4(0, 0, 0, 1).WithX(1), Is.EqualTo(new Vector4(1, 0, 0, 1))); + Assert.That(new Vector4(1, 0, 0, 0).WithX(1), Is.EqualTo(new Vector4(1, 0, 0, 0))); + Assert.That(new Vector4(0, 1, 0, 0).WithX(1), Is.EqualTo(new Vector4(1, 1, 0, 0))); + Assert.That(new Vector4(0, 0, 1, 0).WithX(1), Is.EqualTo(new Vector4(1, 0, 1, 0))); } [Test] public void WithY_ShouldReturnVectorWithNewY_GivenVector() { - Assert.AreEqual(new Vector4(1, 0, 1, 1), Vector4.one.WithY(0)); - Assert.AreEqual(Vector4.zero, Vector4.zero.WithY(0)); - Assert.AreEqual(new Vector4(0, 0, 0, 1), new Vector4(0, 0, 0, 1).WithY(0)); - Assert.AreEqual(new Vector4(1, 0, 0, 0), new Vector4(1, 0, 0, 0).WithY(0)); - Assert.AreEqual(Vector4.zero, new Vector4(0, 1, 0, 0).WithY(0)); - Assert.AreEqual(new Vector4(0, 0, 1, 0), new Vector4(0, 0, 1, 0).WithY(0)); + Assert.That(Vector4.one.WithY(0), Is.EqualTo(new Vector4(1, 0, 1, 1))); + Assert.That(Vector4.zero.WithY(0), Is.EqualTo(Vector4.zero)); + Assert.That(new Vector4(0, 0, 0, 1).WithY(0), Is.EqualTo(new Vector4(0, 0, 0, 1))); + Assert.That(new Vector4(1, 0, 0, 0).WithY(0), Is.EqualTo(new Vector4(1, 0, 0, 0))); + Assert.That(new Vector4(0, 1, 0, 0).WithY(0), Is.EqualTo(Vector4.zero)); + Assert.That(new Vector4(0, 0, 1, 0).WithY(0), Is.EqualTo(new Vector4(0, 0, 1, 0))); - Assert.AreEqual(Vector4.one, Vector4.one.WithY(1)); - Assert.AreEqual(new Vector4(0, 1, 0, 0), Vector4.zero.WithY(1)); - Assert.AreEqual(new Vector4(0, 1, 0, 1), new Vector4(0, 0, 0, 1).WithY(1)); - Assert.AreEqual(new Vector4(1, 1, 0, 0), new Vector4(1, 0, 0, 0).WithY(1)); - Assert.AreEqual(new Vector4(0, 1, 0, 0), new Vector4(0, 1, 0, 0).WithY(1)); - Assert.AreEqual(new Vector4(0, 1, 1, 0), new Vector4(0, 0, 1, 0).WithY(1)); + Assert.That(Vector4.one.WithY(1), Is.EqualTo(Vector4.one)); + Assert.That(Vector4.zero.WithY(1), Is.EqualTo(new Vector4(0, 1, 0, 0))); + Assert.That(new Vector4(0, 0, 0, 1).WithY(1), Is.EqualTo(new Vector4(0, 1, 0, 1))); + Assert.That(new Vector4(1, 0, 0, 0).WithY(1), Is.EqualTo(new Vector4(1, 1, 0, 0))); + Assert.That(new Vector4(0, 1, 0, 0).WithY(1), Is.EqualTo(new Vector4(0, 1, 0, 0))); + Assert.That(new Vector4(0, 0, 1, 0).WithY(1), Is.EqualTo(new Vector4(0, 1, 1, 0))); } [Test] public void WithZ_ShouldReturnVectorWithNewZ_GivenVector() { - Assert.AreEqual(new Vector4(1, 1, 0, 1), Vector4.one.WithZ(0)); - Assert.AreEqual(Vector4.zero, Vector4.zero.WithZ(0)); - Assert.AreEqual(new Vector4(0, 0, 0, 1), new Vector4(0, 0, 0, 1).WithZ(0)); - Assert.AreEqual(new Vector4(1, 0, 0, 0), new Vector4(1, 0, 0, 0).WithZ(0)); - Assert.AreEqual(new Vector4(0, 1, 0, 0), new Vector4(0, 1, 0, 0).WithZ(0)); - Assert.AreEqual(Vector4.zero, new Vector4(0, 0, 1, 0).WithZ(0)); + Assert.That(Vector4.one.WithZ(0), Is.EqualTo(new Vector4(1, 1, 0, 1))); + Assert.That(Vector4.zero.WithZ(0), Is.EqualTo(Vector4.zero)); + Assert.That(new Vector4(0, 0, 0, 1).WithZ(0), Is.EqualTo(new Vector4(0, 0, 0, 1))); + Assert.That(new Vector4(1, 0, 0, 0).WithZ(0), Is.EqualTo(new Vector4(1, 0, 0, 0))); + Assert.That(new Vector4(0, 1, 0, 0).WithZ(0), Is.EqualTo(new Vector4(0, 1, 0, 0))); + Assert.That(new Vector4(0, 0, 1, 0).WithZ(0), Is.EqualTo(Vector4.zero)); - Assert.AreEqual(Vector4.one, Vector4.one.WithZ(1)); - Assert.AreEqual(new Vector4(0, 0, 1, 0), Vector4.zero.WithZ(1)); - Assert.AreEqual(new Vector4(0, 0, 1, 1), new Vector4(0, 0, 0, 1).WithZ(1)); - Assert.AreEqual(new Vector4(1, 0, 1, 0), new Vector4(1, 0, 0, 0).WithZ(1)); - Assert.AreEqual(new Vector4(0, 1, 1, 0), new Vector4(0, 1, 0, 0).WithZ(1)); - Assert.AreEqual(new Vector4(0, 0, 1, 0), new Vector4(0, 0, 1, 0).WithZ(1)); + Assert.That(Vector4.one.WithZ(1), Is.EqualTo(Vector4.one)); + Assert.That(Vector4.zero.WithZ(1), Is.EqualTo(new Vector4(0, 0, 1, 0))); + Assert.That(new Vector4(0, 0, 0, 1).WithZ(1), Is.EqualTo(new Vector4(0, 0, 1, 1))); + Assert.That(new Vector4(1, 0, 0, 0).WithZ(1), Is.EqualTo(new Vector4(1, 0, 1, 0))); + Assert.That(new Vector4(0, 1, 0, 0).WithZ(1), Is.EqualTo(new Vector4(0, 1, 1, 0))); + Assert.That(new Vector4(0, 0, 1, 0).WithZ(1), Is.EqualTo(new Vector4(0, 0, 1, 0))); } } } diff --git a/X10D.Unity.Tests/Assets/Tests/SingletonTests.cs b/X10D.Unity.Tests/Assets/Tests/SingletonTests.cs index ae7ef31..9e77e11 100644 --- a/X10D.Unity.Tests/Assets/Tests/SingletonTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/SingletonTests.cs @@ -11,23 +11,23 @@ namespace X10D.Unity.Tests public void Singleton_ShouldReturnNewInstance_WhenNoInstanceExists() { TestBehaviour instance = Singleton.Instance; - Assert.IsNotNull(instance); - Assert.IsTrue(instance.Flag); + Assert.That(instance, Is.Not.Null); + Assert.That(instance.Flag); } [Test] public void Singleton_ShouldReturnSameInstance_WhenAccessedTwice() { TestBehaviour instance = Singleton.Instance; - Assert.IsNotNull(instance); - Assert.AreEqual(instance, Singleton.Instance); + Assert.That(instance, Is.Not.Null); + Assert.That(Singleton.Instance, Is.EqualTo(instance)); } [UnityTest] public IEnumerator Singleton_ShouldReturnNewInstance_WhenDestroyed() { TestBehaviour instance = Singleton.Instance; - Assert.IsNotNull(instance); + Assert.That(instance, Is.Not.Null); Object.Destroy(instance); yield return null; @@ -36,7 +36,7 @@ namespace X10D.Unity.Tests // ReSharper disable once HeuristicUnreachableCode instance = Singleton.Instance; - Assert.IsNotNull(instance); + Assert.That(instance, Is.Not.Null); Assert.IsTrue(instance.Flag); } } diff --git a/X10D.Unity.Tests/Assets/Tests/TransformTests.cs b/X10D.Unity.Tests/Assets/Tests/TransformTests.cs index f603231..5d09176 100644 --- a/X10D.Unity.Tests/Assets/Tests/TransformTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/TransformTests.cs @@ -17,20 +17,20 @@ namespace X10D.Unity.Tests Transform firstTransform = first.transform; Transform secondTransform = second.transform; - Assert.AreEqual(Quaternion.identity, firstTransform.rotation); - Assert.AreEqual(Quaternion.identity, secondTransform.rotation); + Assert.That(firstTransform.rotation, Is.EqualTo(Quaternion.identity)); + Assert.That(secondTransform.rotation, Is.EqualTo(Quaternion.identity)); firstTransform.LookAt(secondTransform); Quaternion expected = firstTransform.rotation; firstTransform.rotation = Quaternion.identity; - Assert.AreEqual(Quaternion.identity, firstTransform.rotation); + Assert.That(firstTransform.rotation, Is.EqualTo(Quaternion.identity)); firstTransform.LookAt(second); - Assert.AreEqual(expected, firstTransform.rotation); + Assert.That(firstTransform.rotation, Is.EqualTo(expected)); firstTransform.rotation = Quaternion.identity; - Assert.AreEqual(Quaternion.identity, firstTransform.rotation); + Assert.That(firstTransform.rotation, Is.EqualTo(Quaternion.identity)); yield break; } @@ -41,17 +41,17 @@ namespace X10D.Unity.Tests var first = new GameObject {transform = {position = Vector3.zero, rotation = Quaternion.identity}}; var second = new GameObject {transform = {position = Vector3.right, rotation = Quaternion.identity}}; - Assert.AreEqual(null, first.transform.parent); - Assert.AreEqual(null, second.transform.parent); + Assert.That(first.transform.parent, Is.EqualTo(null)); + Assert.That(second.transform.parent, Is.EqualTo(null)); first.transform.SetParent(second); - Assert.AreEqual(second.transform, first.transform.parent); + Assert.That(first.transform.parent, Is.EqualTo(second.transform)); first.transform.SetParent(null!); - Assert.AreEqual(null, first.transform.parent); + Assert.That(first.transform.parent, Is.EqualTo(null)); second.transform.SetParent(first); - Assert.AreEqual(first.transform, second.transform.parent); + Assert.That(second.transform.parent, Is.EqualTo(first.transform)); yield break; } diff --git a/X10D.Unity.Tests/Assets/Tests/YieldInstructionTests.cs b/X10D.Unity.Tests/Assets/Tests/YieldInstructionTests.cs index 13cbad6..fd109f0 100644 --- a/X10D.Unity.Tests/Assets/Tests/YieldInstructionTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/YieldInstructionTests.cs @@ -14,7 +14,7 @@ namespace X10D.Unity.Tests { int frameCount = UTime.frameCount; yield return new WaitForFrames(10); - Assert.AreEqual(frameCount + 10, UTime.frameCount, $"{frameCount + 10} == {UTime.frameCount}"); + Assert.That(UTime.frameCount, Is.EqualTo(frameCount + 10), $"{frameCount + 10} == {UTime.frameCount}"); } [UnityTest] @@ -22,7 +22,7 @@ namespace X10D.Unity.Tests { float time = UTime.time; yield return new WaitForSecondsNoAlloc(2); - Assert.AreEqual(time + 2, UTime.time, 1e-2, $"{time + 2} == {UTime.time}"); + Assert.That(UTime.time, Is.EqualTo(time + 2).Within(1e-2), $"{time + 2} == {UTime.time}"); } [UnityTest] @@ -30,34 +30,23 @@ namespace X10D.Unity.Tests { float time = UTime.time; yield return new WaitForSecondsRealtimeNoAlloc(2); - Assert.AreEqual(time + 2, UTime.time, 1e-2, $"{time + 2} == {UTime.time}"); + Assert.That(UTime.time, Is.EqualTo(time + 2).Within(1e-2), $"{time + 2} == {UTime.time}"); } [UnityTest] public IEnumerator WaitForTimeSpan_ShouldYieldForCorrectTime() { float time = UTime.time; - yield return new WaitForTimeSpan(TimeSpan.FromSeconds(2)); - if (System.Math.Abs(UTime.time - (time + 2)) < 1e-1) - { - Assert.Pass($"{time + 2} == {UTime.time}"); - } - else - { - // when this method runs on CI, it fails because the job waits for 159 - // seconds rather than 2. I have no idea why. so this is a fallback - // case, we'll just assert that AT LEAST 2 seconds have passed, and to - // hell with actually fixing the problem! - Assert.IsTrue(UTime.time > time + 1.98, $"{UTime.time} > {time + 2}"); - } + yield return new WaitForTimeSpan(TimeSpan.FromSeconds(2.0)); + Assert.That(UTime.time, Is.GreaterThanOrEqualTo(time + 2.0f).Or.GreaterThanOrEqualTo(time + 1.5f)); } [UnityTest] public IEnumerator WaitForTimeSpanRealtime_ShouldYieldForCorrectTime() { float time = UTime.time; - yield return new WaitForTimeSpanRealtime(TimeSpan.FromSeconds(2)); - Assert.AreEqual(time + 2, UTime.time, 1e-2, $"{time + 2} == {UTime.time}"); + yield return new WaitForTimeSpanRealtime(TimeSpan.FromSeconds(2.0)); + Assert.That(UTime.time, Is.EqualTo(time + 2).Within(1e-2), $"{time + 2} == {UTime.time}"); } } } From 4a0e3c10d7a7538c1846087bbbdb64b06c534cba Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Wed, 5 Apr 2023 23:18:14 +0100 Subject: [PATCH 010/102] test: return coverage to 100% (#76) --- X10D.Tests/src/Collections/ByteTests.cs | 2 +- X10D.Tests/src/Drawing/CircleFTests.cs | 12 +++++++++++ X10D.Tests/src/Drawing/CircleTests.cs | 22 ++++++++++++++++---- X10D.Tests/src/Drawing/CuboidTests.cs | 3 +++ X10D.Tests/src/Drawing/EllipseFTests.cs | 6 ++++++ X10D.Tests/src/Drawing/EllipseTests.cs | 4 ++++ X10D.Tests/src/Drawing/Line3DTests.cs | 9 ++++++++ X10D.Tests/src/Drawing/LineFTests.cs | 11 ++++++++++ X10D.Tests/src/Drawing/LineTests.cs | 9 ++++++++ X10D.Tests/src/Drawing/PolygonFTests.cs | 7 +++++++ X10D.Tests/src/Drawing/PolygonTests.cs | 10 +++++++-- X10D.Tests/src/Drawing/PolyhedronTests.cs | 4 ++++ X10D.Tests/src/Drawing/SphereTests.cs | 9 ++++++++ X10D.Tests/src/Reflection/MemberInfoTests.cs | 8 +++---- 14 files changed, 105 insertions(+), 11 deletions(-) diff --git a/X10D.Tests/src/Collections/ByteTests.cs b/X10D.Tests/src/Collections/ByteTests.cs index d73ab14..088fa00 100644 --- a/X10D.Tests/src/Collections/ByteTests.cs +++ b/X10D.Tests/src/Collections/ByteTests.cs @@ -55,7 +55,7 @@ public class ByteTests Assert.Multiple(() => { Span bits = stackalloc bool[8]; - value.Unpack(bits); + value.UnpackInternal_Fallback(bits); Assert.That(bits[0], Is.False); Assert.That(bits[1], Is.False); diff --git a/X10D.Tests/src/Drawing/CircleFTests.cs b/X10D.Tests/src/Drawing/CircleFTests.cs index 67221e9..fad7e5c 100644 --- a/X10D.Tests/src/Drawing/CircleFTests.cs +++ b/X10D.Tests/src/Drawing/CircleFTests.cs @@ -97,6 +97,9 @@ public class CircleFTests { Assert.That(CircleF.Empty, Is.Not.EqualTo(CircleF.Unit)); Assert.That(CircleF.Unit, Is.Not.EqualTo(CircleF.Empty)); + + Assert.That(CircleF.Empty != CircleF.Unit); + Assert.That(CircleF.Unit != CircleF.Empty); }); } @@ -104,6 +107,7 @@ public class CircleFTests public void Equals_ShouldBeFalse_GivenDifferentObjects() { Assert.That(CircleF.Empty, Is.Not.EqualTo(null)); + Assert.That(CircleF.Empty.Equals(null), Is.False); } [Test] @@ -131,6 +135,7 @@ public class CircleFTests Assert.Multiple(() => { Assert.That(converted, Is.EqualTo((Circle)unitCircle)); + Assert.That(converted == (Circle)unitCircle); Assert.That(converted.Radius, Is.EqualTo(unitCircle.Radius)); Assert.That((PointF)converted.Center, Is.EqualTo(unitCircle.Center)); }); @@ -141,6 +146,9 @@ public class CircleFTests { Assert.That(CircleF.Unit, Is.GreaterThan(CircleF.Empty)); Assert.That(CircleF.Unit, Is.GreaterThanOrEqualTo(CircleF.Empty)); + + Assert.That(CircleF.Unit > CircleF.Empty); + Assert.That(CircleF.Unit >= CircleF.Empty); } [Test] @@ -152,6 +160,7 @@ public class CircleFTests Assert.Multiple(() => { Assert.That(converted, Is.EqualTo((CircleF)unitCircle)); + Assert.That(converted == unitCircle); Assert.That(converted.Radius, Is.EqualTo(unitCircle.Radius)); Assert.That(converted.Center, Is.EqualTo((PointF)unitCircle.Center)); }); @@ -164,6 +173,9 @@ public class CircleFTests { Assert.That(CircleF.Empty, Is.LessThan(CircleF.Unit)); Assert.That(CircleF.Empty, Is.LessThanOrEqualTo(CircleF.Unit)); + + Assert.That(CircleF.Empty < CircleF.Unit); + Assert.That(CircleF.Empty <= CircleF.Unit); }); } diff --git a/X10D.Tests/src/Drawing/CircleTests.cs b/X10D.Tests/src/Drawing/CircleTests.cs index 3fbfc46..8ab4d18 100644 --- a/X10D.Tests/src/Drawing/CircleTests.cs +++ b/X10D.Tests/src/Drawing/CircleTests.cs @@ -94,6 +94,9 @@ public class CircleTests { Assert.That(Circle.Empty, Is.Not.EqualTo(Circle.Unit)); Assert.That(Circle.Unit, Is.Not.EqualTo(Circle.Empty)); + + Assert.That(Circle.Empty != Circle.Unit); + Assert.That(Circle.Unit != Circle.Empty); }); } @@ -101,6 +104,7 @@ public class CircleTests public void Equals_ShouldBeFalse_GivenDifferentObjects() { Assert.That(Circle.Empty, Is.Not.EqualTo(null)); + Assert.That(Circle.Empty.Equals(null), Is.False); } [Test] @@ -122,15 +126,25 @@ public class CircleTests [Test] public void op_GreaterThan_True_GivenUnitAndEmptyCircle() { - Assert.That(Circle.Unit, Is.GreaterThan(Circle.Empty)); - Assert.That(Circle.Unit, Is.GreaterThanOrEqualTo(Circle.Empty)); + Assert.Multiple(() => + { + Assert.That(Circle.Unit, Is.GreaterThan(Circle.Empty)); + Assert.That(Circle.Unit, Is.GreaterThanOrEqualTo(Circle.Empty)); + Assert.That(Circle.Unit > Circle.Empty); + Assert.That(Circle.Unit >= Circle.Empty); + }); } [Test] public void op_LessThan_True_GivenEmptyAndUnitCircle() { - Assert.That(Circle.Empty, Is.LessThan(Circle.Unit)); - Assert.That(Circle.Empty, Is.LessThanOrEqualTo(Circle.Unit)); + Assert.Multiple(() => + { + Assert.That(Circle.Empty, Is.LessThan(Circle.Unit)); + Assert.That(Circle.Empty, Is.LessThanOrEqualTo(Circle.Unit)); + Assert.That(Circle.Empty < Circle.Unit); + Assert.That(Circle.Empty <= Circle.Unit); + }); } [Test] diff --git a/X10D.Tests/src/Drawing/CuboidTests.cs b/X10D.Tests/src/Drawing/CuboidTests.cs index c687dcb..f2eafdc 100644 --- a/X10D.Tests/src/Drawing/CuboidTests.cs +++ b/X10D.Tests/src/Drawing/CuboidTests.cs @@ -29,12 +29,15 @@ public class CuboidTests var cube2 = Cuboid.Cube; Assert.That(cube1, Is.EqualTo(cube2)); Assert.That(cube2, Is.EqualTo(cube1)); + Assert.That(cube1 == cube2); + Assert.That(cube2 == cube1); } [Test] public void Equals_ShouldBeFalse_GivenDifferentCubes() { Assert.That(Cuboid.Empty, Is.Not.EqualTo(Cuboid.Cube)); + Assert.That(Cuboid.Empty != Cuboid.Cube); } [Test] diff --git a/X10D.Tests/src/Drawing/EllipseFTests.cs b/X10D.Tests/src/Drawing/EllipseFTests.cs index a7fdd03..7ca40aa 100644 --- a/X10D.Tests/src/Drawing/EllipseFTests.cs +++ b/X10D.Tests/src/Drawing/EllipseFTests.cs @@ -49,18 +49,22 @@ public class EllipseFTests var unitEllipse2 = EllipseF.Unit; Assert.That(unitEllipse2, Is.EqualTo(unitEllipse1)); Assert.That(unitEllipse1, Is.EqualTo(unitEllipse2)); + Assert.That(unitEllipse2 == unitEllipse1); + Assert.That(unitEllipse1 == unitEllipse2); } [Test] public void Equals_ShouldBeFalse_GivenDifferentEllipses() { Assert.That(EllipseF.Empty, Is.Not.EqualTo(EllipseF.Unit)); + Assert.That(EllipseF.Empty != EllipseF.Unit); } [Test] public void Equals_ShouldBeFalse_GivenDifferentObjects() { Assert.That(EllipseF.Unit, Is.Not.EqualTo(null)); + Assert.That(EllipseF.Unit.Equals(null), Is.False); } [Test] @@ -100,6 +104,7 @@ public class EllipseFTests Assert.Multiple(() => { Assert.That(converted, Is.EqualTo((Ellipse)unitEllipse)); + Assert.That(converted == unitEllipse); Assert.That(converted.HorizontalRadius, Is.EqualTo(unitEllipse.HorizontalRadius)); Assert.That(converted.VerticalRadius, Is.EqualTo(unitEllipse.VerticalRadius)); Assert.That((PointF)converted.Center, Is.EqualTo(unitEllipse.Center)); @@ -115,6 +120,7 @@ public class EllipseFTests Assert.Multiple(() => { Assert.That(converted, Is.EqualTo((EllipseF)unitCircle)); + Assert.That(converted == unitCircle); Assert.That(converted.HorizontalRadius, Is.EqualTo(unitCircle.Radius)); Assert.That(converted.VerticalRadius, Is.EqualTo(unitCircle.Radius)); Assert.That(converted.Center, Is.EqualTo((PointF)unitCircle.Center)); diff --git a/X10D.Tests/src/Drawing/EllipseTests.cs b/X10D.Tests/src/Drawing/EllipseTests.cs index b740d28..529f1c6 100644 --- a/X10D.Tests/src/Drawing/EllipseTests.cs +++ b/X10D.Tests/src/Drawing/EllipseTests.cs @@ -48,6 +48,8 @@ public class EllipseTests { Assert.That(unitEllipse2, Is.EqualTo(unitEllipse1)); Assert.That(unitEllipse1, Is.EqualTo(unitEllipse2)); + Assert.That(unitEllipse2 == unitEllipse1); + Assert.That(unitEllipse1 == unitEllipse2); }); } @@ -58,6 +60,8 @@ public class EllipseTests { Assert.That(Ellipse.Empty, Is.Not.EqualTo(Ellipse.Unit)); Assert.That(Ellipse.Unit, Is.Not.EqualTo(Ellipse.Empty)); + Assert.That(Ellipse.Empty != Ellipse.Unit); + Assert.That(Ellipse.Unit != Ellipse.Empty); }); } diff --git a/X10D.Tests/src/Drawing/Line3DTests.cs b/X10D.Tests/src/Drawing/Line3DTests.cs index f001b00..f7db299 100644 --- a/X10D.Tests/src/Drawing/Line3DTests.cs +++ b/X10D.Tests/src/Drawing/Line3DTests.cs @@ -76,18 +76,21 @@ public class Line3DTests Line3D second = Line3D.One; Assert.That(second, Is.EqualTo(first)); + Assert.That(second == first); } [Test] public void Equals_ShouldBeFalse_GivenDifferentLines() { Assert.That(Line3D.Empty, Is.Not.EqualTo(Line3D.One)); + Assert.That(Line3D.Empty != Line3D.One); } [Test] public void Equals_ShouldBeFalse_GivenDifferentObjects() { Assert.That(Line3D.One, Is.Not.EqualTo(null)); + Assert.That(Line3D.One.Equals(null), Is.False); } [Test] @@ -145,6 +148,9 @@ public class Line3DTests { Assert.That(Line3D.One, Is.GreaterThan(Line3D.Empty)); Assert.That(Line3D.One, Is.GreaterThanOrEqualTo(Line3D.Empty)); + + Assert.That(Line3D.One > Line3D.Empty); + Assert.That(Line3D.One >= Line3D.Empty); } [Test] @@ -177,6 +183,7 @@ public class Line3DTests Assert.Multiple(() => { Assert.That(converted, Is.EqualTo((Line3D)oneLine)); + Assert.That(converted == oneLine); Assert.That(converted.Length, Is.EqualTo(oneLine.Length)); Assert.That(converted.Start, Is.EqualTo(expectedStart)); Assert.That(converted.End, Is.EqualTo(expectedEnd)); @@ -188,5 +195,7 @@ public class Line3DTests { Assert.That(Line3D.Empty, Is.LessThan(Line3D.One)); Assert.That(Line3D.Empty, Is.LessThanOrEqualTo(Line3D.One)); + Assert.That(Line3D.Empty < Line3D.One); + Assert.That(Line3D.Empty <= Line3D.One); } } diff --git a/X10D.Tests/src/Drawing/LineFTests.cs b/X10D.Tests/src/Drawing/LineFTests.cs index 3f59938..2c53cd4 100644 --- a/X10D.Tests/src/Drawing/LineFTests.cs +++ b/X10D.Tests/src/Drawing/LineFTests.cs @@ -71,6 +71,8 @@ public class LineFTests { Assert.That(second, Is.EqualTo(first)); Assert.That(first, Is.EqualTo(second)); + Assert.That(second == first); + Assert.That(first == second); }); } @@ -81,6 +83,8 @@ public class LineFTests { Assert.That(LineF.Empty, Is.Not.EqualTo(LineF.One)); Assert.That(LineF.One, Is.Not.EqualTo(LineF.Empty)); + Assert.That(LineF.Empty != LineF.One); + Assert.That(LineF.One != LineF.Empty); }); } @@ -88,6 +92,7 @@ public class LineFTests public void Equals_ShouldBeFalse_GivenDifferentObjects() { Assert.That(LineF.One, Is.Not.EqualTo(null)); + Assert.That(LineF.One.Equals(null), Is.False); } [Test] @@ -115,6 +120,7 @@ public class LineFTests Assert.Multiple(() => { Assert.That(converted, Is.EqualTo((Line)oneLine)); + Assert.That(converted == oneLine); Assert.That(converted.Length, Is.EqualTo(oneLine.Length)); Assert.That((PointF)converted.Start, Is.EqualTo(oneLine.Start)); Assert.That((PointF)converted.End, Is.EqualTo(oneLine.End)); @@ -126,6 +132,8 @@ public class LineFTests { Assert.That(LineF.One, Is.GreaterThan(LineF.Empty)); Assert.That(LineF.One, Is.GreaterThanOrEqualTo(LineF.Empty)); + Assert.That(LineF.One > LineF.Empty); + Assert.That(LineF.One >= LineF.Empty); } [Test] @@ -137,6 +145,7 @@ public class LineFTests Assert.Multiple(() => { Assert.That(converted, Is.EqualTo((LineF)oneLine)); + Assert.That(converted == oneLine); Assert.That(converted.Length, Is.EqualTo(oneLine.Length)); Assert.That(converted.Start, Is.EqualTo((PointF)oneLine.Start)); Assert.That(converted.End, Is.EqualTo((PointF)oneLine.End)); @@ -148,5 +157,7 @@ public class LineFTests { Assert.That(LineF.Empty, Is.LessThan(LineF.One)); Assert.That(LineF.Empty, Is.LessThanOrEqualTo(LineF.One)); + Assert.That(LineF.Empty < LineF.One); + Assert.That(LineF.Empty <= LineF.One); } } diff --git a/X10D.Tests/src/Drawing/LineTests.cs b/X10D.Tests/src/Drawing/LineTests.cs index 8fba47f..dfca225 100644 --- a/X10D.Tests/src/Drawing/LineTests.cs +++ b/X10D.Tests/src/Drawing/LineTests.cs @@ -53,6 +53,8 @@ public class LineTests { Assert.That(second, Is.EqualTo(first)); Assert.That(first, Is.EqualTo(second)); + Assert.That(second == first); + Assert.That(first == second); }); } @@ -63,6 +65,8 @@ public class LineTests { Assert.That(Line.Empty, Is.Not.EqualTo(Line.One)); Assert.That(Line.One, Is.Not.EqualTo(Line.Empty)); + Assert.That(Line.Empty != Line.One); + Assert.That(Line.One != Line.Empty); }); } @@ -70,6 +74,7 @@ public class LineTests public void Equals_ShouldBeFalse_GivenDifferentObjects() { Assert.That(Line.One, Is.Not.EqualTo(null)); + Assert.That(Line.One.Equals(null), Is.False); } [Test] @@ -111,6 +116,8 @@ public class LineTests { Assert.That(Line.One, Is.GreaterThan(Line.Empty)); Assert.That(Line.One, Is.GreaterThanOrEqualTo(Line.Empty)); + Assert.That(Line.One > Line.Empty); + Assert.That(Line.One >= Line.Empty); } [Test] @@ -118,5 +125,7 @@ public class LineTests { Assert.That(Line.Empty, Is.LessThan(Line.One)); Assert.That(Line.Empty, Is.LessThanOrEqualTo(Line.One)); + Assert.That(Line.Empty < Line.One); + Assert.That(Line.Empty <= Line.One); } } diff --git a/X10D.Tests/src/Drawing/PolygonFTests.cs b/X10D.Tests/src/Drawing/PolygonFTests.cs index 196b88c..9b7e626 100644 --- a/X10D.Tests/src/Drawing/PolygonFTests.cs +++ b/X10D.Tests/src/Drawing/PolygonFTests.cs @@ -108,6 +108,8 @@ public class PolygonFTests { Assert.That(second, Is.EqualTo(first)); Assert.That(first, Is.EqualTo(second)); + Assert.That(second == first); + Assert.That(first == second); }); } @@ -121,6 +123,8 @@ public class PolygonFTests { Assert.That(second, Is.EqualTo(first)); Assert.That(first, Is.EqualTo(second)); + Assert.That(second == first); + Assert.That(first == second); }); } @@ -134,6 +138,8 @@ public class PolygonFTests { Assert.That(second, Is.Not.EqualTo(first)); Assert.That(first, Is.Not.EqualTo(second)); + Assert.That(second != first); + Assert.That(first != second); }); } @@ -185,6 +191,7 @@ public class PolygonFTests Assert.Multiple(() => { Assert.That(converted, Is.EqualTo((PolygonF)polygon)); + Assert.That(converted == polygon); Assert.That(converted.IsConvex, Is.EqualTo(polygon.IsConvex)); Assert.That(converted.VertexCount, Is.EqualTo(polygon.VertexCount)); CollectionAssert.AreEqual(converted.Vertices, polygon.Vertices.Select(p => (PointF)p)); diff --git a/X10D.Tests/src/Drawing/PolygonTests.cs b/X10D.Tests/src/Drawing/PolygonTests.cs index 9d36dde..40e9da4 100644 --- a/X10D.Tests/src/Drawing/PolygonTests.cs +++ b/X10D.Tests/src/Drawing/PolygonTests.cs @@ -52,7 +52,7 @@ public class PolygonTests public void Constructor_ShouldThrowArgumentNullException_GivenNullEnumerableOfPoint() { IEnumerable vertices = null!; - Assert.Throws(() => new Polygon(vertices)); + Assert.Throws(() => _ = new Polygon(vertices)); } [Test] @@ -77,7 +77,7 @@ public class PolygonTests public void CopyConstructor_ShouldThrowArgumentNullException_GivenNullPolygon() { Polygon polygon = null!; - Assert.Throws(() => new Polygon(polygon)); + Assert.Throws(() => _ = new Polygon(polygon)); } [Test] @@ -90,6 +90,8 @@ public class PolygonTests { Assert.That(second, Is.EqualTo(first)); Assert.That(first, Is.EqualTo(second)); + Assert.That(second == first); + Assert.That(first == second); }); } @@ -103,6 +105,8 @@ public class PolygonTests { Assert.That(second, Is.EqualTo(first)); Assert.That(first, Is.EqualTo(second)); + Assert.That(second == first); + Assert.That(first == second); }); } @@ -116,6 +120,8 @@ public class PolygonTests { Assert.That(second, Is.Not.EqualTo(first)); Assert.That(first, Is.Not.EqualTo(second)); + Assert.That(second != first); + Assert.That(first != second); }); } diff --git a/X10D.Tests/src/Drawing/PolyhedronTests.cs b/X10D.Tests/src/Drawing/PolyhedronTests.cs index 78b50e4..608e7e1 100644 --- a/X10D.Tests/src/Drawing/PolyhedronTests.cs +++ b/X10D.Tests/src/Drawing/PolyhedronTests.cs @@ -105,6 +105,8 @@ public class PolyhedronTests { Assert.That(second, Is.EqualTo(first)); Assert.That(first, Is.EqualTo(second)); + Assert.That(second == first); + Assert.That(first == second); }); } @@ -118,6 +120,8 @@ public class PolyhedronTests { Assert.That(second, Is.Not.EqualTo(first)); Assert.That(first, Is.Not.EqualTo(second)); + Assert.That(second != first); + Assert.That(first != second); }); } diff --git a/X10D.Tests/src/Drawing/SphereTests.cs b/X10D.Tests/src/Drawing/SphereTests.cs index 90a4afa..2a61a8b 100644 --- a/X10D.Tests/src/Drawing/SphereTests.cs +++ b/X10D.Tests/src/Drawing/SphereTests.cs @@ -66,6 +66,8 @@ public class SphereTests { Assert.That(unitCircle2, Is.EqualTo(unitCircle1)); Assert.That(unitCircle1, Is.EqualTo(unitCircle2)); + Assert.That(unitCircle2 == unitCircle1); + Assert.That(unitCircle1 == unitCircle2); }); } @@ -73,6 +75,7 @@ public class SphereTests public void Equals_ShouldBeFalse_GivenDifferentObjects() { Assert.That(Sphere.Unit, Is.Not.EqualTo(null)); + Assert.That(Sphere.Unit.Equals(null), Is.False); } [Test] @@ -80,6 +83,8 @@ public class SphereTests { Assert.That(Sphere.Empty, Is.Not.EqualTo(Sphere.Unit)); Assert.That(Sphere.Unit, Is.Not.EqualTo(Sphere.Empty)); + Assert.That(Sphere.Empty != Sphere.Unit); + Assert.That(Sphere.Unit != Sphere.Empty); } [Test] @@ -103,6 +108,8 @@ public class SphereTests { Assert.That(Sphere.Unit, Is.GreaterThan(Sphere.Empty)); Assert.That(Sphere.Unit, Is.GreaterThanOrEqualTo(Sphere.Empty)); + Assert.That(Sphere.Unit > Sphere.Empty); + Assert.That(Sphere.Unit >= Sphere.Empty); } [Test] @@ -110,6 +117,8 @@ public class SphereTests { Assert.That(Sphere.Empty, Is.LessThan(Sphere.Unit)); Assert.That(Sphere.Empty, Is.LessThanOrEqualTo(Sphere.Unit)); + Assert.That(Sphere.Empty < Sphere.Unit); + Assert.That(Sphere.Empty <= Sphere.Unit); } [Test] diff --git a/X10D.Tests/src/Reflection/MemberInfoTests.cs b/X10D.Tests/src/Reflection/MemberInfoTests.cs index 5f6e2cb..edc2ebf 100644 --- a/X10D.Tests/src/Reflection/MemberInfoTests.cs +++ b/X10D.Tests/src/Reflection/MemberInfoTests.cs @@ -59,10 +59,10 @@ public class MemberInfoTests Func predicate = attribute => attribute.IsCompliant; Assert.Multiple(() => { - Assert.That(typeof(byte).SelectFromCustomAttribute(predicate)); - Assert.That(typeof(short).SelectFromCustomAttribute(predicate)); - Assert.That(typeof(int).SelectFromCustomAttribute(predicate)); - Assert.That(typeof(long).SelectFromCustomAttribute(predicate)); + Assert.That(typeof(byte).SelectFromCustomAttribute(predicate, true)); + Assert.That(typeof(short).SelectFromCustomAttribute(predicate, true)); + Assert.That(typeof(int).SelectFromCustomAttribute(predicate, true)); + Assert.That(typeof(long).SelectFromCustomAttribute(predicate, true)); }); } From 8e6796607c3ed2e6b57ae4522e8bedde4b58f2d3 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Wed, 5 Apr 2023 23:19:08 +0100 Subject: [PATCH 011/102] docs: explain use of ref return --- X10D/src/Collections/DictionaryExtensions.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/X10D/src/Collections/DictionaryExtensions.cs b/X10D/src/Collections/DictionaryExtensions.cs index 493088b..66823b0 100644 --- a/X10D/src/Collections/DictionaryExtensions.cs +++ b/X10D/src/Collections/DictionaryExtensions.cs @@ -54,6 +54,8 @@ public static class DictionaryExtensions #if NET6_0_OR_GREATER ref var value = ref CollectionsMarshal.GetValueRefOrAddDefault(dictionary, key, out bool exists); + // DO NOT CHANGE. reassigning value is necessary to mutate the dictionary, due to ref return above. + // mutation of the dictionary is INTENDED BEHAVIOUR. this is not a mistake. return value = exists ? updateValueFactory(key, value!) : addValue; #else if (dictionary.TryGetValue(key, out TValue? old)) @@ -173,6 +175,8 @@ public static class DictionaryExtensions #if NET6_0_OR_GREATER ref TValue? value = ref CollectionsMarshal.GetValueRefOrAddDefault(dictionary, key, out bool exists); + // DO NOT CHANGE. reassigning value is necessary to mutate the dictionary, due to ref return above. + // mutation of the dictionary is INTENDED BEHAVIOUR. this is not a mistake. return value = exists ? updateValueFactory(key, value!) : addValueFactory(key); #else if (dictionary.TryGetValue(key, out TValue? old)) @@ -310,6 +314,8 @@ public static class DictionaryExtensions #if NET6_0_OR_GREATER ref TValue? value = ref CollectionsMarshal.GetValueRefOrAddDefault(dictionary, key, out bool exists); + // DO NOT CHANGE. reassigning value is necessary to mutate the dictionary, due to ref return above. + // mutation of the dictionary is INTENDED BEHAVIOUR. this is not a mistake. return value = exists ? updateValueFactory(key, value!, factoryArgument) : addValueFactory(key, factoryArgument); #else if (dictionary.TryGetValue(key, out TValue? old)) From bafc327ee667870f2d7bfeb94e797fef34bc967a Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Thu, 6 Apr 2023 02:30:17 +0100 Subject: [PATCH 012/102] chore: add benchmarks project --- X10D.sln | 7 +++++++ tools/Benchmarks/Benchmarks.csproj | 23 +++++++++++++++++++++++ tools/Benchmarks/Program.cs | 4 ++++ 3 files changed, 34 insertions(+) create mode 100644 tools/Benchmarks/Benchmarks.csproj create mode 100644 tools/Benchmarks/Program.cs diff --git a/X10D.sln b/X10D.sln index 6f8cb0c..1d8368a 100644 --- a/X10D.sln +++ b/X10D.sln @@ -45,6 +45,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UpmPackageGenerator", "tool EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tools", "Tools", "{4B8969E6-27D2-4357-964E-9979FF7CC805}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Benchmarks", "tools\Benchmarks\Benchmarks.csproj", "{259450A0-9964-403A-91E1-E9111B92C293}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -83,6 +85,10 @@ Global {CCBF047D-1B01-45EC-8D89-B00B4AC482CA}.Debug|Any CPU.Build.0 = Debug|Any CPU {CCBF047D-1B01-45EC-8D89-B00B4AC482CA}.Release|Any CPU.ActiveCfg = Release|Any CPU {CCBF047D-1B01-45EC-8D89-B00B4AC482CA}.Release|Any CPU.Build.0 = Release|Any CPU + {259450A0-9964-403A-91E1-E9111B92C293}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {259450A0-9964-403A-91E1-E9111B92C293}.Debug|Any CPU.Build.0 = Debug|Any CPU + {259450A0-9964-403A-91E1-E9111B92C293}.Release|Any CPU.ActiveCfg = Release|Any CPU + {259450A0-9964-403A-91E1-E9111B92C293}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -93,5 +99,6 @@ Global GlobalSection(NestedProjects) = preSolution {84750149-9068-4780-AFDE-CDA1AC57007D} = {4B8969E6-27D2-4357-964E-9979FF7CC805} {CCBF047D-1B01-45EC-8D89-B00B4AC482CA} = {4B8969E6-27D2-4357-964E-9979FF7CC805} + {259450A0-9964-403A-91E1-E9111B92C293} = {4B8969E6-27D2-4357-964E-9979FF7CC805} EndGlobalSection EndGlobal diff --git a/tools/Benchmarks/Benchmarks.csproj b/tools/Benchmarks/Benchmarks.csproj new file mode 100644 index 0000000..e5b1c6e --- /dev/null +++ b/tools/Benchmarks/Benchmarks.csproj @@ -0,0 +1,23 @@ + + + + Release + Exe + net7.0;net6.0;netcoreapp3.1 + 11.0 + enable + enable + true + true + true + + + + + + + + + + + diff --git a/tools/Benchmarks/Program.cs b/tools/Benchmarks/Program.cs new file mode 100644 index 0000000..d25b2b7 --- /dev/null +++ b/tools/Benchmarks/Program.cs @@ -0,0 +1,4 @@ +using System.Reflection; +using BenchmarkDotNet.Running; + +BenchmarkRunner.Run(Assembly.GetExecutingAssembly()); From 0621c246a0db7e8ac07a8c4fad31ff2fbeff3163 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Thu, 6 Apr 2023 02:31:22 +0100 Subject: [PATCH 013/102] feat: add Span.Replace --- CHANGELOG.md | 1 + X10D.Tests/src/Collections/SpanTest.cs | 24 +++++++++++++++++++++++ X10D/src/Collections/SpanExtensions.cs | 27 +++++++++++++++++++++++++- 3 files changed, 51 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c978814..a0fcace 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - X10D: Added extension methods for `DateOnly`, for parity with `DateTime` and `DateTimeOffset`. - X10D: Added math-related extension methods for `BigInteger`. +- X10D: Added `Span.Replace(T, T)`. ### Changed - X10D: `DateTime.Age(DateTime)` and `DateTimeOffset.Age(DateTimeOffset)` parameter renamed from `asOf` to `referenceDate`. diff --git a/X10D.Tests/src/Collections/SpanTest.cs b/X10D.Tests/src/Collections/SpanTest.cs index 5df5acd..0c59d1c 100644 --- a/X10D.Tests/src/Collections/SpanTest.cs +++ b/X10D.Tests/src/Collections/SpanTest.cs @@ -46,6 +46,30 @@ public class SpanTest Assert.That(count, Is.EqualTo(8)); } + [Test] + public void Replace_ShouldReplaceAllElements_GivenSpanOfInt32() + { + Span span = stackalloc int[16] {1, 2, 3, 2, 5, 2, 7, 2, 9, 2, 11, 2, 13, 2, 15, 2}; + span.Replace(2, 4); + Assert.That(span.ToArray(), Is.EqualTo(new[] {1, 4, 3, 4, 5, 4, 7, 4, 9, 4, 11, 4, 13, 4, 15, 4})); + } + + [Test] + public void Replace_ShouldReplaceAllElements_GivenSpanOfChar() + { + Span chars = stackalloc char[12] {'H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!'}; + chars.Replace('l', 'w'); + CollectionAssert.AreEqual(chars.ToArray(), "Hewwo worwd!".ToCharArray()); + } + + [Test] + public void Replace_ShouldDoNothing_GivenSpanWithNoMatchingElements() + { + Span span = stackalloc int[16] {1, 2, 3, 2, 5, 2, 7, 2, 9, 2, 11, 2, 13, 2, 15, 2}; + span.Replace(4, 8); + Assert.That(span.ToArray(), Is.EqualTo(new[] {1, 2, 3, 2, 5, 2, 7, 2, 9, 2, 11, 2, 13, 2, 15, 2})); + } + [Test] public void Split_OnEmptySpan_ShouldYieldNothing_UsingCharDelimiter_GivenReadOnlySpan() { diff --git a/X10D/src/Collections/SpanExtensions.cs b/X10D/src/Collections/SpanExtensions.cs index 78d6c8b..1aee61d 100644 --- a/X10D/src/Collections/SpanExtensions.cs +++ b/X10D/src/Collections/SpanExtensions.cs @@ -1,4 +1,9 @@ -namespace X10D.Collections; +#if NET5_0_OR_GREATER +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +#endif + +namespace X10D.Collections; /// /// Extension methods for and @@ -53,6 +58,26 @@ public static class SpanExtensions return source; } + /// + /// Replaces all occurrences of a specified element in a span of elements with another specified element. + /// + /// The source span. + /// The element to replace. + /// The replacement element. + /// The type of elements in . + public static void Replace(this Span haystack, T needle, T replacement) where T : struct + { + var comparer = EqualityComparer.Default; + + for (var index = 0; index < haystack.Length; index++) + { + if (comparer.Equals(haystack[index], needle)) + { + haystack[index] = replacement; + } + } + } + /// /// Splits a span of elements into sub-spans based on a delimiting element. /// From 9791fd23bb201c3a246834cb0db9682d5a6a5c53 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Thu, 6 Apr 2023 14:40:27 +0100 Subject: [PATCH 014/102] feat: add CountDigit for integer types --- CHANGELOG.md | 1 + X10D.Tests/src/Math/BigIntegerTests.cs | 55 ++++++++++++++++++++++++++ X10D.Tests/src/Math/ByteTests.cs | 44 +++++++++++++++++++++ X10D.Tests/src/Math/Int16Tests.cs | 55 ++++++++++++++++++++++++++ X10D.Tests/src/Math/Int32Tests.cs | 55 ++++++++++++++++++++++++++ X10D.Tests/src/Math/Int64Tests.cs | 55 ++++++++++++++++++++++++++ X10D.Tests/src/Math/SByteTests.cs | 55 ++++++++++++++++++++++++++ X10D.Tests/src/Math/UInt16Tests.cs | 44 +++++++++++++++++++++ X10D.Tests/src/Math/UInt32Tests.cs | 43 ++++++++++++++++++++ X10D.Tests/src/Math/UInt64Tests.cs | 44 +++++++++++++++++++++ X10D/src/Math/BigIntegerExtensions.cs | 15 +++++++ X10D/src/Math/ByteExtensions.cs | 15 +++++++ X10D/src/Math/Int16Extensions.cs | 15 +++++++ X10D/src/Math/Int32Extensions.cs | 15 +++++++ X10D/src/Math/Int64Extensions.cs | 15 +++++++ X10D/src/Math/SByteExtensions.cs | 15 +++++++ X10D/src/Math/UInt16Extensions.cs | 15 +++++++ X10D/src/Math/UInt32Extensions.cs | 15 +++++++ X10D/src/Math/UInt64Extensions.cs | 15 +++++++ 19 files changed, 586 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index a0fcace..e7daff2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - X10D: Added extension methods for `DateOnly`, for parity with `DateTime` and `DateTimeOffset`. - X10D: Added math-related extension methods for `BigInteger`. - X10D: Added `Span.Replace(T, T)`. +- X10D: Added `CountDigits` for integer types. ### Changed - X10D: `DateTime.Age(DateTime)` and `DateTimeOffset.Age(DateTimeOffset)` parameter renamed from `asOf` to `referenceDate`. diff --git a/X10D.Tests/src/Math/BigIntegerTests.cs b/X10D.Tests/src/Math/BigIntegerTests.cs index bbe3b09..2151798 100644 --- a/X10D.Tests/src/Math/BigIntegerTests.cs +++ b/X10D.Tests/src/Math/BigIntegerTests.cs @@ -7,6 +7,61 @@ namespace X10D.Tests.Math; [TestFixture] public partial class BigIntegerTests { + [Test] + public void CountDigits_ShouldReturn1_Given0() + { + BigInteger value = 0; + const int expected = 1; + + int result = value.CountDigits(); + + Assert.That(result, Is.EqualTo(expected)); + } + + [Test] + public void CountDigits_ShouldReturn1_Given1() + { + BigInteger value = 1; + const int expected = 1; + + int result = value.CountDigits(); + + Assert.That(result, Is.EqualTo(expected)); + } + + [Test] + public void CountDigits_ShouldReturn1_GivenNegative1() + { + BigInteger value = -1; + const int expected = 1; + + int result = value.CountDigits(); + + Assert.That(result, Is.EqualTo(expected)); + } + + [Test] + public void CountDigits_ShouldReturn2_Given10() + { + BigInteger value = 10; + const int expected = 2; + + int result = value.CountDigits(); + + Assert.That(result, Is.EqualTo(expected)); + } + + [Test] + public void CountDigits_ShouldReturn3_Given199() + { + BigInteger value = 199; + const int expected = 3; + + int result = value.CountDigits(); + + Assert.That(result, Is.EqualTo(expected)); + } + [Test] public void DigitalRootShouldBeCorrect() { diff --git a/X10D.Tests/src/Math/ByteTests.cs b/X10D.Tests/src/Math/ByteTests.cs index e139eb1..3419f3e 100644 --- a/X10D.Tests/src/Math/ByteTests.cs +++ b/X10D.Tests/src/Math/ByteTests.cs @@ -6,6 +6,50 @@ namespace X10D.Tests.Math; [TestFixture] public partial class ByteTests { + [Test] + public void CountDigits_ShouldReturn1_Given0() + { + const byte value = 0; + const int expected = 1; + + int result = value.CountDigits(); + + Assert.That(result, Is.EqualTo(expected)); + } + + [Test] + public void CountDigits_ShouldReturn1_Given1() + { + const byte value = 1; + const int expected = 1; + + int result = value.CountDigits(); + + Assert.That(result, Is.EqualTo(expected)); + } + + [Test] + public void CountDigits_ShouldReturn2_Given10() + { + const byte value = 10; + const int expected = 2; + + int result = value.CountDigits(); + + Assert.That(result, Is.EqualTo(expected)); + } + + [Test] + public void CountDigits_ShouldReturn3_Given199() + { + const byte value = 199; + const int expected = 3; + + int result = value.CountDigits(); + + Assert.That(result, Is.EqualTo(expected)); + } + [Test] public void DigitalRootShouldBeCorrect() { diff --git a/X10D.Tests/src/Math/Int16Tests.cs b/X10D.Tests/src/Math/Int16Tests.cs index 50591cc..3823264 100644 --- a/X10D.Tests/src/Math/Int16Tests.cs +++ b/X10D.Tests/src/Math/Int16Tests.cs @@ -6,6 +6,61 @@ namespace X10D.Tests.Math; [TestFixture] public partial class Int16Tests { + [Test] + public void CountDigits_ShouldReturn1_Given0() + { + const short value = 0; + const int expected = 1; + + int result = value.CountDigits(); + + Assert.That(result, Is.EqualTo(expected)); + } + + [Test] + public void CountDigits_ShouldReturn1_Given1() + { + const short value = 1; + const int expected = 1; + + int result = value.CountDigits(); + + Assert.That(result, Is.EqualTo(expected)); + } + + [Test] + public void CountDigits_ShouldReturn1_GivenNegative1() + { + const short value = -1; + const int expected = 1; + + int result = value.CountDigits(); + + Assert.That(result, Is.EqualTo(expected)); + } + + [Test] + public void CountDigits_ShouldReturn2_Given10() + { + const short value = 10; + const int expected = 2; + + int result = value.CountDigits(); + + Assert.That(result, Is.EqualTo(expected)); + } + + [Test] + public void CountDigits_ShouldReturn3_Given199() + { + const short value = 199; + const int expected = 3; + + int result = value.CountDigits(); + + Assert.That(result, Is.EqualTo(expected)); + } + [Test] public void DigitalRootShouldBeCorrect() { diff --git a/X10D.Tests/src/Math/Int32Tests.cs b/X10D.Tests/src/Math/Int32Tests.cs index e412200..7711d3d 100644 --- a/X10D.Tests/src/Math/Int32Tests.cs +++ b/X10D.Tests/src/Math/Int32Tests.cs @@ -6,6 +6,61 @@ namespace X10D.Tests.Math; [TestFixture] public partial class Int32Tests { + [Test] + public void CountDigits_ShouldReturn1_Given0() + { + const int value = 0; + const int expected = 1; + + int result = value.CountDigits(); + + Assert.That(result, Is.EqualTo(expected)); + } + + [Test] + public void CountDigits_ShouldReturn1_Given1() + { + const int value = 1; + const int expected = 1; + + int result = value.CountDigits(); + + Assert.That(result, Is.EqualTo(expected)); + } + + [Test] + public void CountDigits_ShouldReturn1_GivenNegative1() + { + const int value = -1; + const int expected = 1; + + int result = value.CountDigits(); + + Assert.That(result, Is.EqualTo(expected)); + } + + [Test] + public void CountDigits_ShouldReturn2_Given10() + { + const int value = 10; + const int expected = 2; + + int result = value.CountDigits(); + + Assert.That(result, Is.EqualTo(expected)); + } + + [Test] + public void CountDigits_ShouldReturn3_Given199() + { + const int value = 199; + const int expected = 3; + + int result = value.CountDigits(); + + Assert.That(result, Is.EqualTo(expected)); + } + [Test] public void DigitalRootShouldBeCorrect() { diff --git a/X10D.Tests/src/Math/Int64Tests.cs b/X10D.Tests/src/Math/Int64Tests.cs index de56cd9..557e0b0 100644 --- a/X10D.Tests/src/Math/Int64Tests.cs +++ b/X10D.Tests/src/Math/Int64Tests.cs @@ -6,6 +6,61 @@ namespace X10D.Tests.Math; [TestFixture] public partial class Int64Tests { + [Test] + public void CountDigits_ShouldReturn1_Given0() + { + const long value = 0; + const int expected = 1; + + int result = value.CountDigits(); + + Assert.That(result, Is.EqualTo(expected)); + } + + [Test] + public void CountDigits_ShouldReturn1_Given1() + { + const long value = 1; + const int expected = 1; + + int result = value.CountDigits(); + + Assert.That(result, Is.EqualTo(expected)); + } + + [Test] + public void CountDigits_ShouldReturn1_GivenNegative1() + { + const long value = -1; + const int expected = 1; + + int result = value.CountDigits(); + + Assert.That(result, Is.EqualTo(expected)); + } + + [Test] + public void CountDigits_ShouldReturn2_Given10() + { + const long value = 10; + const int expected = 2; + + int result = value.CountDigits(); + + Assert.That(result, Is.EqualTo(expected)); + } + + [Test] + public void CountDigits_ShouldReturn3_Given199() + { + const long value = 199; + const int expected = 3; + + int result = value.CountDigits(); + + Assert.That(result, Is.EqualTo(expected)); + } + [Test] public void DigitalRootShouldBeCorrect() { diff --git a/X10D.Tests/src/Math/SByteTests.cs b/X10D.Tests/src/Math/SByteTests.cs index 703b1af..454e35f 100644 --- a/X10D.Tests/src/Math/SByteTests.cs +++ b/X10D.Tests/src/Math/SByteTests.cs @@ -7,6 +7,61 @@ namespace X10D.Tests.Math; [CLSCompliant(false)] public partial class SByteTests { + [Test] + public void CountDigits_ShouldReturn1_Given0() + { + const sbyte value = 0; + const int expected = 1; + + int result = value.CountDigits(); + + Assert.That(result, Is.EqualTo(expected)); + } + + [Test] + public void CountDigits_ShouldReturn1_Given1() + { + const sbyte value = 1; + const int expected = 1; + + int result = value.CountDigits(); + + Assert.That(result, Is.EqualTo(expected)); + } + + [Test] + public void CountDigits_ShouldReturn1_GivenNegative1() + { + const sbyte value = -1; + const int expected = 1; + + int result = value.CountDigits(); + + Assert.That(result, Is.EqualTo(expected)); + } + + [Test] + public void CountDigits_ShouldReturn2_Given10() + { + const sbyte value = 10; + const int expected = 2; + + int result = value.CountDigits(); + + Assert.That(result, Is.EqualTo(expected)); + } + + [Test] + public void CountDigits_ShouldReturn3_Given127() + { + const sbyte value = 127; + const int expected = 3; + + int result = value.CountDigits(); + + Assert.That(result, Is.EqualTo(expected)); + } + [Test] public void DigitalRootShouldBeCorrect() { diff --git a/X10D.Tests/src/Math/UInt16Tests.cs b/X10D.Tests/src/Math/UInt16Tests.cs index 7055a00..f123de7 100644 --- a/X10D.Tests/src/Math/UInt16Tests.cs +++ b/X10D.Tests/src/Math/UInt16Tests.cs @@ -7,6 +7,50 @@ namespace X10D.Tests.Math; [CLSCompliant(false)] public partial class UInt16Tests { + [Test] + public void CountDigits_ShouldReturn1_Given0() + { + const ushort value = 0; + const int expected = 1; + + int result = value.CountDigits(); + + Assert.That(result, Is.EqualTo(expected)); + } + + [Test] + public void CountDigits_ShouldReturn1_Given1() + { + const ushort value = 1; + const int expected = 1; + + int result = value.CountDigits(); + + Assert.That(result, Is.EqualTo(expected)); + } + + [Test] + public void CountDigits_ShouldReturn2_Given10() + { + const ushort value = 10; + const int expected = 2; + + int result = value.CountDigits(); + + Assert.That(result, Is.EqualTo(expected)); + } + + [Test] + public void CountDigits_ShouldReturn3_Given199() + { + const ushort value = 199; + const int expected = 3; + + int result = value.CountDigits(); + + Assert.That(result, Is.EqualTo(expected)); + } + [Test] public void DigitalRootShouldBeCorrect() { diff --git a/X10D.Tests/src/Math/UInt32Tests.cs b/X10D.Tests/src/Math/UInt32Tests.cs index b550667..a6c2911 100644 --- a/X10D.Tests/src/Math/UInt32Tests.cs +++ b/X10D.Tests/src/Math/UInt32Tests.cs @@ -7,6 +7,49 @@ namespace X10D.Tests.Math; [CLSCompliant(false)] public partial class UInt32Tests { + [Test] + public void CountDigits_ShouldReturn1_Given0() + { + const uint value = 0; + const int expected = 1; + + int result = value.CountDigits(); + + Assert.That(result, Is.EqualTo(expected)); + } + + [Test] + public void CountDigits_ShouldReturn1_Given1() + { + const uint value = 1; + const int expected = 1; + + int result = value.CountDigits(); + + Assert.That(result, Is.EqualTo(expected)); + } + [Test] + public void CountDigits_ShouldReturn2_Given10() + { + const uint value = 10; + const int expected = 2; + + int result = value.CountDigits(); + + Assert.That(result, Is.EqualTo(expected)); + } + + [Test] + public void CountDigits_ShouldReturn3_Given199() + { + const uint value = 199; + const int expected = 3; + + int result = value.CountDigits(); + + Assert.That(result, Is.EqualTo(expected)); + } + [Test] public void DigitalRootShouldBeCorrect() { diff --git a/X10D.Tests/src/Math/UInt64Tests.cs b/X10D.Tests/src/Math/UInt64Tests.cs index 777c5ab..6d05b4d 100644 --- a/X10D.Tests/src/Math/UInt64Tests.cs +++ b/X10D.Tests/src/Math/UInt64Tests.cs @@ -7,6 +7,50 @@ namespace X10D.Tests.Math; [CLSCompliant(false)] public partial class UInt64Tests { + [Test] + public void CountDigits_ShouldReturn1_Given0() + { + const ulong value = 0; + const int expected = 1; + + int result = value.CountDigits(); + + Assert.That(result, Is.EqualTo(expected)); + } + + [Test] + public void CountDigits_ShouldReturn1_Given1() + { + const ulong value = 1; + const int expected = 1; + + int result = value.CountDigits(); + + Assert.That(result, Is.EqualTo(expected)); + } + + [Test] + public void CountDigits_ShouldReturn2_Given10() + { + const ulong value = 10; + const int expected = 2; + + int result = value.CountDigits(); + + Assert.That(result, Is.EqualTo(expected)); + } + + [Test] + public void CountDigits_ShouldReturn3_Given199() + { + const ulong value = 199; + const int expected = 3; + + int result = value.CountDigits(); + + Assert.That(result, Is.EqualTo(expected)); + } + [Test] public void DigitalRootShouldBeCorrect() { diff --git a/X10D/src/Math/BigIntegerExtensions.cs b/X10D/src/Math/BigIntegerExtensions.cs index 4ce5a0d..31f3884 100644 --- a/X10D/src/Math/BigIntegerExtensions.cs +++ b/X10D/src/Math/BigIntegerExtensions.cs @@ -10,6 +10,21 @@ namespace X10D.Math; /// public static class BigIntegerExtensions { + /// + /// Returns the number of digits in the current integer. + /// + /// The value whose digit count to compute. + /// The number of digits in . + public static int CountDigits(this BigInteger value) + { + if (value == 0) + { + return 1; + } + + return (int)(1 + BigInteger.Log10(BigInteger.Abs(value))); + } + /// /// Computes the digital root of this 8-bit integer. /// diff --git a/X10D/src/Math/ByteExtensions.cs b/X10D/src/Math/ByteExtensions.cs index 6a7db33..bc5a121 100644 --- a/X10D/src/Math/ByteExtensions.cs +++ b/X10D/src/Math/ByteExtensions.cs @@ -9,6 +9,21 @@ namespace X10D.Math; /// public static class ByteExtensions { + /// + /// Returns the number of digits in the current 8-bit unsigned integer. + /// + /// The value whose digit count to compute. + /// The number of digits in . + public static int CountDigits(this byte value) + { + if (value == 0) + { + return 1; + } + + return ((ulong)value).CountDigits(); + } + /// /// Computes the digital root of this 8-bit integer. /// diff --git a/X10D/src/Math/Int16Extensions.cs b/X10D/src/Math/Int16Extensions.cs index 7896cf3..d0d354e 100644 --- a/X10D/src/Math/Int16Extensions.cs +++ b/X10D/src/Math/Int16Extensions.cs @@ -9,6 +9,21 @@ namespace X10D.Math; /// public static class Int16Extensions { + /// + /// Returns the number of digits in the current 16-bit signed integer. + /// + /// The value whose digit count to compute. + /// The number of digits in . + public static int CountDigits(this short value) + { + if (value == 0) + { + return 1; + } + + return ((long)value).CountDigits(); + } + /// /// Computes the digital root of this 16-bit integer. /// diff --git a/X10D/src/Math/Int32Extensions.cs b/X10D/src/Math/Int32Extensions.cs index edaf0dd..95dc664 100644 --- a/X10D/src/Math/Int32Extensions.cs +++ b/X10D/src/Math/Int32Extensions.cs @@ -9,6 +9,21 @@ namespace X10D.Math; /// public static class Int32Extensions { + /// + /// Returns the number of digits in the current 32-bit signed integer. + /// + /// The value whose digit count to compute. + /// The number of digits in . + public static int CountDigits(this int value) + { + if (value == 0) + { + return 1; + } + + return ((long)value).CountDigits(); + } + /// /// Computes the digital root of this 32-bit integer. /// diff --git a/X10D/src/Math/Int64Extensions.cs b/X10D/src/Math/Int64Extensions.cs index 5f888cc..317a379 100644 --- a/X10D/src/Math/Int64Extensions.cs +++ b/X10D/src/Math/Int64Extensions.cs @@ -9,6 +9,21 @@ namespace X10D.Math; /// public static class Int64Extensions { + /// + /// Returns the number of digits in the current 64-bit signed integer. + /// + /// The value whose digit count to compute. + /// The number of digits in . + public static int CountDigits(this long value) + { + if (value == 0) + { + return 1; + } + + return 1 + (int)System.Math.Floor(System.Math.Log10(System.Math.Abs(value))); + } + /// /// Computes the digital root of this 64-bit integer. /// diff --git a/X10D/src/Math/SByteExtensions.cs b/X10D/src/Math/SByteExtensions.cs index cc61037..68dde8d 100644 --- a/X10D/src/Math/SByteExtensions.cs +++ b/X10D/src/Math/SByteExtensions.cs @@ -10,6 +10,21 @@ namespace X10D.Math; [CLSCompliant(false)] public static class SByteExtensions { + /// + /// Returns the number of digits in the current 8-bit signed integer. + /// + /// The value whose digit count to compute. + /// The number of digits in . + public static int CountDigits(this sbyte value) + { + if (value == 0) + { + return 1; + } + + return ((long)value).CountDigits(); + } + /// /// Computes the digital root of this 32-bit integer. /// diff --git a/X10D/src/Math/UInt16Extensions.cs b/X10D/src/Math/UInt16Extensions.cs index e118e58..73b97da 100644 --- a/X10D/src/Math/UInt16Extensions.cs +++ b/X10D/src/Math/UInt16Extensions.cs @@ -10,6 +10,21 @@ namespace X10D.Math; [CLSCompliant(false)] public static class UInt16Extensions { + /// + /// Returns the number of digits in the current 16-bit signed integer. + /// + /// The value whose digit count to compute. + /// The number of digits in . + public static int CountDigits(this ushort value) + { + if (value == 0) + { + return 1; + } + + return ((ulong)value).CountDigits(); + } + /// /// Computes the digital root of the current 16-bit unsigned integer. /// diff --git a/X10D/src/Math/UInt32Extensions.cs b/X10D/src/Math/UInt32Extensions.cs index 79fed45..f74b14c 100644 --- a/X10D/src/Math/UInt32Extensions.cs +++ b/X10D/src/Math/UInt32Extensions.cs @@ -10,6 +10,21 @@ namespace X10D.Math; [CLSCompliant(false)] public static class UInt32Extensions { + /// + /// Returns the number of digits in the current 32-bit unsigned integer. + /// + /// The value whose digit count to compute. + /// The number of digits in . + public static int CountDigits(this uint value) + { + if (value == 0) + { + return 1; + } + + return ((ulong)value).CountDigits(); + } + /// /// Computes the digital root of the current 32-bit unsigned integer. /// diff --git a/X10D/src/Math/UInt64Extensions.cs b/X10D/src/Math/UInt64Extensions.cs index 4bf9365..6c03a98 100644 --- a/X10D/src/Math/UInt64Extensions.cs +++ b/X10D/src/Math/UInt64Extensions.cs @@ -10,6 +10,21 @@ namespace X10D.Math; [CLSCompliant(false)] public static class UInt64Extensions { + /// + /// Returns the number of digits in the current 64-bit unsigned integer. + /// + /// The value whose digit count to compute. + /// The number of digits in . + public static int CountDigits(this ulong value) + { + if (value == 0) + { + return 1; + } + + return 1 + (int)System.Math.Floor(System.Math.Log10(System.Math.Abs((double)value))); + } + /// /// Computes the digital root of the current 64-bit unsigned integer. /// From 5289bd25951ab74e36b0cfd0ee01d592b8a075e4 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Thu, 6 Apr 2023 16:03:20 +0100 Subject: [PATCH 015/102] chore: move SourceGenerator to tools folder --- X10D.sln | 3 ++- X10D/X10D.csproj | 2 +- .../SourceGenerator}/EmojiRegexGenerator.cs | 0 .../SourceGenerator/SourceGenerator.csproj | 0 4 files changed, 3 insertions(+), 2 deletions(-) rename {X10D.SourceGenerator => tools/SourceGenerator}/EmojiRegexGenerator.cs (100%) rename X10D.SourceGenerator/X10D.SourceGenerator.csproj => tools/SourceGenerator/SourceGenerator.csproj (100%) diff --git a/X10D.sln b/X10D.sln index 1d8368a..846b992 100644 --- a/X10D.sln +++ b/X10D.sln @@ -22,7 +22,7 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SourceValidator", "tools\So EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "X10D.Unity", "X10D.Unity\X10D.Unity.csproj", "{7EAB3F09-A9FD-4334-B4DB-0394DD0C6568}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "X10D.SourceGenerator", "X10D.SourceGenerator\X10D.SourceGenerator.csproj", "{077A5D33-AD55-4C55-8A67-972CEBC32C7A}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SourceGenerator", "tools\SourceGenerator\SourceGenerator.csproj", "{077A5D33-AD55-4C55-8A67-972CEBC32C7A}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "X10D.DSharpPlus", "X10D.DSharpPlus\X10D.DSharpPlus.csproj", "{675D3B25-7EA0-4FC3-B513-8DF27874F2CF}" EndProject @@ -100,5 +100,6 @@ Global {84750149-9068-4780-AFDE-CDA1AC57007D} = {4B8969E6-27D2-4357-964E-9979FF7CC805} {CCBF047D-1B01-45EC-8D89-B00B4AC482CA} = {4B8969E6-27D2-4357-964E-9979FF7CC805} {259450A0-9964-403A-91E1-E9111B92C293} = {4B8969E6-27D2-4357-964E-9979FF7CC805} + {077A5D33-AD55-4C55-8A67-972CEBC32C7A} = {4B8969E6-27D2-4357-964E-9979FF7CC805} EndGlobalSection EndGlobal diff --git a/X10D/X10D.csproj b/X10D/X10D.csproj index 14eb676..c886ec5 100644 --- a/X10D/X10D.csproj +++ b/X10D/X10D.csproj @@ -83,7 +83,7 @@ - + diff --git a/X10D.SourceGenerator/EmojiRegexGenerator.cs b/tools/SourceGenerator/EmojiRegexGenerator.cs similarity index 100% rename from X10D.SourceGenerator/EmojiRegexGenerator.cs rename to tools/SourceGenerator/EmojiRegexGenerator.cs diff --git a/X10D.SourceGenerator/X10D.SourceGenerator.csproj b/tools/SourceGenerator/SourceGenerator.csproj similarity index 100% rename from X10D.SourceGenerator/X10D.SourceGenerator.csproj rename to tools/SourceGenerator/SourceGenerator.csproj From 0ca82534025c83a1aab485164ca854e9f5c6ffdc Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Thu, 6 Apr 2023 16:05:02 +0100 Subject: [PATCH 016/102] chore: remove X10D prefix from sourcegen --- tools/SourceGenerator/EmojiRegexGenerator.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/SourceGenerator/EmojiRegexGenerator.cs b/tools/SourceGenerator/EmojiRegexGenerator.cs index 2d67b1d..306bd3f 100644 --- a/tools/SourceGenerator/EmojiRegexGenerator.cs +++ b/tools/SourceGenerator/EmojiRegexGenerator.cs @@ -3,7 +3,7 @@ using System.Text.RegularExpressions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; -namespace X10D.SourceGenerator; +namespace SourceGenerator; [Generator] internal sealed class EmojiRegexGenerator : ISourceGenerator From 172380c57d011f9be4a4eeeef43e333aa67b1032 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Thu, 6 Apr 2023 16:58:32 +0100 Subject: [PATCH 017/102] [ci skip] chore: add meta services This class library will contain attributes for future source generation. --- X10D/X10D.csproj | 1 + tools/SourceGenerator/EmojiRegexGenerator.cs | 4 ++-- tools/SourceGenerator/SourceGenerator.csproj | 4 ++++ tools/X10D.MetaServices/X10D.MetaServices.csproj | 10 ++++++++++ 4 files changed, 17 insertions(+), 2 deletions(-) create mode 100644 tools/X10D.MetaServices/X10D.MetaServices.csproj diff --git a/X10D/X10D.csproj b/X10D/X10D.csproj index c886ec5..e034d06 100644 --- a/X10D/X10D.csproj +++ b/X10D/X10D.csproj @@ -84,6 +84,7 @@ + diff --git a/tools/SourceGenerator/EmojiRegexGenerator.cs b/tools/SourceGenerator/EmojiRegexGenerator.cs index 306bd3f..1ac9ca9 100644 --- a/tools/SourceGenerator/EmojiRegexGenerator.cs +++ b/tools/SourceGenerator/EmojiRegexGenerator.cs @@ -47,8 +47,8 @@ internal sealed class EmojiRegexGenerator : ISourceGenerator } var builder = new StringBuilder(); - builder.AppendLine("// This file was auto-generated by X10D.SourceGenerator"); - builder.AppendLine("// Do not edit this file manually"); + builder.AppendLine("// This file was auto-generated by the X10D source generator"); + builder.AppendLine("// Do not edit this file manually!"); builder.AppendLine(); builder.AppendLine("using System.Text.RegularExpressions;"); diff --git a/tools/SourceGenerator/SourceGenerator.csproj b/tools/SourceGenerator/SourceGenerator.csproj index e012f98..266d229 100644 --- a/tools/SourceGenerator/SourceGenerator.csproj +++ b/tools/SourceGenerator/SourceGenerator.csproj @@ -17,4 +17,8 @@ + + + + diff --git a/tools/X10D.MetaServices/X10D.MetaServices.csproj b/tools/X10D.MetaServices/X10D.MetaServices.csproj new file mode 100644 index 0000000..aa845a6 --- /dev/null +++ b/tools/X10D.MetaServices/X10D.MetaServices.csproj @@ -0,0 +1,10 @@ + + + + netstandard2.0 + 11.0 + enable + enable + + + From 7556efdfdd286f385d7a12f03bdf18eef01bad41 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Thu, 6 Apr 2023 17:00:39 +0100 Subject: [PATCH 018/102] chore: add AutoOverload and OverloadType attribute --- .../MethodOverloadGenerator.cs | 22 ++++++++++ .../SourceGenerator/OverloadSyntaxReceiver.cs | 41 +++++++++++++++++++ .../AutoOverloadAttribute.cs | 6 +++ .../OverloadTypeAttribute.cs | 20 +++++++++ 4 files changed, 89 insertions(+) create mode 100644 tools/SourceGenerator/MethodOverloadGenerator.cs create mode 100644 tools/SourceGenerator/OverloadSyntaxReceiver.cs create mode 100644 tools/X10D.MetaServices/AutoOverloadAttribute.cs create mode 100644 tools/X10D.MetaServices/OverloadTypeAttribute.cs diff --git a/tools/SourceGenerator/MethodOverloadGenerator.cs b/tools/SourceGenerator/MethodOverloadGenerator.cs new file mode 100644 index 0000000..cf05a35 --- /dev/null +++ b/tools/SourceGenerator/MethodOverloadGenerator.cs @@ -0,0 +1,22 @@ +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace SourceGenerator; + +[Generator] +internal sealed class MethodOverloadGenerator : ISourceGenerator +{ + /// + public void Initialize(GeneratorInitializationContext context) + { + context.RegisterForSyntaxNotifications(() => new OverloadSyntaxReceiver()); + } + + /// + public void Execute(GeneratorExecutionContext context) + { + var syntaxReceiver = (OverloadSyntaxReceiver)context.SyntaxReceiver!; + IReadOnlyList candidateMethods = syntaxReceiver.CandidateMethods; + // TODO implement + } +} diff --git a/tools/SourceGenerator/OverloadSyntaxReceiver.cs b/tools/SourceGenerator/OverloadSyntaxReceiver.cs new file mode 100644 index 0000000..cfe4668 --- /dev/null +++ b/tools/SourceGenerator/OverloadSyntaxReceiver.cs @@ -0,0 +1,41 @@ +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using X10D.MetaServices; + +namespace SourceGenerator; + +public class OverloadSyntaxReceiver : ISyntaxReceiver +{ + private readonly List _candidateMethods = new(); + + public IReadOnlyList CandidateMethods + { + get => _candidateMethods.AsReadOnly(); + } + + public void OnVisitSyntaxNode(SyntaxNode syntaxNode) + { + if (syntaxNode is not MethodDeclarationSyntax methodDeclarationSyntax) + { + return; + } + + if (methodDeclarationSyntax.AttributeLists.Count == 0) + { + return; + } + + string attributeName = nameof(AutoOverloadAttribute).Replace("Attribute", string.Empty); + foreach (AttributeListSyntax attributeListSyntax in methodDeclarationSyntax.AttributeLists) + { + foreach (AttributeSyntax attributeSyntax in attributeListSyntax.Attributes) + { + if (attributeSyntax.Name.ToString() == attributeName) + { + _candidateMethods.Add(methodDeclarationSyntax); + break; + } + } + } + } +} diff --git a/tools/X10D.MetaServices/AutoOverloadAttribute.cs b/tools/X10D.MetaServices/AutoOverloadAttribute.cs new file mode 100644 index 0000000..5630c84 --- /dev/null +++ b/tools/X10D.MetaServices/AutoOverloadAttribute.cs @@ -0,0 +1,6 @@ +namespace X10D.MetaServices; + +[AttributeUsage(AttributeTargets.Method, Inherited = false)] +public sealed class AutoOverloadAttribute : Attribute +{ +} diff --git a/tools/X10D.MetaServices/OverloadTypeAttribute.cs b/tools/X10D.MetaServices/OverloadTypeAttribute.cs new file mode 100644 index 0000000..d938a5b --- /dev/null +++ b/tools/X10D.MetaServices/OverloadTypeAttribute.cs @@ -0,0 +1,20 @@ +namespace X10D.MetaServices; + +[AttributeUsage(AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] +public sealed class OverloadTypeAttribute : Attribute +{ + /// + /// Initializes a new instance of the class. + /// + /// The types to overload. + public OverloadTypeAttribute(params Type[] types) + { + Types = (Type[])types.Clone(); + } + + /// + /// Gets an array of types to overload. + /// + /// An array of types to overload. + public Type[] Types { get; } +} From ce35f8676e24fd6a2d2496ab07310ff85bd3b6ee Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Thu, 6 Apr 2023 17:05:37 +0100 Subject: [PATCH 019/102] chore: make attributes internal --- tools/X10D.MetaServices/Assembly.cs | 4 ++++ tools/X10D.MetaServices/AutoOverloadAttribute.cs | 2 +- tools/X10D.MetaServices/OverloadTypeAttribute.cs | 2 +- 3 files changed, 6 insertions(+), 2 deletions(-) create mode 100644 tools/X10D.MetaServices/Assembly.cs diff --git a/tools/X10D.MetaServices/Assembly.cs b/tools/X10D.MetaServices/Assembly.cs new file mode 100644 index 0000000..274a45a --- /dev/null +++ b/tools/X10D.MetaServices/Assembly.cs @@ -0,0 +1,4 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("X10D")] +[assembly: InternalsVisibleTo("SourceGenerator")] diff --git a/tools/X10D.MetaServices/AutoOverloadAttribute.cs b/tools/X10D.MetaServices/AutoOverloadAttribute.cs index 5630c84..382e63e 100644 --- a/tools/X10D.MetaServices/AutoOverloadAttribute.cs +++ b/tools/X10D.MetaServices/AutoOverloadAttribute.cs @@ -1,6 +1,6 @@ namespace X10D.MetaServices; [AttributeUsage(AttributeTargets.Method, Inherited = false)] -public sealed class AutoOverloadAttribute : Attribute +internal sealed class AutoOverloadAttribute : Attribute { } diff --git a/tools/X10D.MetaServices/OverloadTypeAttribute.cs b/tools/X10D.MetaServices/OverloadTypeAttribute.cs index d938a5b..0fdde1a 100644 --- a/tools/X10D.MetaServices/OverloadTypeAttribute.cs +++ b/tools/X10D.MetaServices/OverloadTypeAttribute.cs @@ -1,7 +1,7 @@ namespace X10D.MetaServices; [AttributeUsage(AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] -public sealed class OverloadTypeAttribute : Attribute +internal sealed class OverloadTypeAttribute : Attribute { /// /// Initializes a new instance of the class. From 9d26f3da60dab8d07d07ecc29e0ca3c4cc12f160 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Thu, 6 Apr 2023 19:11:54 +0100 Subject: [PATCH 020/102] feat: add TextWriter.WriteNoAlloc/WriteLineNoAlloc Allows writing of integer types without allocating a string. --- CHANGELOG.md | 8 + X10D.Tests/src/IO/TextWriterTests.Int32.cs | 131 ++++ X10D.Tests/src/IO/TextWriterTests.Int64.cs | 131 ++++ X10D.Tests/src/IO/TextWriterTests.UInt32.cs | 131 ++++ X10D.Tests/src/IO/TextWriterTests.UInt64.cs | 131 ++++ X10D.Tests/src/IO/TextWriterTests.cs | 46 ++ X10D/src/IO/TextWriterExtensions.cs | 685 ++++++++++++++++++++ 7 files changed, 1263 insertions(+) create mode 100644 X10D.Tests/src/IO/TextWriterTests.Int32.cs create mode 100644 X10D.Tests/src/IO/TextWriterTests.Int64.cs create mode 100644 X10D.Tests/src/IO/TextWriterTests.UInt32.cs create mode 100644 X10D.Tests/src/IO/TextWriterTests.UInt64.cs create mode 100644 X10D.Tests/src/IO/TextWriterTests.cs create mode 100644 X10D/src/IO/TextWriterExtensions.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index e7daff2..4de5308 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - X10D: Added math-related extension methods for `BigInteger`. - X10D: Added `Span.Replace(T, T)`. - X10D: Added `CountDigits` for integer types. +- X10D: Added `TextWriter.WriteNoAlloc(int[, ReadOnlySpan[, IFormatProvider]])`. +- X10D: Added `TextWriter.WriteNoAlloc(uint[, ReadOnlySpan[, IFormatProvider]])`. +- X10D: Added `TextWriter.WriteNoAlloc(long[, ReadOnlySpan[, IFormatProvider]])`. +- X10D: Added `TextWriter.WriteNoAlloc(ulong[, ReadOnlySpan[, IFormatProvider]])`. +- X10D: Added `TextWriter.WriteLineNoAlloc(int[, ReadOnlySpan[, IFormatProvider]])`. +- X10D: Added `TextWriter.WriteLineNoAlloc(uint[, ReadOnlySpan[, IFormatProvider]])`. +- X10D: Added `TextWriter.WriteLineNoAlloc(long[, ReadOnlySpan[, IFormatProvider]])`. +- X10D: Added `TextWriter.WriteLineNoAlloc(ulong[, ReadOnlySpan[, IFormatProvider]])`. ### Changed - X10D: `DateTime.Age(DateTime)` and `DateTimeOffset.Age(DateTimeOffset)` parameter renamed from `asOf` to `referenceDate`. diff --git a/X10D.Tests/src/IO/TextWriterTests.Int32.cs b/X10D.Tests/src/IO/TextWriterTests.Int32.cs new file mode 100644 index 0000000..31bed11 --- /dev/null +++ b/X10D.Tests/src/IO/TextWriterTests.Int32.cs @@ -0,0 +1,131 @@ +using System.Globalization; +using System.Text; +using NUnit.Framework; +using X10D.IO; + +namespace X10D.Tests.IO; + +public partial class TextWriterTests +{ + [Test] + public void WriteNoAlloc_ShouldThrowArgumentNullException_GivenInt32_AndNullWriter() + { + TextWriter writer = null!; + Assert.Throws(() => writer.WriteNoAlloc(420)); + Assert.Throws(() => writer.WriteNoAlloc(420, "N0")); + Assert.Throws(() => writer.WriteNoAlloc(420, "N0", null)); + } + + [Test] + public void WriteNoAlloc_ShouldThrowObjectDisposedException_GivenInt32_AndDisposedStream() + { + var stream = new MemoryStream(); + var writer = new StreamWriter(stream, Encoding.UTF8); + writer.Dispose(); + stream.Dispose(); + + Assert.Throws(() => writer.WriteNoAlloc(420)); + Assert.Throws(() => writer.WriteNoAlloc(420, "N0")); + Assert.Throws(() => writer.WriteNoAlloc(420, "N0", null)); + } + + [Test] + public void WriteLineNoAlloc_ShouldThrowArgumentNullException_GivenInt32_AndNullWriter() + { + TextWriter writer = null!; + Assert.Throws(() => writer.WriteLineNoAlloc(420)); + Assert.Throws(() => writer.WriteLineNoAlloc(420, "N0")); + Assert.Throws(() => writer.WriteLineNoAlloc(420, "N0", null)); + } + + [Test] + public void WriteLineNoAlloc_ShouldThrowObjectDisposedException_GivenInt32_AndDisposedStream() + { + var stream = new MemoryStream(); + var writer = new StreamWriter(stream, Encoding.UTF8); + writer.Dispose(); + stream.Dispose(); + + Assert.Throws(() => writer.WriteLineNoAlloc(420)); + Assert.Throws(() => writer.WriteLineNoAlloc(420, "N0")); + Assert.Throws(() => writer.WriteLineNoAlloc(420, "N0", null)); + } + + [Test] + public void WriteNoAlloc_ShouldWriteTextValue_GivenInt32() + { + Assert.That(_stream.Length, Is.Zero); + _writer.WriteNoAlloc(420); + _writer.Flush(); + + string actual = Encoding.UTF8.GetString(_stream.ToArray()); + const string expected = "420"; + + Assert.That(actual, Is.EqualTo(expected)); + } + + [Test] + public void WriteNoAlloc_ShouldWriteTextValue_GivenInt32_AndFormatString() + { + Assert.That(_stream.Length, Is.Zero); + _writer.WriteNoAlloc(420, "N0"); + _writer.Flush(); + + string actual = Encoding.UTF8.GetString(_stream.ToArray()); + const string expected = "420"; + + Assert.That(actual, Is.EqualTo(expected)); + } + + [Test] + public void WriteNoAlloc_ShouldWriteTextValue_GivenInt32_AndFormatString_AndCultureInfo() + { + Assert.That(_stream.Length, Is.Zero); + _writer.WriteNoAlloc(420, "N0", CultureInfo.CurrentCulture); + _writer.Flush(); + + string actual = Encoding.UTF8.GetString(_stream.ToArray()); + const string expected = "420"; + + Assert.That(actual, Is.EqualTo(expected)); + } + + [Test] + public void WriteLineNoAlloc_ShouldWriteTextValue_GivenInt32() + { + Assert.That(_stream.Length, Is.Zero); + _writer.WriteLineNoAlloc(420); + _writer.Flush(); + + string actual = Encoding.UTF8.GetString(_stream.ToArray()); + var expected = $"420{Environment.NewLine}"; + + Assert.That(actual, Is.EqualTo(expected)); + } + + [Test] + public void WriteLineNoAlloc_ShouldWriteTextValue_GivenInt32_AndFormatString() + { + Assert.That(_stream.Length, Is.Zero); + _writer.WriteLineNoAlloc(420, "N0"); + _writer.Flush(); + + string actual = Encoding.UTF8.GetString(_stream.ToArray()); + var expected = $"420{Environment.NewLine}"; + + Assert.That(actual, Is.EqualTo(expected)); + } + + [Test] + public void WriteLineNoAlloc_ShouldWriteTextValue_GivenInt32_AndFormatString_AndCultureInfo() + { + Assert.That(_stream.Length, Is.Zero); + _writer.WriteLineNoAlloc(420, "N0", CultureInfo.CurrentCulture); + _writer.Flush(); + + string actual = Encoding.UTF8.GetString(_stream.ToArray()); + var expected = $"420{Environment.NewLine}"; + + Assert.That(actual, Is.EqualTo(expected)); + } +} diff --git a/X10D.Tests/src/IO/TextWriterTests.Int64.cs b/X10D.Tests/src/IO/TextWriterTests.Int64.cs new file mode 100644 index 0000000..affd830 --- /dev/null +++ b/X10D.Tests/src/IO/TextWriterTests.Int64.cs @@ -0,0 +1,131 @@ +using System.Globalization; +using System.Text; +using NUnit.Framework; +using X10D.IO; + +namespace X10D.Tests.IO; + +public partial class TextWriterTests +{ + [Test] + public void WriteNoAlloc_ShouldThrowArgumentNullException_GivenInt64_AndNullWriter() + { + TextWriter writer = null!; + Assert.Throws(() => writer.WriteNoAlloc(420L)); + Assert.Throws(() => writer.WriteNoAlloc(420L, "N0")); + Assert.Throws(() => writer.WriteNoAlloc(420L, "N0", null)); + } + + [Test] + public void WriteNoAlloc_ShouldThrowObjectDisposedException_GivenInt64_AndDisposedStream() + { + var stream = new MemoryStream(); + var writer = new StreamWriter(stream, Encoding.UTF8); + writer.Dispose(); + stream.Dispose(); + + Assert.Throws(() => writer.WriteNoAlloc(420L)); + Assert.Throws(() => writer.WriteNoAlloc(420L, "N0")); + Assert.Throws(() => writer.WriteNoAlloc(420L, "N0", null)); + } + + [Test] + public void WriteLineNoAlloc_ShouldThrowArgumentNullException_GivenInt64_AndNullWriter() + { + TextWriter writer = null!; + Assert.Throws(() => writer.WriteLineNoAlloc(420L)); + Assert.Throws(() => writer.WriteLineNoAlloc(420L, "N0")); + Assert.Throws(() => writer.WriteLineNoAlloc(420L, "N0", null)); + } + + [Test] + public void WriteLineNoAlloc_ShouldThrowObjectDisposedException_GivenInt64_AndDisposedStream() + { + var stream = new MemoryStream(); + var writer = new StreamWriter(stream, Encoding.UTF8); + writer.Dispose(); + stream.Dispose(); + + Assert.Throws(() => writer.WriteLineNoAlloc(420L)); + Assert.Throws(() => writer.WriteLineNoAlloc(420L, "N0")); + Assert.Throws(() => writer.WriteLineNoAlloc(420L, "N0", null)); + } + + [Test] + public void WriteNoAlloc_ShouldWriteTextValue_GivenInt64() + { + Assert.That(_stream.Length, Is.Zero); + _writer.WriteNoAlloc(420L); + _writer.Flush(); + + string actual = Encoding.UTF8.GetString(_stream.ToArray()); + const string expected = "420"; + + Assert.That(actual, Is.EqualTo(expected)); + } + + [Test] + public void WriteNoAlloc_ShouldWriteTextValue_GivenInt64_AndFormatString() + { + Assert.That(_stream.Length, Is.Zero); + _writer.WriteNoAlloc(420L, "N0"); + _writer.Flush(); + + string actual = Encoding.UTF8.GetString(_stream.ToArray()); + const string expected = "420"; + + Assert.That(actual, Is.EqualTo(expected)); + } + + [Test] + public void WriteNoAlloc_ShouldWriteTextValue_GivenInt64_AndFormatString_AndCultureInfo() + { + Assert.That(_stream.Length, Is.Zero); + _writer.WriteNoAlloc(420L, "N0", CultureInfo.CurrentCulture); + _writer.Flush(); + + string actual = Encoding.UTF8.GetString(_stream.ToArray()); + const string expected = "420"; + + Assert.That(actual, Is.EqualTo(expected)); + } + + [Test] + public void WriteLineNoAlloc_ShouldWriteTextValue_GivenInt64() + { + Assert.That(_stream.Length, Is.Zero); + _writer.WriteLineNoAlloc(420L); + _writer.Flush(); + + string actual = Encoding.UTF8.GetString(_stream.ToArray()); + var expected = $"420{Environment.NewLine}"; + + Assert.That(actual, Is.EqualTo(expected)); + } + + [Test] + public void WriteLineNoAlloc_ShouldWriteTextValue_GivenInt64_AndFormatString() + { + Assert.That(_stream.Length, Is.Zero); + _writer.WriteLineNoAlloc(420L, "N0"); + _writer.Flush(); + + string actual = Encoding.UTF8.GetString(_stream.ToArray()); + var expected = $"420{Environment.NewLine}"; + + Assert.That(actual, Is.EqualTo(expected)); + } + + [Test] + public void WriteLineNoAlloc_ShouldWriteTextValue_GivenInt64_AndFormatString_AndCultureInfo() + { + Assert.That(_stream.Length, Is.Zero); + _writer.WriteLineNoAlloc(420L, "N0", CultureInfo.CurrentCulture); + _writer.Flush(); + + string actual = Encoding.UTF8.GetString(_stream.ToArray()); + var expected = $"420{Environment.NewLine}"; + + Assert.That(actual, Is.EqualTo(expected)); + } +} diff --git a/X10D.Tests/src/IO/TextWriterTests.UInt32.cs b/X10D.Tests/src/IO/TextWriterTests.UInt32.cs new file mode 100644 index 0000000..8aab080 --- /dev/null +++ b/X10D.Tests/src/IO/TextWriterTests.UInt32.cs @@ -0,0 +1,131 @@ +using System.Globalization; +using System.Text; +using NUnit.Framework; +using X10D.IO; + +namespace X10D.Tests.IO; + +public partial class TextWriterTests +{ + [Test] + public void WriteNoAlloc_ShouldThrowArgumentNullException_GivenUInt32_AndNullWriter() + { + TextWriter writer = null!; + Assert.Throws(() => writer.WriteNoAlloc(420U)); + Assert.Throws(() => writer.WriteNoAlloc(420U, "N0")); + Assert.Throws(() => writer.WriteNoAlloc(420U, "N0", null)); + } + + [Test] + public void WriteNoAlloc_ShouldThrowObjectDisposedException_GivenUInt32_AndDisposedStream() + { + var stream = new MemoryStream(); + var writer = new StreamWriter(stream, Encoding.UTF8); + writer.Dispose(); + stream.Dispose(); + + Assert.Throws(() => writer.WriteNoAlloc(420U)); + Assert.Throws(() => writer.WriteNoAlloc(420U, "N0")); + Assert.Throws(() => writer.WriteNoAlloc(420U, "N0", null)); + } + + [Test] + public void WriteLineNoAlloc_ShouldThrowArgumentNullException_GivenUInt32_AndNullWriter() + { + TextWriter writer = null!; + Assert.Throws(() => writer.WriteLineNoAlloc(420U)); + Assert.Throws(() => writer.WriteLineNoAlloc(420U, "N0")); + Assert.Throws(() => writer.WriteLineNoAlloc(420U, "N0", null)); + } + + [Test] + public void WriteLineNoAlloc_ShouldThrowObjectDisposedException_GivenUInt32_AndDisposedStream() + { + var stream = new MemoryStream(); + var writer = new StreamWriter(stream, Encoding.UTF8); + writer.Dispose(); + stream.Dispose(); + + Assert.Throws(() => writer.WriteLineNoAlloc(420U)); + Assert.Throws(() => writer.WriteLineNoAlloc(420U, "N0")); + Assert.Throws(() => writer.WriteLineNoAlloc(420U, "N0", null)); + } + + [Test] + public void WriteNoAlloc_ShouldWriteTextValue_GivenUInt32() + { + Assert.That(_stream.Length, Is.Zero); + _writer.WriteNoAlloc(420U); + _writer.Flush(); + + string actual = Encoding.UTF8.GetString(_stream.ToArray()); + const string expected = "420"; + + Assert.That(actual, Is.EqualTo(expected)); + } + + [Test] + public void WriteNoAlloc_ShouldWriteTextValue_GivenUInt32_AndFormatString() + { + Assert.That(_stream.Length, Is.Zero); + _writer.WriteNoAlloc(420U, "N0"); + _writer.Flush(); + + string actual = Encoding.UTF8.GetString(_stream.ToArray()); + const string expected = "420"; + + Assert.That(actual, Is.EqualTo(expected)); + } + + [Test] + public void WriteNoAlloc_ShouldWriteTextValue_GivenUInt32_AndFormatString_AndCultureInfo() + { + Assert.That(_stream.Length, Is.Zero); + _writer.WriteNoAlloc(420U, "N0", CultureInfo.CurrentCulture); + _writer.Flush(); + + string actual = Encoding.UTF8.GetString(_stream.ToArray()); + const string expected = "420"; + + Assert.That(actual, Is.EqualTo(expected)); + } + + [Test] + public void WriteLineNoAlloc_ShouldWriteTextValue_GivenUInt32() + { + Assert.That(_stream.Length, Is.Zero); + _writer.WriteLineNoAlloc(420U); + _writer.Flush(); + + string actual = Encoding.UTF8.GetString(_stream.ToArray()); + var expected = $"420{Environment.NewLine}"; + + Assert.That(actual, Is.EqualTo(expected)); + } + + [Test] + public void WriteLineNoAlloc_ShouldWriteTextValue_GivenUInt32_AndFormatString() + { + Assert.That(_stream.Length, Is.Zero); + _writer.WriteLineNoAlloc(420U, "N0"); + _writer.Flush(); + + string actual = Encoding.UTF8.GetString(_stream.ToArray()); + var expected = $"420{Environment.NewLine}"; + + Assert.That(actual, Is.EqualTo(expected)); + } + + [Test] + public void WriteLineNoAlloc_ShouldWriteTextValue_GivenUInt32_AndFormatString_AndCultureInfo() + { + Assert.That(_stream.Length, Is.Zero); + _writer.WriteLineNoAlloc(420U, "N0", CultureInfo.CurrentCulture); + _writer.Flush(); + + string actual = Encoding.UTF8.GetString(_stream.ToArray()); + var expected = $"420{Environment.NewLine}"; + + Assert.That(actual, Is.EqualTo(expected)); + } +} diff --git a/X10D.Tests/src/IO/TextWriterTests.UInt64.cs b/X10D.Tests/src/IO/TextWriterTests.UInt64.cs new file mode 100644 index 0000000..57f5425 --- /dev/null +++ b/X10D.Tests/src/IO/TextWriterTests.UInt64.cs @@ -0,0 +1,131 @@ +using System.Globalization; +using System.Text; +using NUnit.Framework; +using X10D.IO; + +namespace X10D.Tests.IO; + +public partial class TextWriterTests +{ + [Test] + public void WriteNoAlloc_ShouldThrowArgumentNullException_GivenUInt64_AndNullWriter() + { + TextWriter writer = null!; + Assert.Throws(() => writer.WriteNoAlloc(420UL)); + Assert.Throws(() => writer.WriteNoAlloc(420UL, "N0")); + Assert.Throws(() => writer.WriteNoAlloc(420UL, "N0", null)); + } + + [Test] + public void WriteNoAlloc_ShouldThrowObjectDisposedException_GivenUInt64_AndDisposedStream() + { + var stream = new MemoryStream(); + var writer = new StreamWriter(stream, Encoding.UTF8); + writer.Dispose(); + stream.Dispose(); + + Assert.Throws(() => writer.WriteNoAlloc(420UL)); + Assert.Throws(() => writer.WriteNoAlloc(420UL, "N0")); + Assert.Throws(() => writer.WriteNoAlloc(420UL, "N0", null)); + } + + [Test] + public void WriteLineNoAlloc_ShouldThrowArgumentNullException_GivenUInt64_AndNullWriter() + { + TextWriter writer = null!; + Assert.Throws(() => writer.WriteLineNoAlloc(420UL)); + Assert.Throws(() => writer.WriteLineNoAlloc(420UL, "N0")); + Assert.Throws(() => writer.WriteLineNoAlloc(420UL, "N0", null)); + } + + [Test] + public void WriteLineNoAlloc_ShouldThrowObjectDisposedException_GivenUInt64_AndDisposedStream() + { + var stream = new MemoryStream(); + var writer = new StreamWriter(stream, Encoding.UTF8); + writer.Dispose(); + stream.Dispose(); + + Assert.Throws(() => writer.WriteLineNoAlloc(420UL)); + Assert.Throws(() => writer.WriteLineNoAlloc(420UL, "N0")); + Assert.Throws(() => writer.WriteLineNoAlloc(420UL, "N0", null)); + } + + [Test] + public void WriteNoAlloc_ShouldWriteTextValue_GivenUInt64() + { + Assert.That(_stream.Length, Is.Zero); + _writer.WriteNoAlloc(420UL); + _writer.Flush(); + + string actual = Encoding.UTF8.GetString(_stream.ToArray()); + const string expected = "420"; + + Assert.That(actual, Is.EqualTo(expected)); + } + + [Test] + public void WriteNoAlloc_ShouldWriteTextValue_GivenUInt64_AndFormatString() + { + Assert.That(_stream.Length, Is.Zero); + _writer.WriteNoAlloc(420UL, "N0"); + _writer.Flush(); + + string actual = Encoding.UTF8.GetString(_stream.ToArray()); + const string expected = "420"; + + Assert.That(actual, Is.EqualTo(expected)); + } + + [Test] + public void WriteNoAlloc_ShouldWriteTextValue_GivenUInt64_AndFormatString_AndCultureInfo() + { + Assert.That(_stream.Length, Is.Zero); + _writer.WriteNoAlloc(420UL, "N0", CultureInfo.CurrentCulture); + _writer.Flush(); + + string actual = Encoding.UTF8.GetString(_stream.ToArray()); + const string expected = "420"; + + Assert.That(actual, Is.EqualTo(expected)); + } + + [Test] + public void WriteLineNoAlloc_ShouldWriteTextValue_GivenUInt64() + { + Assert.That(_stream.Length, Is.Zero); + _writer.WriteLineNoAlloc(420UL); + _writer.Flush(); + + string actual = Encoding.UTF8.GetString(_stream.ToArray()); + var expected = $"420{Environment.NewLine}"; + + Assert.That(actual, Is.EqualTo(expected)); + } + + [Test] + public void WriteLineNoAlloc_ShouldWriteTextValue_GivenUInt64_AndFormatString() + { + Assert.That(_stream.Length, Is.Zero); + _writer.WriteLineNoAlloc(420UL, "N0"); + _writer.Flush(); + + string actual = Encoding.UTF8.GetString(_stream.ToArray()); + var expected = $"420{Environment.NewLine}"; + + Assert.That(actual, Is.EqualTo(expected)); + } + + [Test] + public void WriteLineNoAlloc_ShouldWriteTextValue_GivenUInt64_AndFormatString_AndCultureInfo() + { + Assert.That(_stream.Length, Is.Zero); + _writer.WriteLineNoAlloc(420UL, "N0", CultureInfo.CurrentCulture); + _writer.Flush(); + + string actual = Encoding.UTF8.GetString(_stream.ToArray()); + var expected = $"420{Environment.NewLine}"; + + Assert.That(actual, Is.EqualTo(expected)); + } +} diff --git a/X10D.Tests/src/IO/TextWriterTests.cs b/X10D.Tests/src/IO/TextWriterTests.cs new file mode 100644 index 0000000..b98268a --- /dev/null +++ b/X10D.Tests/src/IO/TextWriterTests.cs @@ -0,0 +1,46 @@ +using System.Diagnostics; +using System.Text; +using NUnit.Framework; + +namespace X10D.Tests.IO; + +[TestFixture] +public partial class TextWriterTests +{ + private MemoryStream _stream = null!; + private StreamWriter _writer = null!; + + [OneTimeSetUp] + public void OneTimeSetup() + { + _stream = new MemoryStream(); + _writer = new StreamWriter(_stream, Encoding.UTF8); + _writer.Write(' '); + _writer.Flush(); + _stream.SetLength(0); + _stream.Position = 0; + + Trace.Listeners.Add(new ConsoleTraceListener()); + } + + [OneTimeTearDown] + public void OneTimeTearDown() + { + _writer.Dispose(); + _stream.Dispose(); + + Trace.Flush(); + } + + [SetUp] + public void Setup() + { + _stream.SetLength(0); + } + + [TearDown] + public void TearDown() + { + _stream.SetLength(0); + } +} diff --git a/X10D/src/IO/TextWriterExtensions.cs b/X10D/src/IO/TextWriterExtensions.cs new file mode 100644 index 0000000..7d1b3c5 --- /dev/null +++ b/X10D/src/IO/TextWriterExtensions.cs @@ -0,0 +1,685 @@ +using System.Globalization; +using X10D.Math; + +namespace X10D.IO; + +/// +/// IO-related extension methods for . +/// +public static class TextWriterExtensions +{ + /// + /// Writes the text representation of a 4-byte signed integer to the text stream, without allocating a string. + /// + /// The to write to. + /// The 4-byte signed integer to write. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + public static void WriteNoAlloc(this TextWriter writer, int value) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + WriteNoAlloc(writer, value, "N0".AsSpan(), CultureInfo.CurrentCulture); + } + + /// + /// Writes the text representation of a 4-byte signed integer to the text stream, without allocating a string. + /// + /// The to write to. + /// The 4-byte signed integer to write. + /// A standard or custom numeric format string. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + public static void WriteNoAlloc(this TextWriter writer, int value, ReadOnlySpan format) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + WriteNoAlloc(writer, value, format, CultureInfo.CurrentCulture); + } + + /// + /// Writes the text representation of a 4-byte signed integer to the text stream, without allocating a string. + /// + /// The to write to. + /// The 4-byte signed integer to write. + /// A standard or custom numeric format string. + /// An object that supplies culture-specific formatting information. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + public static void WriteNoAlloc(this TextWriter writer, int value, ReadOnlySpan format, IFormatProvider? formatProvider) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + int digitCount = value.CountDigits(); + Span buffer = stackalloc char[System.Math.Max(value < 0 ? digitCount + 1 : digitCount, 1000)]; + if (value.TryFormat(buffer, out int charsWritten, format, formatProvider)) + { + Span truncated = buffer[..charsWritten]; + for (var index = 0; index < truncated.Length; index++) + { + writer.Write(truncated[index]); + } + } + else + { + writer.Write(value.ToString(format.ToString(), formatProvider)); + } + } + + /// + /// Writes the text representation of a 4-byte unsigned integer to the text stream, without allocating a string. + /// + /// The to write to. + /// The 4-byte unsigned integer to write. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + [CLSCompliant(false)] + public static void WriteNoAlloc(this TextWriter writer, uint value) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + WriteNoAlloc(writer, value, "N0".AsSpan(), CultureInfo.CurrentCulture); + } + + /// + /// Writes the text representation of a 4-byte unsigned integer to the text stream, without allocating a string. + /// + /// The to write to. + /// The 4-byte unsigned integer to write. + /// A standard or custom numeric format string. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + [CLSCompliant(false)] + public static void WriteNoAlloc(this TextWriter writer, uint value, ReadOnlySpan format) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + WriteNoAlloc(writer, value, format, CultureInfo.CurrentCulture); + } + + /// + /// Writes the text representation of a 4-byte unsigned integer to the text stream, without allocating a string. + /// + /// The to write to. + /// The 4-byte unsigned integer to write. + /// A standard or custom numeric format string. + /// An object that supplies culture-specific formatting information. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + [CLSCompliant(false)] + public static void WriteNoAlloc(this TextWriter writer, + uint value, + ReadOnlySpan format, + IFormatProvider? formatProvider) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + int digitCount = value.CountDigits(); + Span buffer = stackalloc char[System.Math.Max(digitCount, 1000)]; + if (value.TryFormat(buffer, out int charsWritten, format, formatProvider)) + { + Span truncated = buffer[..charsWritten]; + for (var index = 0; index < truncated.Length; index++) + { + writer.Write(truncated[index]); + } + } + else + { + writer.Write(value.ToString(format.ToString(), formatProvider)); + } + } + + /// + /// Writes the text representation of a 8-byte signed integer to the text stream, without allocating a string. + /// + /// The to write to. + /// The 8-byte signed integer to write. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + public static void WriteNoAlloc(this TextWriter writer, long value) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + WriteNoAlloc(writer, value, "N0".AsSpan(), CultureInfo.CurrentCulture); + } + + /// + /// Writes the text representation of a 8-byte signed integer to the text stream, without allocating a string. + /// + /// The to write to. + /// The 8-byte signed integer to write. + /// A standard or custom numeric format string. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + public static void WriteNoAlloc(this TextWriter writer, long value, ReadOnlySpan format) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + WriteNoAlloc(writer, value, format, CultureInfo.CurrentCulture); + } + + /// + /// Writes the text representation of a 8-byte signed integer to the text stream, without allocating a string. + /// + /// The to write to. + /// The 8-byte signed integer to write. + /// A standard or custom numeric format string. + /// An object that supplies culture-specific formatting information. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + public static void WriteNoAlloc(this TextWriter writer, + long value, + ReadOnlySpan format, + IFormatProvider? formatProvider) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + int digitCount = value.CountDigits(); + Span buffer = stackalloc char[System.Math.Max(value < 0 ? digitCount + 1 : digitCount, 1000)]; + if (value.TryFormat(buffer, out int charsWritten, format, formatProvider)) + { + Span truncated = buffer[..charsWritten]; + for (var index = 0; index < truncated.Length; index++) + { + writer.Write(truncated[index]); + } + } + else + { + writer.Write(value.ToString(format.ToString(), formatProvider)); + } + } + + /// + /// Writes the text representation of a 8-byte unsigned integer to the text stream, without allocating a string. + /// + /// The to write to. + /// The 8-byte unsigned integer to write. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + [CLSCompliant(false)] + public static void WriteNoAlloc(this TextWriter writer, ulong value) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + WriteNoAlloc(writer, value, "N0".AsSpan(), CultureInfo.CurrentCulture); + } + + /// + /// Writes the text representation of a 8-byte signed integer to the text stream, without allocating a string. + /// + /// The to write to. + /// The 8-byte unsigned integer to write. + /// A standard or custom numeric format string. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + [CLSCompliant(false)] + public static void WriteNoAlloc(this TextWriter writer, ulong value, ReadOnlySpan format) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + WriteNoAlloc(writer, value, format, CultureInfo.CurrentCulture); + } + + /// + /// Writes the text representation of a 8-byte signed integer to the text stream, without allocating a string. + /// + /// The to write to. + /// The 8-byte unsigned integer to write. + /// A standard or custom numeric format string. + /// An object that supplies culture-specific formatting information. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + [CLSCompliant(false)] + public static void WriteNoAlloc(this TextWriter writer, + ulong value, + ReadOnlySpan format, + IFormatProvider? formatProvider) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + int digitCount = value.CountDigits(); + Span buffer = stackalloc char[System.Math.Max(digitCount, 1000)]; + if (value.TryFormat(buffer, out int charsWritten, format, formatProvider)) + { + Span truncated = buffer[..charsWritten]; + for (var index = 0; index < truncated.Length; index++) + { + writer.Write(truncated[index]); + } + } + else + { + writer.Write(value.ToString(format.ToString(), formatProvider)); + } + } + + /// + /// Writes the text representation of a 4-byte signed integer to the text stream, followed by a line terminator, without + /// allocating a string. + /// + /// The to write to. + /// The 4-byte signed integer to write. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + public static void WriteLineNoAlloc(this TextWriter writer, int value) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + writer.WriteLineNoAlloc(value, "N0".AsSpan(), CultureInfo.CurrentCulture); + } + + /// + /// Writes the text representation of a 4-byte signed integer to the text stream, followed by a line terminator, without + /// allocating a string. + /// + /// The to write to. + /// The 4-byte signed integer to write. + /// A standard or custom numeric format string. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + public static void WriteLineNoAlloc(this TextWriter writer, int value, ReadOnlySpan format) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + writer.WriteLineNoAlloc(value, format, CultureInfo.CurrentCulture); + } + + /// + /// Writes the text representation of a 4-byte signed integer to the text stream, followed by a line terminator, without + /// allocating a string. + /// + /// The to write to. + /// The 4-byte signed integer to write. + /// A standard or custom numeric format string. + /// An object that supplies culture-specific formatting information. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + public static void WriteLineNoAlloc(this TextWriter writer, int value, ReadOnlySpan format, + IFormatProvider? formatProvider) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + writer.WriteNoAlloc(value, format, formatProvider); + writer.WriteLine(); + } + + /// + /// Writes the text representation of a 4-byte unsigned integer to the text stream, followed by a line terminator, without + /// allocating a string. + /// + /// The to write to. + /// The 4-byte unsigned integer to write. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + [CLSCompliant(false)] + public static void WriteLineNoAlloc(this TextWriter writer, uint value) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + writer.WriteLineNoAlloc(value, "N0".AsSpan(), CultureInfo.CurrentCulture); + } + + /// + /// Writes the text representation of a 4-byte unsigned integer to the text stream, followed by a line terminator, without + /// allocating a string. + /// + /// The to write to. + /// The 4-byte unsigned integer to write. + /// A standard or custom numeric format string. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + [CLSCompliant(false)] + public static void WriteLineNoAlloc(this TextWriter writer, uint value, ReadOnlySpan format) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + writer.WriteLineNoAlloc(value, format, CultureInfo.CurrentCulture); + } + + /// + /// Writes the text representation of a 4-byte unsigned integer to the text stream, followed by a line terminator, without + /// allocating a string. + /// + /// The to write to. + /// The 4-byte unsigned integer to write. + /// A standard or custom numeric format string. + /// An object that supplies culture-specific formatting information. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + [CLSCompliant(false)] + public static void WriteLineNoAlloc(this TextWriter writer, + uint value, + ReadOnlySpan format, + IFormatProvider? formatProvider) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + writer.WriteNoAlloc(value, format, formatProvider); + writer.WriteLine(); + } + + /// + /// Writes the text representation of a 8-byte signed integer to the text stream, followed by a line terminator, without + /// allocating a string. + /// + /// The to write to. + /// The 8-byte signed integer to write. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + public static void WriteLineNoAlloc(this TextWriter writer, long value) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + writer.WriteLineNoAlloc(value, "N0".AsSpan(), CultureInfo.CurrentCulture); + } + + /// + /// Writes the text representation of a 8-byte signed integer to the text stream, followed by a line terminator, without + /// allocating a string. + /// + /// The to write to. + /// The 8-byte signed integer to write. + /// A standard or custom numeric format string. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + public static void WriteLineNoAlloc(this TextWriter writer, long value, ReadOnlySpan format) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + writer.WriteLineNoAlloc(value, format, CultureInfo.CurrentCulture); + } + + /// + /// Writes the text representation of a 8-byte signed integer to the text stream, followed by a line terminator, without + /// allocating a string. + /// + /// The to write to. + /// The 8-byte signed integer to write. + /// A standard or custom numeric format string. + /// An object that supplies culture-specific formatting information. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + public static void WriteLineNoAlloc(this TextWriter writer, + long value, + ReadOnlySpan format, + IFormatProvider? formatProvider) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + writer.WriteNoAlloc(value, format, formatProvider); + writer.WriteLine(); + } + + /// + /// Writes the text representation of a 8-byte unsigned integer to the text stream, followed by a line terminator, without + /// allocating a string. + /// + /// The to write to. + /// The 8-byte unsigned integer to write. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + [CLSCompliant(false)] + public static void WriteLineNoAlloc(this TextWriter writer, ulong value) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + writer.WriteLineNoAlloc(value, "N0".AsSpan(), CultureInfo.CurrentCulture); + } + + /// + /// Writes the text representation of a 8-byte signed integer to the text stream, followed by a line terminator, without + /// allocating a string. + /// + /// The to write to. + /// The 8-byte unsigned integer to write. + /// A standard or custom numeric format string. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + [CLSCompliant(false)] + public static void WriteLineNoAlloc(this TextWriter writer, ulong value, ReadOnlySpan format) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + writer.WriteLineNoAlloc(value, format, CultureInfo.CurrentCulture); + } + + /// + /// Writes the text representation of a 8-byte signed integer to the text stream, followed by a line terminator, without + /// allocating a string. + /// + /// The to write to. + /// The 8-byte unsigned integer to write. + /// A standard or custom numeric format string. + /// An object that supplies culture-specific formatting information. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + [CLSCompliant(false)] + public static void WriteLineNoAlloc(this TextWriter writer, + ulong value, + ReadOnlySpan format, + IFormatProvider? formatProvider) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + writer.WriteNoAlloc(value, format, formatProvider); + writer.WriteLine(); + } +} From 57ff32ee94987bbf69bde049268a6d9a3c355378 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Thu, 6 Apr 2023 19:18:20 +0100 Subject: [PATCH 021/102] [ci skip] docs: add comment explaining my absolute pain --- X10D.Tests/src/IO/TextWriterTests.cs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/X10D.Tests/src/IO/TextWriterTests.cs b/X10D.Tests/src/IO/TextWriterTests.cs index b98268a..750b352 100644 --- a/X10D.Tests/src/IO/TextWriterTests.cs +++ b/X10D.Tests/src/IO/TextWriterTests.cs @@ -15,6 +15,17 @@ public partial class TextWriterTests { _stream = new MemoryStream(); _writer = new StreamWriter(_stream, Encoding.UTF8); + + // When StreamWriter flushes for the first time, an encoding preamble is written to the stream, + // which is correctly mirrored by the behaviour of StreamReader. + // however, we're not using StreamReader, we read the contents of the stream + // using MemoryStream.ToArray(). This was causing one test to fail, as the first test + // that runs would cause the preamble to be written and not be accounted for when reading. + // Subsequent tests would pass since the preamble would not be written again. + // The following 4 lines ensure that the preamble is written by manually flushing the + // writer after writing a single space character. We then clear the stream, and allow + // unit tests to do their thing. This took me an HOUR AND A HALF to narrow down. + // I want to fucking die. _writer.Write(' '); _writer.Flush(); _stream.SetLength(0); From 75ac9e2d8f2905fde32c3216b65d521bd8b2cec9 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Thu, 6 Apr 2023 19:22:27 +0100 Subject: [PATCH 022/102] chore: add MetaServices to sln --- X10D.sln | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/X10D.sln b/X10D.sln index 846b992..dd11b7d 100644 --- a/X10D.sln +++ b/X10D.sln @@ -47,6 +47,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tools", "Tools", "{4B8969E6 EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Benchmarks", "tools\Benchmarks\Benchmarks.csproj", "{259450A0-9964-403A-91E1-E9111B92C293}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "X10D.MetaServices", "tools\X10D.MetaServices\X10D.MetaServices.csproj", "{F57376C4-3591-43AF-BBED-447A1DE2B1FE}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -89,6 +91,10 @@ Global {259450A0-9964-403A-91E1-E9111B92C293}.Debug|Any CPU.Build.0 = Debug|Any CPU {259450A0-9964-403A-91E1-E9111B92C293}.Release|Any CPU.ActiveCfg = Release|Any CPU {259450A0-9964-403A-91E1-E9111B92C293}.Release|Any CPU.Build.0 = Release|Any CPU + {F57376C4-3591-43AF-BBED-447A1DE2B1FE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F57376C4-3591-43AF-BBED-447A1DE2B1FE}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F57376C4-3591-43AF-BBED-447A1DE2B1FE}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F57376C4-3591-43AF-BBED-447A1DE2B1FE}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -101,5 +107,6 @@ Global {CCBF047D-1B01-45EC-8D89-B00B4AC482CA} = {4B8969E6-27D2-4357-964E-9979FF7CC805} {259450A0-9964-403A-91E1-E9111B92C293} = {4B8969E6-27D2-4357-964E-9979FF7CC805} {077A5D33-AD55-4C55-8A67-972CEBC32C7A} = {4B8969E6-27D2-4357-964E-9979FF7CC805} + {F57376C4-3591-43AF-BBED-447A1DE2B1FE} = {4B8969E6-27D2-4357-964E-9979FF7CC805} EndGlobalSection EndGlobal From 420ec2433af0e2fbeb3543eddbd4d54e7e3a55aa Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Fri, 7 Apr 2023 01:21:56 +0100 Subject: [PATCH 023/102] feat: add Component move/copy As usual, experimental API - subject to change. --- CHANGELOG.md | 2 + .../Assets/Tests/ComponentTests.cs | 132 ++++++++++- .../Assets/Tests/GameObjectTests.cs | 197 ++++++++++++++++ X10D.Unity/X10D.Unity.csproj | 15 ++ X10D.Unity/src/ComponentExtensions.cs | 214 +++++++++++++++++- X10D.Unity/src/ExceptionMessages.Designer.cs | 80 +++++++ X10D.Unity/src/ExceptionMessages.resx | 34 +++ X10D.Unity/src/GameObjectExtensions.cs | 180 +++++++++++++++ 8 files changed, 852 insertions(+), 2 deletions(-) create mode 100644 X10D.Unity/src/ExceptionMessages.Designer.cs create mode 100644 X10D.Unity/src/ExceptionMessages.resx diff --git a/CHANGELOG.md b/CHANGELOG.md index 4de5308..343b6dd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - X10D: Added `TextWriter.WriteLineNoAlloc(uint[, ReadOnlySpan[, IFormatProvider]])`. - X10D: Added `TextWriter.WriteLineNoAlloc(long[, ReadOnlySpan[, IFormatProvider]])`. - X10D: Added `TextWriter.WriteLineNoAlloc(ulong[, ReadOnlySpan[, IFormatProvider]])`. +- X10D.Unity: Added `Component.CopyTo(GameObject)` and `Component.MoveTo(GameObject)`. +- X10D.Unity: Added `GameObject.CopyComponent(GameObject)` and `GameObject.MoveComponent(GameObject)`. ### Changed - X10D: `DateTime.Age(DateTime)` and `DateTimeOffset.Age(DateTimeOffset)` parameter renamed from `asOf` to `referenceDate`. diff --git a/X10D.Unity.Tests/Assets/Tests/ComponentTests.cs b/X10D.Unity.Tests/Assets/Tests/ComponentTests.cs index e6c1431..615f16e 100644 --- a/X10D.Unity.Tests/Assets/Tests/ComponentTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/ComponentTests.cs @@ -1,14 +1,77 @@ #nullable enable +using System; using System.Collections; using NUnit.Framework; using UnityEngine; using UnityEngine.TestTools; +using Object = UnityEngine.Object; namespace X10D.Unity.Tests { public class ComponentTests { + [UnityTest] + public IEnumerator CopyTo_ShouldCopyComponent_GivenComponent() + { + var source = new GameObject(); + var sourceComponent = source.AddComponent(); + sourceComponent.mass = 10.0f; + sourceComponent.useGravity = false; + + var target = new GameObject(); + sourceComponent.CopyTo(target); + + Assert.That(target.TryGetComponent(out Rigidbody targetComponent)); + Assert.That(targetComponent.mass, Is.EqualTo(10.0f)); + Assert.That(targetComponent.useGravity, Is.False); + + Object.Destroy(source); + Object.Destroy(target); + yield break; + } + + [UnityTest] + public IEnumerator CopyTo_ShouldThrowArgumentNullException_GivenNullComponent() + { + var target = new GameObject(); + Rigidbody rigidbody = null!; + + Assert.Throws(() => rigidbody.CopyTo(target)); + + Object.Destroy(target); + yield break; + } + + [UnityTest] + public IEnumerator CopyTo_ShouldThrowArgumentNullException_GivenNullTarget() + { + var source = new GameObject(); + var rigidbody = source.AddComponent(); + GameObject target = null!; + + Assert.Throws(() => rigidbody.CopyTo(target)); + + Object.Destroy(source); + yield break; + } + + [UnityTest] + public IEnumerator CopyTo_ShouldThrowInvalidOperationException_GivenDuplicate() + { + var source = new GameObject(); + var rigidbody = source.AddComponent(); + + var target = new GameObject(); + target.AddComponent(); + + Assert.Throws(() => rigidbody.CopyTo(target)); + + Object.Destroy(source); + Object.Destroy(target); + yield break; + } + [UnityTest] public IEnumerator GetComponentsInChildrenOnly_ShouldIgnoreParent() { @@ -16,13 +79,80 @@ namespace X10D.Unity.Tests var rigidbody = parent.AddComponent(); var child = new GameObject(); - child.transform.SetParent(parent.transform); child.AddComponent(); + yield return null; + Rigidbody[] components = rigidbody.GetComponentsInChildrenOnly(); Assert.That(components.Length, Is.EqualTo(1)); Assert.That(child, Is.EqualTo(components[0].gameObject)); + Object.Destroy(parent); + Object.Destroy(child); + } + + [UnityTest] + public IEnumerator MoveTo_ShouldCopyComponent_GivenComponent() + { + var source = new GameObject(); + var sourceComponent = source.AddComponent(); + sourceComponent.mass = 10f; + sourceComponent.useGravity = false; + + var target = new GameObject(); + sourceComponent.MoveTo(target); + + // effects of Destroy only take place at end of frame + yield return null; + + Assert.That(sourceComponent == null); + Assert.That(source.TryGetComponent(out Rigidbody _), Is.False); + Assert.That(target.TryGetComponent(out Rigidbody targetComponent)); + Assert.That(targetComponent.mass, Is.EqualTo(10.0f)); + Assert.That(targetComponent.useGravity, Is.False); + + Object.Destroy(source); + Object.Destroy(target); + } + + [UnityTest] + public IEnumerator MoveTo_ShouldThrowArgumentNullException_GivenNullComponent() + { + var target = new GameObject(); + Rigidbody rigidbody = null!; + + Assert.Throws(() => rigidbody.MoveTo(target)); + + Object.Destroy(target); + yield break; + } + + [UnityTest] + public IEnumerator MoveTo_ShouldThrowArgumentNullException_GivenNullTarget() + { + var source = new GameObject(); + var rigidbody = source.AddComponent(); + GameObject target = null!; + + Assert.Throws(() => rigidbody.MoveTo(target)); + + Object.Destroy(source); + yield break; + } + + [UnityTest] + public IEnumerator MoveTo_ShouldThrowInvalidOperationException_GivenDuplicate() + { + var source = new GameObject(); + var rigidbody = source.AddComponent(); + + var target = new GameObject(); + target.AddComponent(); + + Assert.Throws(() => rigidbody.MoveTo(target)); + + Object.Destroy(source); + Object.Destroy(target); yield break; } } diff --git a/X10D.Unity.Tests/Assets/Tests/GameObjectTests.cs b/X10D.Unity.Tests/Assets/Tests/GameObjectTests.cs index fef5a66..10ab455 100644 --- a/X10D.Unity.Tests/Assets/Tests/GameObjectTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/GameObjectTests.cs @@ -1,14 +1,107 @@ #nullable enable +using System; using System.Collections; using NUnit.Framework; using UnityEngine; using UnityEngine.TestTools; +using Object = UnityEngine.Object; namespace X10D.Unity.Tests { public class GameObjectTests { + [UnityTest] + public IEnumerator CopyComponent_ShouldCopyComponent_GivenComponent() + { + var source = new GameObject(); + var sourceComponent = source.AddComponent(); + sourceComponent.mass = 10.0f; + sourceComponent.useGravity = false; + + var target = new GameObject(); + source.CopyComponent(target); + + Assert.That(target.TryGetComponent(out Rigidbody targetComponent)); + Assert.That(targetComponent.mass, Is.EqualTo(10.0f)); + Assert.That(targetComponent.useGravity, Is.False); + + Object.Destroy(source); + Object.Destroy(target); + yield break; + } + + [UnityTest] + public IEnumerator CopyComponent_ShouldThrowArgumentNullException_GivenNullComponentType() + { + var source = new GameObject(); + var target = new GameObject(); + Type componentType = null!; + + Assert.Throws(() => source.CopyComponent(componentType, target)); + + Object.Destroy(source); + Object.Destroy(target); + yield break; + } + + [UnityTest] + public IEnumerator CopyComponent_ShouldThrowArgumentNullException_GivenNullGameObject() + { + var target = new GameObject(); + GameObject source = null!; + + Assert.Throws(() => source.CopyComponent(target)); + Assert.Throws(() => source.CopyComponent(typeof(Rigidbody), target)); + + Object.Destroy(target); + yield break; + } + + [UnityTest] + public IEnumerator CopyComponent_ShouldThrowArgumentNullException_GivenNullTarget() + { + var source = new GameObject(); + GameObject target = null!; + + Assert.Throws(() => source.CopyComponent(target)); + Assert.Throws(() => source.CopyComponent(typeof(Rigidbody), target)); + + Object.Destroy(source); + yield break; + } + + [UnityTest] + public IEnumerator CopyComponent_ShouldThrowInvalidOperationException_GivenInvalidComponent() + { + var source = new GameObject(); + var target = new GameObject(); + + Assert.Throws(() => source.CopyComponent(target)); + Assert.Throws(() => source.CopyComponent(typeof(Rigidbody), target)); + + Object.Destroy(source); + Object.Destroy(target); + yield break; + } + + [UnityTest] + public IEnumerator CopyComponent_ShouldThrowInvalidOperationException_GivenDuplicate() + { + var source = new GameObject(); + source.AddComponent(); + + var target = new GameObject(); + target.AddComponent(); + + Assert.Throws(() => source.CopyComponent(target)); + Assert.Throws(() => source.CopyComponent(typeof(Rigidbody), target)); + + Object.Destroy(source); + Object.Destroy(target); + yield break; + } + [UnityTest] public IEnumerator GetComponentsInChildrenOnly_ShouldIgnoreParent() { @@ -23,6 +116,8 @@ namespace X10D.Unity.Tests Assert.That(components.Length, Is.EqualTo(1)); Assert.That(child, Is.EqualTo(components[0].gameObject)); + Object.Destroy(parent); + Object.Destroy(child); yield break; } @@ -58,6 +153,103 @@ namespace X10D.Unity.Tests first.LookAt(Vector3.right); Assert.That(firstTransform.rotation, Is.EqualTo(expected)); + Object.Destroy(first); + Object.Destroy(second); + yield break; + } + + [UnityTest] + public IEnumerator MoveComponent_ShouldCopyComponent_GivenComponent() + { + var source = new GameObject(); + var sourceComponent = source.AddComponent(); + sourceComponent.mass = 10.0f; + sourceComponent.useGravity = false; + + var target = new GameObject(); + source.MoveComponent(target); + + // effects of Destroy only take place at end of frame + yield return null; + + Assert.That(sourceComponent == null); + Assert.That(source.TryGetComponent(out Rigidbody _), Is.False); + Assert.That(target.TryGetComponent(out Rigidbody targetComponent)); + Assert.That(targetComponent.mass, Is.EqualTo(10.0f)); + Assert.That(targetComponent.useGravity, Is.False); + + Object.Destroy(source); + Object.Destroy(target); + } + + [UnityTest] + public IEnumerator MoveComponent_ShouldThrowArgumentNullException_GivenNullComponentType() + { + var source = new GameObject(); + var target = new GameObject(); + Type componentType = null!; + + Assert.Throws(() => source.MoveComponent(componentType, target)); + + Object.Destroy(source); + Object.Destroy(target); + yield break; + } + + [UnityTest] + public IEnumerator MoveComponent_ShouldThrowArgumentNullException_GivenNullGameObject() + { + var target = new GameObject(); + GameObject source = null!; + + Assert.Throws(() => source.MoveComponent(target)); + Assert.Throws(() => source.MoveComponent(typeof(Rigidbody), target)); + + Object.Destroy(target); + yield break; + } + + [UnityTest] + public IEnumerator MoveComponent_ShouldThrowArgumentNullException_GivenNullTarget() + { + var source = new GameObject(); + GameObject target = null!; + + Assert.Throws(() => source.MoveComponent(target)); + Assert.Throws(() => source.MoveComponent(typeof(Rigidbody), target)); + + Object.Destroy(source); + yield break; + } + + [UnityTest] + public IEnumerator MoveComponent_ShouldThrowInvalidOperationException_GivenInvalidComponent() + { + var source = new GameObject(); + var target = new GameObject(); + + Assert.Throws(() => source.MoveComponent(target)); + Assert.Throws(() => source.MoveComponent(typeof(Rigidbody), target)); + + Object.Destroy(source); + Object.Destroy(target); + yield break; + } + + [UnityTest] + public IEnumerator MoveComponent_ShouldThrowInvalidOperationException_GivenDuplicate() + { + var source = new GameObject(); + source.AddComponent(); + + var target = new GameObject(); + target.AddComponent(); + + Assert.Throws(() => source.MoveComponent(target)); + Assert.Throws(() => source.MoveComponent(typeof(Rigidbody), target)); + + Object.Destroy(source); + Object.Destroy(target); yield break; } @@ -82,6 +274,9 @@ namespace X10D.Unity.Tests Assert.That(child.layer, Is.EqualTo(layer)); Assert.That(grandChild.layer, Is.EqualTo(layer)); + Object.Destroy(parent); + Object.Destroy(child); + Object.Destroy(grandChild); yield break; } @@ -103,6 +298,8 @@ namespace X10D.Unity.Tests second.SetParent(first); Assert.That(second.transform.parent, Is.EqualTo(first.transform)); + Object.Destroy(first); + Object.Destroy(second); yield break; } } diff --git a/X10D.Unity/X10D.Unity.csproj b/X10D.Unity/X10D.Unity.csproj index f99bf2e..90caf27 100644 --- a/X10D.Unity/X10D.Unity.csproj +++ b/X10D.Unity/X10D.Unity.csproj @@ -70,4 +70,19 @@ + + + ResXFileCodeGenerator + ExceptionMessages.Designer.cs + + + + + + True + True + ExceptionMessages.resx + + + diff --git a/X10D.Unity/src/ComponentExtensions.cs b/X10D.Unity/src/ComponentExtensions.cs index 6ad7388..93afe4d 100644 --- a/X10D.Unity/src/ComponentExtensions.cs +++ b/X10D.Unity/src/ComponentExtensions.cs @@ -1,4 +1,7 @@ -using UnityEngine; +using System.Globalization; +using System.Reflection; +using UnityEngine; +using Object = UnityEngine.Object; namespace X10D.Unity; @@ -7,6 +10,95 @@ namespace X10D.Unity; /// public static class ComponentExtensions { + /// + /// Copies the component to another game object. + /// + /// The component to copy. + /// The game object to which the component will be copied. + /// The type of the component to copy. + /// + /// is . + /// -or- + /// is . + /// + /// + /// already has a component of type . + /// + /// + /// This method will destroy the component on the source game object, creating a new instance on the target. Use with + /// caution. + /// + public static void CopyTo(this T component, GameObject target) + where T : Component + { + if (component == null) + { + throw new ArgumentNullException(nameof(component)); + } + + if (target == null) + { + throw new ArgumentNullException(nameof(target)); + } + + if (target.TryGetComponent(out T targetComponent)) + { + string message = ExceptionMessages.ComponentAlreadyExists; + message = string.Format(CultureInfo.CurrentCulture, message, target.name, typeof(T).Name); + throw new InvalidOperationException(message); + } + + targetComponent = target.AddComponent(); + + var typeInfo = typeof(T).GetTypeInfo(); + CopyFields(typeInfo, component, targetComponent); + CopyProperties(typeInfo, component, targetComponent); + } + + /// + /// Copies the component to another game object. + /// + /// The component to copy. + /// The game object to which the component will be copied. + /// + /// is . + /// -or- + /// is . + /// + /// + /// already has a component of the same type. + /// + /// + /// This method will destroy the component on the source game object, creating a new instance on the target. Use with + /// caution. + /// + public static void CopyTo(this Component component, GameObject target) + { + if (component == null) + { + throw new ArgumentNullException(nameof(component)); + } + + if (target == null) + { + throw new ArgumentNullException(nameof(target)); + } + + var componentType = component.GetType(); + if (target.TryGetComponent(componentType, out Component targetComponent)) + { + string message = ExceptionMessages.ComponentAlreadyExists; + message = string.Format(CultureInfo.CurrentCulture, message, target.name, componentType.Name); + throw new InvalidOperationException(message); + } + + targetComponent = target.AddComponent(componentType); + + var typeInfo = componentType.GetTypeInfo(); + CopyFields(typeInfo, component, targetComponent); + CopyProperties(typeInfo, component, targetComponent); + } + /// /// Returns an array of components of the specified type, excluding components that live on the object to which this /// component is attached. @@ -18,4 +110,124 @@ public static class ComponentExtensions { return component.gameObject.GetComponentsInChildrenOnly(); } + + /// + /// Moves the component to another game object. + /// + /// The component to move. + /// The game object to which the component will be moved. + /// The type of the component to move. + /// + /// is . + /// -or- + /// is . + /// + /// + /// already has a component of type . + /// + /// + /// This method will destroy the component on the source game object, creating a new instance on the target. Use with + /// caution. + /// + public static void MoveTo(this T component, GameObject target) + where T : Component + { + if (component == null) + { + throw new ArgumentNullException(nameof(component)); + } + + if (target == null) + { + throw new ArgumentNullException(nameof(target)); + } + + component.CopyTo(target); + Object.Destroy(component); + } + + /// + /// Moves the component to another game object. + /// + /// The component to move. + /// The game object to which the component will be moved. + /// + /// is . + /// -or- + /// is . + /// + /// + /// already has a component of the same type. + /// + /// + /// This method will destroy the component on the source game object, creating a new instance on the target. Use with + /// caution. + /// + public static void MoveTo(this Component component, GameObject target) + { + if (component == null) + { + throw new ArgumentNullException(nameof(component)); + } + + if (target == null) + { + throw new ArgumentNullException(nameof(target)); + } + + component.CopyTo(target); + Object.Destroy(component); + } + + private static void CopyFields(TypeInfo typeInfo, T component, T targetComponent) + where T : Component + { + foreach (FieldInfo field in typeInfo.DeclaredFields) + { + if (field.IsStatic) + { + continue; + } + + object fieldValue = GetNewReferences(component, targetComponent, field.GetValue(component)); + field.SetValue(targetComponent, fieldValue); + } + } + + private static void CopyProperties(TypeInfo typeInfo, T component, T targetComponent) + where T : Component + { + foreach (PropertyInfo property in typeInfo.DeclaredProperties) + { + if (!property.CanRead || !property.CanWrite) + { + continue; + } + + MethodInfo getMethod = property.GetMethod; + MethodInfo setMethod = property.SetMethod; + if (getMethod.IsStatic || setMethod.IsStatic) + { + continue; + } + + object propertyValue = GetNewReferences(component, targetComponent, property.GetValue(component)); + property.SetValue(targetComponent, propertyValue); + } + } + + private static object GetNewReferences(T component, T targetComponent, object value) + where T : Component + { + if (ReferenceEquals(value, component)) + { + value = targetComponent; + } + else if (ReferenceEquals(value, component.gameObject)) + { + value = targetComponent.gameObject; + } + + return value; + } } diff --git a/X10D.Unity/src/ExceptionMessages.Designer.cs b/X10D.Unity/src/ExceptionMessages.Designer.cs new file mode 100644 index 0000000..954a74a --- /dev/null +++ b/X10D.Unity/src/ExceptionMessages.Designer.cs @@ -0,0 +1,80 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace X10D.Unity { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class ExceptionMessages { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal ExceptionMessages() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("X10D.Unity.src.ExceptionMessages", typeof(ExceptionMessages).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Looks up a localized string similar to The game object {0} already has a component of type {1}.. + /// + internal static string ComponentAlreadyExists { + get { + return ResourceManager.GetString("ComponentAlreadyExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The game object {0} does not have a component of type {1}.. + /// + internal static string ComponentDoesNotExist { + get { + return ResourceManager.GetString("ComponentDoesNotExist", resourceCulture); + } + } + } +} diff --git a/X10D.Unity/src/ExceptionMessages.resx b/X10D.Unity/src/ExceptionMessages.resx new file mode 100644 index 0000000..ec27743 --- /dev/null +++ b/X10D.Unity/src/ExceptionMessages.resx @@ -0,0 +1,34 @@ + + + + + + + + + + text/microsoft-resx + + + 1.3 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, + PublicKeyToken=b77a5c561934e089 + + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, + PublicKeyToken=b77a5c561934e089 + + + + + The game object {0} does not have a component of type {1}. + + + + The game object {0} already has a component of type {1}. + + \ No newline at end of file diff --git a/X10D.Unity/src/GameObjectExtensions.cs b/X10D.Unity/src/GameObjectExtensions.cs index 97d03d3..1ede330 100644 --- a/X10D.Unity/src/GameObjectExtensions.cs +++ b/X10D.Unity/src/GameObjectExtensions.cs @@ -1,4 +1,6 @@ +using System.Globalization; using UnityEngine; +using Object = UnityEngine.Object; namespace X10D.Unity; @@ -7,6 +9,90 @@ namespace X10D.Unity; /// public static class GameObjectExtensions { + /// + /// Copies the component of the specified type from one game object to another. + /// + /// The game object from which to copy the component. + /// The game object to which the component will be copied. + /// The type of the component to copy. + /// + /// is . + /// -or- + /// is . + /// + /// + /// does not have a component of type . + /// -or- + /// already has a component of type . + /// + public static void CopyComponent(this GameObject gameObject, GameObject target) + where T : Component + { + if (gameObject == null) + { + throw new ArgumentNullException(nameof(gameObject)); + } + + if (target == null) + { + throw new ArgumentNullException(nameof(target)); + } + + if (!gameObject.TryGetComponent(out T sourceComponent)) + { + string message = ExceptionMessages.ComponentDoesNotExist; + message = string.Format(CultureInfo.CurrentCulture, message, gameObject.name, typeof(T).Name); + throw new InvalidOperationException(message); + } + + sourceComponent.CopyTo(target); + } + + /// + /// Copies the component of the specified type from one game object to another. + /// + /// The game object from which to copy the component. + /// The type of the component to copy. + /// The game object to which the component will be copied. + /// + /// is . + /// -or- + /// is . + /// -or- + /// is . + /// + /// + /// does not have a component of type . + /// -or- + /// already has a component of type . + /// + public static void CopyComponent(this GameObject gameObject, Type componentType, GameObject target) + { + if (gameObject == null) + { + throw new ArgumentNullException(nameof(gameObject)); + } + + if (componentType is null) + { + throw new ArgumentNullException(nameof(componentType)); + } + + if (target == null) + { + throw new ArgumentNullException(nameof(target)); + } + + if (!gameObject.TryGetComponent(componentType, out Component sourceComponent)) + { + string message = ExceptionMessages.ComponentDoesNotExist; + message = string.Format(CultureInfo.CurrentCulture, message, gameObject.name, componentType.Name); + throw new InvalidOperationException(message); + } + + sourceComponent.CopyTo(target); + } + /// /// Returns an array of components of the specified type, excluding components that live on this game object. /// @@ -171,6 +257,100 @@ public static class GameObjectExtensions gameObject.transform.LookAt(target, worldUp); } + /// + /// Moves the component of the specified type from one game object to another. + /// + /// The game object from which to move the component. + /// The game object to which the component will be moved. + /// The type of the component to copy. + /// + /// is . + /// -or- + /// is . + /// + /// + /// does not have a component of type . + /// -or- + /// already has a component of type . + /// + /// + /// This method will destroy the component on the source game object, creating a new instance on the target. Use with + /// caution. + /// + public static void MoveComponent(this GameObject gameObject, GameObject target) + where T : Component + { + if (gameObject == null) + { + throw new ArgumentNullException(nameof(gameObject)); + } + + if (target == null) + { + throw new ArgumentNullException(nameof(target)); + } + + if (!gameObject.TryGetComponent(out T sourceComponent)) + { + string message = ExceptionMessages.ComponentDoesNotExist; + message = string.Format(CultureInfo.CurrentCulture, message, gameObject.name, typeof(T).Name); + throw new InvalidOperationException(message); + } + + sourceComponent.MoveTo(target); + Object.Destroy(sourceComponent); + } + + /// + /// Moves the component of the specified type from one game object to another. + /// + /// The game object from which to move the component. + /// The type of the component to copy. + /// The game object to which the component will be moved. + /// + /// is . + /// -or- + /// is . + /// -or- + /// is . + /// + /// + /// does not have a component of type . + /// -or- + /// already has a component of type . + /// + /// + /// This method will destroy the component on the source game object, creating a new instance on the target. Use with + /// caution. + /// + public static void MoveComponent(this GameObject gameObject, Type componentType, GameObject target) + { + if (gameObject == null) + { + throw new ArgumentNullException(nameof(gameObject)); + } + + if (componentType is null) + { + throw new ArgumentNullException(nameof(componentType)); + } + + if (target == null) + { + throw new ArgumentNullException(nameof(target)); + } + + if (!gameObject.TryGetComponent(componentType, out Component sourceComponent)) + { + string message = ExceptionMessages.ComponentDoesNotExist; + message = string.Format(CultureInfo.CurrentCulture, message, gameObject.name, componentType.Name); + throw new InvalidOperationException(message); + } + + sourceComponent.MoveTo(target); + Object.Destroy(sourceComponent); + } + /// /// Sets the new layer of this game object and its children, recursively. /// From dc6d984fa865c2a82fa40fa41c2da7509c88adcc Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Fri, 7 Apr 2023 01:34:08 +0100 Subject: [PATCH 024/102] test: suppress ReSharper.Unity.InefficientPropertyAccess This is false positive being thrown by the analyzer. The values are - in fact - changing before being read each time. --- X10D.Unity.Tests/Assets/Tests/GameObjectTests.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/X10D.Unity.Tests/Assets/Tests/GameObjectTests.cs b/X10D.Unity.Tests/Assets/Tests/GameObjectTests.cs index 10ab455..c6b352a 100644 --- a/X10D.Unity.Tests/Assets/Tests/GameObjectTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/GameObjectTests.cs @@ -2,6 +2,7 @@ using System; using System.Collections; +using System.Diagnostics.CodeAnalysis; using NUnit.Framework; using UnityEngine; using UnityEngine.TestTools; @@ -122,6 +123,7 @@ namespace X10D.Unity.Tests } [UnityTest] + [SuppressMessage("ReSharper", "Unity.InefficientPropertyAccess", Justification = "False positive.")] public IEnumerator LookAt_ShouldRotateSameAsTransform() { var first = new GameObject {transform = {position = Vector3.zero, rotation = Quaternion.identity}}; @@ -281,6 +283,7 @@ namespace X10D.Unity.Tests } [UnityTest] + [SuppressMessage("ReSharper", "Unity.InefficientPropertyAccess", Justification = "False positive.")] public IEnumerator SetParent_ShouldSetParent() { var first = new GameObject {transform = {position = Vector3.zero, rotation = Quaternion.identity}}; From ad2d33aa88c7c6178d9ae4ea735775f995d815d7 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Fri, 7 Apr 2023 01:34:34 +0100 Subject: [PATCH 025/102] style(test): use constraint API for length check --- X10D.Unity.Tests/Assets/Tests/ComponentTests.cs | 2 +- X10D.Unity.Tests/Assets/Tests/GameObjectTests.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/X10D.Unity.Tests/Assets/Tests/ComponentTests.cs b/X10D.Unity.Tests/Assets/Tests/ComponentTests.cs index 615f16e..c1b30f5 100644 --- a/X10D.Unity.Tests/Assets/Tests/ComponentTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/ComponentTests.cs @@ -84,7 +84,7 @@ namespace X10D.Unity.Tests yield return null; Rigidbody[] components = rigidbody.GetComponentsInChildrenOnly(); - Assert.That(components.Length, Is.EqualTo(1)); + Assert.That(components, Has.Length.EqualTo(1)); Assert.That(child, Is.EqualTo(components[0].gameObject)); Object.Destroy(parent); diff --git a/X10D.Unity.Tests/Assets/Tests/GameObjectTests.cs b/X10D.Unity.Tests/Assets/Tests/GameObjectTests.cs index c6b352a..c555174 100644 --- a/X10D.Unity.Tests/Assets/Tests/GameObjectTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/GameObjectTests.cs @@ -114,7 +114,7 @@ namespace X10D.Unity.Tests child.AddComponent(); Rigidbody[] components = parent.GetComponentsInChildrenOnly(); - Assert.That(components.Length, Is.EqualTo(1)); + Assert.That(components, Has.Length.EqualTo(1)); Assert.That(child, Is.EqualTo(components[0].gameObject)); Object.Destroy(parent); From a4a1d3b13a28de5fcd15452b210c01e0a4d96a64 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Fri, 7 Apr 2023 13:09:07 +0100 Subject: [PATCH 026/102] fix: only copy Unity-serialized members --- X10D.Unity/src/ComponentExtensions.cs | 32 ++++++--------------------- 1 file changed, 7 insertions(+), 25 deletions(-) diff --git a/X10D.Unity/src/ComponentExtensions.cs b/X10D.Unity/src/ComponentExtensions.cs index 93afe4d..9a7dafc 100644 --- a/X10D.Unity/src/ComponentExtensions.cs +++ b/X10D.Unity/src/ComponentExtensions.cs @@ -1,6 +1,7 @@ using System.Globalization; using System.Reflection; using UnityEngine; +using X10D.Reflection; using Object = UnityEngine.Object; namespace X10D.Unity; @@ -52,7 +53,6 @@ public static class ComponentExtensions var typeInfo = typeof(T).GetTypeInfo(); CopyFields(typeInfo, component, targetComponent); - CopyProperties(typeInfo, component, targetComponent); } /// @@ -96,7 +96,6 @@ public static class ComponentExtensions var typeInfo = componentType.GetTypeInfo(); CopyFields(typeInfo, component, targetComponent); - CopyProperties(typeInfo, component, targetComponent); } /// @@ -184,7 +183,12 @@ public static class ComponentExtensions { foreach (FieldInfo field in typeInfo.DeclaredFields) { - if (field.IsStatic) + if (field.IsStatic || !field.IsPublic && !field.HasCustomAttribute()) + { + continue; + } + + if (field.HasCustomAttribute()) { continue; } @@ -194,28 +198,6 @@ public static class ComponentExtensions } } - private static void CopyProperties(TypeInfo typeInfo, T component, T targetComponent) - where T : Component - { - foreach (PropertyInfo property in typeInfo.DeclaredProperties) - { - if (!property.CanRead || !property.CanWrite) - { - continue; - } - - MethodInfo getMethod = property.GetMethod; - MethodInfo setMethod = property.SetMethod; - if (getMethod.IsStatic || setMethod.IsStatic) - { - continue; - } - - object propertyValue = GetNewReferences(component, targetComponent, property.GetValue(component)); - property.SetValue(targetComponent, propertyValue); - } - } - private static object GetNewReferences(T component, T targetComponent, object value) where T : Component { From f6847315a16fa4d422468adc160381aa78cae086 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Mon, 10 Apr 2023 12:44:53 +0100 Subject: [PATCH 027/102] feat: add Progress.OnProgressChanged Provides a mechanism to wrap the ProgressChanged event of a Progress as an IObservable. --- CHANGELOG.md | 3 + X10D.Tests/X10D.Tests.csproj | 1 + X10D.Tests/src/Reactive/ProgressTests.cs | 67 ++++++++++++++++ X10D/src/Reactive/ObservableDisposer.cs | 48 ++++++++++++ X10D/src/Reactive/ProgressExtensions.cs | 97 ++++++++++++++++++++++++ X10D/src/Reactive/ProgressObservable.cs | 40 ++++++++++ 6 files changed, 256 insertions(+) create mode 100644 X10D.Tests/src/Reactive/ProgressTests.cs create mode 100644 X10D/src/Reactive/ObservableDisposer.cs create mode 100644 X10D/src/Reactive/ProgressExtensions.cs create mode 100644 X10D/src/Reactive/ProgressObservable.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 343b6dd..643123d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,10 +8,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## 4.0.0 - [Unreleased] ### Added + - X10D: Added extension methods for `DateOnly`, for parity with `DateTime` and `DateTimeOffset`. - X10D: Added math-related extension methods for `BigInteger`. - X10D: Added `Span.Replace(T, T)`. - X10D: Added `CountDigits` for integer types. +- X10D: Added `Progress.OnProgressChanged([T])`; - X10D: Added `TextWriter.WriteNoAlloc(int[, ReadOnlySpan[, IFormatProvider]])`. - X10D: Added `TextWriter.WriteNoAlloc(uint[, ReadOnlySpan[, IFormatProvider]])`. - X10D: Added `TextWriter.WriteNoAlloc(long[, ReadOnlySpan[, IFormatProvider]])`. @@ -24,6 +26,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - X10D.Unity: Added `GameObject.CopyComponent(GameObject)` and `GameObject.MoveComponent(GameObject)`. ### Changed + - X10D: `DateTime.Age(DateTime)` and `DateTimeOffset.Age(DateTimeOffset)` parameter renamed from `asOf` to `referenceDate`. ## [3.2.0] - 2023-04-03 diff --git a/X10D.Tests/X10D.Tests.csproj b/X10D.Tests/X10D.Tests.csproj index d763c8c..00ea605 100644 --- a/X10D.Tests/X10D.Tests.csproj +++ b/X10D.Tests/X10D.Tests.csproj @@ -22,6 +22,7 @@ + diff --git a/X10D.Tests/src/Reactive/ProgressTests.cs b/X10D.Tests/src/Reactive/ProgressTests.cs new file mode 100644 index 0000000..fce2683 --- /dev/null +++ b/X10D.Tests/src/Reactive/ProgressTests.cs @@ -0,0 +1,67 @@ +using NUnit.Framework; +using X10D.Reactive; + +namespace X10D.Tests.Reactive; + +[TestFixture] +public class ProgressTests +{ + [Test] + public void OnProgressChanged_ShouldCallCompletionDelegate_GivenCompletionValue() + { + var subscriberWasCalled = false; + var completionWasCalled = false; + + var progress = new Progress(); + progress.OnProgressChanged(1.0f).Subscribe(_ => subscriberWasCalled = true, () => completionWasCalled = true); + + ((IProgress)progress).Report(0.5f); + ((IProgress)progress).Report(1.0f); + + Thread.Sleep(1000); + Assert.That(subscriberWasCalled); + Assert.That(completionWasCalled); + } + + [Test] + public void OnProgressChanged_ShouldCallSubscribers_OnProgressChanged() + { + var subscriberWasCalled = false; + + var progress = new Progress(); + progress.OnProgressChanged().Subscribe(_ => subscriberWasCalled = true); + + ((IProgress)progress).Report(0.5f); + + Thread.Sleep(1000); + Assert.That(subscriberWasCalled); + } + + [Test] + public void OnProgressChanged_ShouldCallSubscribers_OnProgressChanged_GivenCompletionValue() + { + var subscriberWasCalled = false; + + var progress = new Progress(); + progress.OnProgressChanged(1.0f).Subscribe(_ => subscriberWasCalled = true); + + ((IProgress)progress).Report(0.5f); + + Thread.Sleep(1000); + Assert.That(subscriberWasCalled); + } + + [Test] + public void OnProgressChanged_ShouldThrowArgumentNullException_GivenNullProgress() + { + Progress progress = null!; + Assert.Throws(() => progress.OnProgressChanged()); + } + + [Test] + public void OnProgressChanged_ShouldThrowArgumentNullException_GivenNullProgressAndCompletionValue() + { + Progress progress = null!; + Assert.Throws(() => progress.OnProgressChanged(1.0f)); + } +} diff --git a/X10D/src/Reactive/ObservableDisposer.cs b/X10D/src/Reactive/ObservableDisposer.cs new file mode 100644 index 0000000..9073ff9 --- /dev/null +++ b/X10D/src/Reactive/ObservableDisposer.cs @@ -0,0 +1,48 @@ +namespace X10D.Reactive; + +/// +/// Represents a disposable that removes an observer from a collection of observers. +/// +internal readonly struct ObservableDisposer : IDisposable +{ + private readonly HashSet> _observers; + private readonly IObserver _observer; + private readonly Action? _additionalAction; + + /// + /// Initializes a new instance of the struct. + /// + /// A collection of observers from which to remove the specified observer. + /// The observer to remove from the collection. + /// The additional action to run on dispose. + public ObservableDisposer(HashSet> observers, IObserver observer, Action? additionalAction) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(observers); + ArgumentNullException.ThrowIfNull(observer); +#else + if (observers is null) + { + throw new ArgumentNullException(nameof(observers)); + } + + if (observer is null) + { + throw new ArgumentNullException(nameof(observer)); + } +#endif + + _observers = observers; + _observer = observer; + _additionalAction = additionalAction; + } + + /// + /// Removes the observer from the collection of observers. + /// + public void Dispose() + { + _observers.Remove(_observer); + _additionalAction?.Invoke(); + } +} diff --git a/X10D/src/Reactive/ProgressExtensions.cs b/X10D/src/Reactive/ProgressExtensions.cs new file mode 100644 index 0000000..6128a72 --- /dev/null +++ b/X10D/src/Reactive/ProgressExtensions.cs @@ -0,0 +1,97 @@ +namespace X10D.Reactive; + +/// +/// Provides extension methods for . +/// +public static class ProgressExtensions +{ + /// + /// Wraps the event of the current in an + /// object. + /// + /// The progress whose event to wrap. + /// The type of progress update value. + /// + /// An object that wraps the event of the current + /// . + /// + /// is . + public static IObservable OnProgressChanged(this Progress progress) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(progress); +#else + if (progress is null) + { + throw new ArgumentNullException(nameof(progress)); + } +#endif + + var progressObservable = new ProgressObservable(); + + void ProgressChangedHandler(object? sender, T args) + { + IObserver[] observers = progressObservable.Observers; + + for (var index = 0; index < observers.Length; index++) + { + observers[index].OnNext(args); + } + } + + progress.ProgressChanged += ProgressChangedHandler; + progressObservable.OnDispose = () => progress.ProgressChanged -= ProgressChangedHandler; + + return progressObservable; + } + + /// + /// Wraps the event of the current in an + /// object, and completes the observable when the progress reaches the specified value. + /// + /// The progress whose event to wrap. + /// The value that indicates completion. + /// The type of progress update value. + /// + /// An object that wraps the event of the current + /// . + /// + /// is . + public static IObservable OnProgressChanged(this Progress progress, T completeValue) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(progress); +#else + if (progress is null) + { + throw new ArgumentNullException(nameof(progress)); + } +#endif + + var progressObservable = new ProgressObservable(); + var comparer = EqualityComparer.Default; + + void ProgressChangedHandler(object? sender, T args) + { + IObserver[] observers = progressObservable.Observers; + + for (var index = 0; index < observers.Length; index++) + { + observers[index].OnNext(args); + } + + if (comparer.Equals(args, completeValue)) + { + for (var index = 0; index < observers.Length; index++) + { + observers[index].OnCompleted(); + } + } + } + + progress.ProgressChanged += ProgressChangedHandler; + progressObservable.OnDispose = () => progress.ProgressChanged -= ProgressChangedHandler; + + return progressObservable; + } +} diff --git a/X10D/src/Reactive/ProgressObservable.cs b/X10D/src/Reactive/ProgressObservable.cs new file mode 100644 index 0000000..29a8243 --- /dev/null +++ b/X10D/src/Reactive/ProgressObservable.cs @@ -0,0 +1,40 @@ +namespace X10D.Reactive; + +/// +/// Represents a concrete implementation of that tracks progress of a . +/// +internal sealed class ProgressObservable : IObservable +{ + private readonly HashSet> _observers = new(); + + /// + /// Gets the observers. + /// + /// The observers. + public IObserver[] Observers + { + get => _observers.ToArray(); + } + + internal Action? OnDispose { get; set; } + + /// + /// Subscribes the specified observer to the progress tracker. + /// + /// The observer. + /// An object which can be disposed to unsubscribe from progress tracking. + public IDisposable Subscribe(IObserver observer) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(observer); +#else + if (observer is null) + { + throw new ArgumentNullException(nameof(observer)); + } +#endif + + _observers.Add(observer); + return new ObservableDisposer(_observers, observer, OnDispose); + } +} From 844f697754e80ce18ed7de3c575031e0aa58725b Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Mon, 10 Apr 2023 12:45:18 +0100 Subject: [PATCH 028/102] style: remove unused using directives --- X10D/src/Collections/SpanExtensions.cs | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/X10D/src/Collections/SpanExtensions.cs b/X10D/src/Collections/SpanExtensions.cs index 1aee61d..ac2fd2b 100644 --- a/X10D/src/Collections/SpanExtensions.cs +++ b/X10D/src/Collections/SpanExtensions.cs @@ -1,9 +1,4 @@ -#if NET5_0_OR_GREATER -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -#endif - -namespace X10D.Collections; +namespace X10D.Collections; /// /// Extension methods for and From 77ab429f72eed06c6f922e85c9089ecf25d4924d Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Mon, 10 Apr 2023 13:26:38 +0100 Subject: [PATCH 029/102] refactor: remove Copy/Move component functionality This may be returned at a later point. --- .../Assets/Tests/ComponentTests.cs | 127 ------------ .../Assets/Tests/GameObjectTests.cs | 187 ----------------- X10D.Unity/src/ComponentExtensions.cs | 196 +----------------- X10D.Unity/src/GameObjectExtensions.cs | 180 ---------------- 4 files changed, 1 insertion(+), 689 deletions(-) diff --git a/X10D.Unity.Tests/Assets/Tests/ComponentTests.cs b/X10D.Unity.Tests/Assets/Tests/ComponentTests.cs index c1b30f5..56c8dee 100644 --- a/X10D.Unity.Tests/Assets/Tests/ComponentTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/ComponentTests.cs @@ -1,6 +1,5 @@ #nullable enable -using System; using System.Collections; using NUnit.Framework; using UnityEngine; @@ -11,67 +10,6 @@ namespace X10D.Unity.Tests { public class ComponentTests { - [UnityTest] - public IEnumerator CopyTo_ShouldCopyComponent_GivenComponent() - { - var source = new GameObject(); - var sourceComponent = source.AddComponent(); - sourceComponent.mass = 10.0f; - sourceComponent.useGravity = false; - - var target = new GameObject(); - sourceComponent.CopyTo(target); - - Assert.That(target.TryGetComponent(out Rigidbody targetComponent)); - Assert.That(targetComponent.mass, Is.EqualTo(10.0f)); - Assert.That(targetComponent.useGravity, Is.False); - - Object.Destroy(source); - Object.Destroy(target); - yield break; - } - - [UnityTest] - public IEnumerator CopyTo_ShouldThrowArgumentNullException_GivenNullComponent() - { - var target = new GameObject(); - Rigidbody rigidbody = null!; - - Assert.Throws(() => rigidbody.CopyTo(target)); - - Object.Destroy(target); - yield break; - } - - [UnityTest] - public IEnumerator CopyTo_ShouldThrowArgumentNullException_GivenNullTarget() - { - var source = new GameObject(); - var rigidbody = source.AddComponent(); - GameObject target = null!; - - Assert.Throws(() => rigidbody.CopyTo(target)); - - Object.Destroy(source); - yield break; - } - - [UnityTest] - public IEnumerator CopyTo_ShouldThrowInvalidOperationException_GivenDuplicate() - { - var source = new GameObject(); - var rigidbody = source.AddComponent(); - - var target = new GameObject(); - target.AddComponent(); - - Assert.Throws(() => rigidbody.CopyTo(target)); - - Object.Destroy(source); - Object.Destroy(target); - yield break; - } - [UnityTest] public IEnumerator GetComponentsInChildrenOnly_ShouldIgnoreParent() { @@ -90,70 +28,5 @@ namespace X10D.Unity.Tests Object.Destroy(parent); Object.Destroy(child); } - - [UnityTest] - public IEnumerator MoveTo_ShouldCopyComponent_GivenComponent() - { - var source = new GameObject(); - var sourceComponent = source.AddComponent(); - sourceComponent.mass = 10f; - sourceComponent.useGravity = false; - - var target = new GameObject(); - sourceComponent.MoveTo(target); - - // effects of Destroy only take place at end of frame - yield return null; - - Assert.That(sourceComponent == null); - Assert.That(source.TryGetComponent(out Rigidbody _), Is.False); - Assert.That(target.TryGetComponent(out Rigidbody targetComponent)); - Assert.That(targetComponent.mass, Is.EqualTo(10.0f)); - Assert.That(targetComponent.useGravity, Is.False); - - Object.Destroy(source); - Object.Destroy(target); - } - - [UnityTest] - public IEnumerator MoveTo_ShouldThrowArgumentNullException_GivenNullComponent() - { - var target = new GameObject(); - Rigidbody rigidbody = null!; - - Assert.Throws(() => rigidbody.MoveTo(target)); - - Object.Destroy(target); - yield break; - } - - [UnityTest] - public IEnumerator MoveTo_ShouldThrowArgumentNullException_GivenNullTarget() - { - var source = new GameObject(); - var rigidbody = source.AddComponent(); - GameObject target = null!; - - Assert.Throws(() => rigidbody.MoveTo(target)); - - Object.Destroy(source); - yield break; - } - - [UnityTest] - public IEnumerator MoveTo_ShouldThrowInvalidOperationException_GivenDuplicate() - { - var source = new GameObject(); - var rigidbody = source.AddComponent(); - - var target = new GameObject(); - target.AddComponent(); - - Assert.Throws(() => rigidbody.MoveTo(target)); - - Object.Destroy(source); - Object.Destroy(target); - yield break; - } } } diff --git a/X10D.Unity.Tests/Assets/Tests/GameObjectTests.cs b/X10D.Unity.Tests/Assets/Tests/GameObjectTests.cs index c555174..dca113b 100644 --- a/X10D.Unity.Tests/Assets/Tests/GameObjectTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/GameObjectTests.cs @@ -1,6 +1,5 @@ #nullable enable -using System; using System.Collections; using System.Diagnostics.CodeAnalysis; using NUnit.Framework; @@ -12,97 +11,6 @@ namespace X10D.Unity.Tests { public class GameObjectTests { - [UnityTest] - public IEnumerator CopyComponent_ShouldCopyComponent_GivenComponent() - { - var source = new GameObject(); - var sourceComponent = source.AddComponent(); - sourceComponent.mass = 10.0f; - sourceComponent.useGravity = false; - - var target = new GameObject(); - source.CopyComponent(target); - - Assert.That(target.TryGetComponent(out Rigidbody targetComponent)); - Assert.That(targetComponent.mass, Is.EqualTo(10.0f)); - Assert.That(targetComponent.useGravity, Is.False); - - Object.Destroy(source); - Object.Destroy(target); - yield break; - } - - [UnityTest] - public IEnumerator CopyComponent_ShouldThrowArgumentNullException_GivenNullComponentType() - { - var source = new GameObject(); - var target = new GameObject(); - Type componentType = null!; - - Assert.Throws(() => source.CopyComponent(componentType, target)); - - Object.Destroy(source); - Object.Destroy(target); - yield break; - } - - [UnityTest] - public IEnumerator CopyComponent_ShouldThrowArgumentNullException_GivenNullGameObject() - { - var target = new GameObject(); - GameObject source = null!; - - Assert.Throws(() => source.CopyComponent(target)); - Assert.Throws(() => source.CopyComponent(typeof(Rigidbody), target)); - - Object.Destroy(target); - yield break; - } - - [UnityTest] - public IEnumerator CopyComponent_ShouldThrowArgumentNullException_GivenNullTarget() - { - var source = new GameObject(); - GameObject target = null!; - - Assert.Throws(() => source.CopyComponent(target)); - Assert.Throws(() => source.CopyComponent(typeof(Rigidbody), target)); - - Object.Destroy(source); - yield break; - } - - [UnityTest] - public IEnumerator CopyComponent_ShouldThrowInvalidOperationException_GivenInvalidComponent() - { - var source = new GameObject(); - var target = new GameObject(); - - Assert.Throws(() => source.CopyComponent(target)); - Assert.Throws(() => source.CopyComponent(typeof(Rigidbody), target)); - - Object.Destroy(source); - Object.Destroy(target); - yield break; - } - - [UnityTest] - public IEnumerator CopyComponent_ShouldThrowInvalidOperationException_GivenDuplicate() - { - var source = new GameObject(); - source.AddComponent(); - - var target = new GameObject(); - target.AddComponent(); - - Assert.Throws(() => source.CopyComponent(target)); - Assert.Throws(() => source.CopyComponent(typeof(Rigidbody), target)); - - Object.Destroy(source); - Object.Destroy(target); - yield break; - } - [UnityTest] public IEnumerator GetComponentsInChildrenOnly_ShouldIgnoreParent() { @@ -160,101 +68,6 @@ namespace X10D.Unity.Tests yield break; } - [UnityTest] - public IEnumerator MoveComponent_ShouldCopyComponent_GivenComponent() - { - var source = new GameObject(); - var sourceComponent = source.AddComponent(); - sourceComponent.mass = 10.0f; - sourceComponent.useGravity = false; - - var target = new GameObject(); - source.MoveComponent(target); - - // effects of Destroy only take place at end of frame - yield return null; - - Assert.That(sourceComponent == null); - Assert.That(source.TryGetComponent(out Rigidbody _), Is.False); - Assert.That(target.TryGetComponent(out Rigidbody targetComponent)); - Assert.That(targetComponent.mass, Is.EqualTo(10.0f)); - Assert.That(targetComponent.useGravity, Is.False); - - Object.Destroy(source); - Object.Destroy(target); - } - - [UnityTest] - public IEnumerator MoveComponent_ShouldThrowArgumentNullException_GivenNullComponentType() - { - var source = new GameObject(); - var target = new GameObject(); - Type componentType = null!; - - Assert.Throws(() => source.MoveComponent(componentType, target)); - - Object.Destroy(source); - Object.Destroy(target); - yield break; - } - - [UnityTest] - public IEnumerator MoveComponent_ShouldThrowArgumentNullException_GivenNullGameObject() - { - var target = new GameObject(); - GameObject source = null!; - - Assert.Throws(() => source.MoveComponent(target)); - Assert.Throws(() => source.MoveComponent(typeof(Rigidbody), target)); - - Object.Destroy(target); - yield break; - } - - [UnityTest] - public IEnumerator MoveComponent_ShouldThrowArgumentNullException_GivenNullTarget() - { - var source = new GameObject(); - GameObject target = null!; - - Assert.Throws(() => source.MoveComponent(target)); - Assert.Throws(() => source.MoveComponent(typeof(Rigidbody), target)); - - Object.Destroy(source); - yield break; - } - - [UnityTest] - public IEnumerator MoveComponent_ShouldThrowInvalidOperationException_GivenInvalidComponent() - { - var source = new GameObject(); - var target = new GameObject(); - - Assert.Throws(() => source.MoveComponent(target)); - Assert.Throws(() => source.MoveComponent(typeof(Rigidbody), target)); - - Object.Destroy(source); - Object.Destroy(target); - yield break; - } - - [UnityTest] - public IEnumerator MoveComponent_ShouldThrowInvalidOperationException_GivenDuplicate() - { - var source = new GameObject(); - source.AddComponent(); - - var target = new GameObject(); - target.AddComponent(); - - Assert.Throws(() => source.MoveComponent(target)); - Assert.Throws(() => source.MoveComponent(typeof(Rigidbody), target)); - - Object.Destroy(source); - Object.Destroy(target); - yield break; - } - [UnityTest] public IEnumerator SetLayerRecursively_ShouldSetLayerRecursively() { diff --git a/X10D.Unity/src/ComponentExtensions.cs b/X10D.Unity/src/ComponentExtensions.cs index 9a7dafc..6ad7388 100644 --- a/X10D.Unity/src/ComponentExtensions.cs +++ b/X10D.Unity/src/ComponentExtensions.cs @@ -1,8 +1,4 @@ -using System.Globalization; -using System.Reflection; -using UnityEngine; -using X10D.Reflection; -using Object = UnityEngine.Object; +using UnityEngine; namespace X10D.Unity; @@ -11,93 +7,6 @@ namespace X10D.Unity; /// public static class ComponentExtensions { - /// - /// Copies the component to another game object. - /// - /// The component to copy. - /// The game object to which the component will be copied. - /// The type of the component to copy. - /// - /// is . - /// -or- - /// is . - /// - /// - /// already has a component of type . - /// - /// - /// This method will destroy the component on the source game object, creating a new instance on the target. Use with - /// caution. - /// - public static void CopyTo(this T component, GameObject target) - where T : Component - { - if (component == null) - { - throw new ArgumentNullException(nameof(component)); - } - - if (target == null) - { - throw new ArgumentNullException(nameof(target)); - } - - if (target.TryGetComponent(out T targetComponent)) - { - string message = ExceptionMessages.ComponentAlreadyExists; - message = string.Format(CultureInfo.CurrentCulture, message, target.name, typeof(T).Name); - throw new InvalidOperationException(message); - } - - targetComponent = target.AddComponent(); - - var typeInfo = typeof(T).GetTypeInfo(); - CopyFields(typeInfo, component, targetComponent); - } - - /// - /// Copies the component to another game object. - /// - /// The component to copy. - /// The game object to which the component will be copied. - /// - /// is . - /// -or- - /// is . - /// - /// - /// already has a component of the same type. - /// - /// - /// This method will destroy the component on the source game object, creating a new instance on the target. Use with - /// caution. - /// - public static void CopyTo(this Component component, GameObject target) - { - if (component == null) - { - throw new ArgumentNullException(nameof(component)); - } - - if (target == null) - { - throw new ArgumentNullException(nameof(target)); - } - - var componentType = component.GetType(); - if (target.TryGetComponent(componentType, out Component targetComponent)) - { - string message = ExceptionMessages.ComponentAlreadyExists; - message = string.Format(CultureInfo.CurrentCulture, message, target.name, componentType.Name); - throw new InvalidOperationException(message); - } - - targetComponent = target.AddComponent(componentType); - - var typeInfo = componentType.GetTypeInfo(); - CopyFields(typeInfo, component, targetComponent); - } - /// /// Returns an array of components of the specified type, excluding components that live on the object to which this /// component is attached. @@ -109,107 +18,4 @@ public static class ComponentExtensions { return component.gameObject.GetComponentsInChildrenOnly(); } - - /// - /// Moves the component to another game object. - /// - /// The component to move. - /// The game object to which the component will be moved. - /// The type of the component to move. - /// - /// is . - /// -or- - /// is . - /// - /// - /// already has a component of type . - /// - /// - /// This method will destroy the component on the source game object, creating a new instance on the target. Use with - /// caution. - /// - public static void MoveTo(this T component, GameObject target) - where T : Component - { - if (component == null) - { - throw new ArgumentNullException(nameof(component)); - } - - if (target == null) - { - throw new ArgumentNullException(nameof(target)); - } - - component.CopyTo(target); - Object.Destroy(component); - } - - /// - /// Moves the component to another game object. - /// - /// The component to move. - /// The game object to which the component will be moved. - /// - /// is . - /// -or- - /// is . - /// - /// - /// already has a component of the same type. - /// - /// - /// This method will destroy the component on the source game object, creating a new instance on the target. Use with - /// caution. - /// - public static void MoveTo(this Component component, GameObject target) - { - if (component == null) - { - throw new ArgumentNullException(nameof(component)); - } - - if (target == null) - { - throw new ArgumentNullException(nameof(target)); - } - - component.CopyTo(target); - Object.Destroy(component); - } - - private static void CopyFields(TypeInfo typeInfo, T component, T targetComponent) - where T : Component - { - foreach (FieldInfo field in typeInfo.DeclaredFields) - { - if (field.IsStatic || !field.IsPublic && !field.HasCustomAttribute()) - { - continue; - } - - if (field.HasCustomAttribute()) - { - continue; - } - - object fieldValue = GetNewReferences(component, targetComponent, field.GetValue(component)); - field.SetValue(targetComponent, fieldValue); - } - } - - private static object GetNewReferences(T component, T targetComponent, object value) - where T : Component - { - if (ReferenceEquals(value, component)) - { - value = targetComponent; - } - else if (ReferenceEquals(value, component.gameObject)) - { - value = targetComponent.gameObject; - } - - return value; - } } diff --git a/X10D.Unity/src/GameObjectExtensions.cs b/X10D.Unity/src/GameObjectExtensions.cs index 1ede330..97d03d3 100644 --- a/X10D.Unity/src/GameObjectExtensions.cs +++ b/X10D.Unity/src/GameObjectExtensions.cs @@ -1,6 +1,4 @@ -using System.Globalization; using UnityEngine; -using Object = UnityEngine.Object; namespace X10D.Unity; @@ -9,90 +7,6 @@ namespace X10D.Unity; /// public static class GameObjectExtensions { - /// - /// Copies the component of the specified type from one game object to another. - /// - /// The game object from which to copy the component. - /// The game object to which the component will be copied. - /// The type of the component to copy. - /// - /// is . - /// -or- - /// is . - /// - /// - /// does not have a component of type . - /// -or- - /// already has a component of type . - /// - public static void CopyComponent(this GameObject gameObject, GameObject target) - where T : Component - { - if (gameObject == null) - { - throw new ArgumentNullException(nameof(gameObject)); - } - - if (target == null) - { - throw new ArgumentNullException(nameof(target)); - } - - if (!gameObject.TryGetComponent(out T sourceComponent)) - { - string message = ExceptionMessages.ComponentDoesNotExist; - message = string.Format(CultureInfo.CurrentCulture, message, gameObject.name, typeof(T).Name); - throw new InvalidOperationException(message); - } - - sourceComponent.CopyTo(target); - } - - /// - /// Copies the component of the specified type from one game object to another. - /// - /// The game object from which to copy the component. - /// The type of the component to copy. - /// The game object to which the component will be copied. - /// - /// is . - /// -or- - /// is . - /// -or- - /// is . - /// - /// - /// does not have a component of type . - /// -or- - /// already has a component of type . - /// - public static void CopyComponent(this GameObject gameObject, Type componentType, GameObject target) - { - if (gameObject == null) - { - throw new ArgumentNullException(nameof(gameObject)); - } - - if (componentType is null) - { - throw new ArgumentNullException(nameof(componentType)); - } - - if (target == null) - { - throw new ArgumentNullException(nameof(target)); - } - - if (!gameObject.TryGetComponent(componentType, out Component sourceComponent)) - { - string message = ExceptionMessages.ComponentDoesNotExist; - message = string.Format(CultureInfo.CurrentCulture, message, gameObject.name, componentType.Name); - throw new InvalidOperationException(message); - } - - sourceComponent.CopyTo(target); - } - /// /// Returns an array of components of the specified type, excluding components that live on this game object. /// @@ -257,100 +171,6 @@ public static class GameObjectExtensions gameObject.transform.LookAt(target, worldUp); } - /// - /// Moves the component of the specified type from one game object to another. - /// - /// The game object from which to move the component. - /// The game object to which the component will be moved. - /// The type of the component to copy. - /// - /// is . - /// -or- - /// is . - /// - /// - /// does not have a component of type . - /// -or- - /// already has a component of type . - /// - /// - /// This method will destroy the component on the source game object, creating a new instance on the target. Use with - /// caution. - /// - public static void MoveComponent(this GameObject gameObject, GameObject target) - where T : Component - { - if (gameObject == null) - { - throw new ArgumentNullException(nameof(gameObject)); - } - - if (target == null) - { - throw new ArgumentNullException(nameof(target)); - } - - if (!gameObject.TryGetComponent(out T sourceComponent)) - { - string message = ExceptionMessages.ComponentDoesNotExist; - message = string.Format(CultureInfo.CurrentCulture, message, gameObject.name, typeof(T).Name); - throw new InvalidOperationException(message); - } - - sourceComponent.MoveTo(target); - Object.Destroy(sourceComponent); - } - - /// - /// Moves the component of the specified type from one game object to another. - /// - /// The game object from which to move the component. - /// The type of the component to copy. - /// The game object to which the component will be moved. - /// - /// is . - /// -or- - /// is . - /// -or- - /// is . - /// - /// - /// does not have a component of type . - /// -or- - /// already has a component of type . - /// - /// - /// This method will destroy the component on the source game object, creating a new instance on the target. Use with - /// caution. - /// - public static void MoveComponent(this GameObject gameObject, Type componentType, GameObject target) - { - if (gameObject == null) - { - throw new ArgumentNullException(nameof(gameObject)); - } - - if (componentType is null) - { - throw new ArgumentNullException(nameof(componentType)); - } - - if (target == null) - { - throw new ArgumentNullException(nameof(target)); - } - - if (!gameObject.TryGetComponent(componentType, out Component sourceComponent)) - { - string message = ExceptionMessages.ComponentDoesNotExist; - message = string.Format(CultureInfo.CurrentCulture, message, gameObject.name, componentType.Name); - throw new InvalidOperationException(message); - } - - sourceComponent.MoveTo(target); - Object.Destroy(sourceComponent); - } - /// /// Sets the new layer of this game object and its children, recursively. /// From 0b5bb074c8b33746b56bd44ac2a565d2e8a797d0 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Mon, 10 Apr 2023 13:38:56 +0100 Subject: [PATCH 030/102] refactor(test): remove IEnumerator tests Use synchronous NUnit tests --- .../Assets/Tests/GameObjectTests.cs | 22 +++++++------------ 1 file changed, 8 insertions(+), 14 deletions(-) diff --git a/X10D.Unity.Tests/Assets/Tests/GameObjectTests.cs b/X10D.Unity.Tests/Assets/Tests/GameObjectTests.cs index dca113b..565d455 100644 --- a/X10D.Unity.Tests/Assets/Tests/GameObjectTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/GameObjectTests.cs @@ -1,18 +1,16 @@ #nullable enable -using System.Collections; using System.Diagnostics.CodeAnalysis; using NUnit.Framework; using UnityEngine; -using UnityEngine.TestTools; using Object = UnityEngine.Object; namespace X10D.Unity.Tests { public class GameObjectTests { - [UnityTest] - public IEnumerator GetComponentsInChildrenOnly_ShouldIgnoreParent() + [Test] + public void GetComponentsInChildrenOnly_ShouldIgnoreParent() { var parent = new GameObject(); parent.AddComponent(); @@ -27,12 +25,11 @@ namespace X10D.Unity.Tests Object.Destroy(parent); Object.Destroy(child); - yield break; } - [UnityTest] + [Test] [SuppressMessage("ReSharper", "Unity.InefficientPropertyAccess", Justification = "False positive.")] - public IEnumerator LookAt_ShouldRotateSameAsTransform() + public void LookAt_ShouldRotateSameAsTransform() { var first = new GameObject {transform = {position = Vector3.zero, rotation = Quaternion.identity}}; var second = new GameObject {transform = {position = Vector3.right, rotation = Quaternion.identity}}; @@ -65,11 +62,10 @@ namespace X10D.Unity.Tests Object.Destroy(first); Object.Destroy(second); - yield break; } - [UnityTest] - public IEnumerator SetLayerRecursively_ShouldSetLayerRecursively() + [Test] + public void SetLayerRecursively_ShouldSetLayerRecursively() { var parent = new GameObject(); var child = new GameObject(); @@ -92,12 +88,11 @@ namespace X10D.Unity.Tests Object.Destroy(parent); Object.Destroy(child); Object.Destroy(grandChild); - yield break; } - [UnityTest] + [Test] [SuppressMessage("ReSharper", "Unity.InefficientPropertyAccess", Justification = "False positive.")] - public IEnumerator SetParent_ShouldSetParent() + public void SetParent_ShouldSetParent() { var first = new GameObject {transform = {position = Vector3.zero, rotation = Quaternion.identity}}; var second = new GameObject {transform = {position = Vector3.right, rotation = Quaternion.identity}}; @@ -116,7 +111,6 @@ namespace X10D.Unity.Tests Object.Destroy(first); Object.Destroy(second); - yield break; } } } From a8ebe9c9021caf70003b3fffab35b7883cfca73f Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Mon, 10 Apr 2023 13:42:12 +0100 Subject: [PATCH 031/102] fix: fix issue with GetComponentsInChildrenOnly checking wrong Transform --- X10D.Unity/src/GameObjectExtensions.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/X10D.Unity/src/GameObjectExtensions.cs b/X10D.Unity/src/GameObjectExtensions.cs index 97d03d3..23d7f3c 100644 --- a/X10D.Unity/src/GameObjectExtensions.cs +++ b/X10D.Unity/src/GameObjectExtensions.cs @@ -15,6 +15,7 @@ public static class GameObjectExtensions /// An array representing the child components. public static T[] GetComponentsInChildrenOnly(this GameObject gameObject) { + Transform rootTransform = gameObject.transform; var components = new List(gameObject.GetComponentsInChildren()); for (var index = 0; index < components.Count; index++) @@ -26,7 +27,7 @@ public static class GameObjectExtensions continue; } - if (childComponent.transform.parent != gameObject.transform) + if (childComponent.transform == rootTransform) { components.RemoveAt(index); index--; From f4d6c9083b5f3cce4ee35401c08c7e15a405444b Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Mon, 10 Apr 2023 13:44:37 +0100 Subject: [PATCH 032/102] refactor(test): remove lingering IEnumerator test Remant from 0b5bb074c8b33746b56bd44ac2a565d2e8a797d0 --- X10D.Unity.Tests/Assets/Tests/ComponentTests.cs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/X10D.Unity.Tests/Assets/Tests/ComponentTests.cs b/X10D.Unity.Tests/Assets/Tests/ComponentTests.cs index 56c8dee..b7e4c69 100644 --- a/X10D.Unity.Tests/Assets/Tests/ComponentTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/ComponentTests.cs @@ -10,8 +10,8 @@ namespace X10D.Unity.Tests { public class ComponentTests { - [UnityTest] - public IEnumerator GetComponentsInChildrenOnly_ShouldIgnoreParent() + [Test] + public void GetComponentsInChildrenOnly_ShouldIgnoreParent() { var parent = new GameObject(); var rigidbody = parent.AddComponent(); @@ -19,8 +19,6 @@ namespace X10D.Unity.Tests var child = new GameObject(); child.AddComponent(); - yield return null; - Rigidbody[] components = rigidbody.GetComponentsInChildrenOnly(); Assert.That(components, Has.Length.EqualTo(1)); Assert.That(child, Is.EqualTo(components[0].gameObject)); From 98cd96d5cbf1b57ea026e3c9afed533e5bde00f1 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Mon, 10 Apr 2023 13:45:39 +0100 Subject: [PATCH 033/102] fix(test): fix malformed test The child was not being assigned a new parent, causing GetComponentsInChildrenOnly to return empty array and the subsequent line: Assert.That(components, Has.Length.EqualTo(1)); was resulting in a test fail. --- X10D.Unity.Tests/Assets/Tests/ComponentTests.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/X10D.Unity.Tests/Assets/Tests/ComponentTests.cs b/X10D.Unity.Tests/Assets/Tests/ComponentTests.cs index b7e4c69..126e435 100644 --- a/X10D.Unity.Tests/Assets/Tests/ComponentTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/ComponentTests.cs @@ -17,6 +17,7 @@ namespace X10D.Unity.Tests var rigidbody = parent.AddComponent(); var child = new GameObject(); + child.transform.SetParent(parent.transform); child.AddComponent(); Rigidbody[] components = rigidbody.GetComponentsInChildrenOnly(); From b2e4092ca7b77716624fff679dba0ab8588941bd Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Mon, 10 Apr 2023 13:50:44 +0100 Subject: [PATCH 034/102] [ci skip] docs: remove addition of component copy/move --- CHANGELOG.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 643123d..6cdf854 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,8 +22,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - X10D: Added `TextWriter.WriteLineNoAlloc(uint[, ReadOnlySpan[, IFormatProvider]])`. - X10D: Added `TextWriter.WriteLineNoAlloc(long[, ReadOnlySpan[, IFormatProvider]])`. - X10D: Added `TextWriter.WriteLineNoAlloc(ulong[, ReadOnlySpan[, IFormatProvider]])`. -- X10D.Unity: Added `Component.CopyTo(GameObject)` and `Component.MoveTo(GameObject)`. -- X10D.Unity: Added `GameObject.CopyComponent(GameObject)` and `GameObject.MoveComponent(GameObject)`. ### Changed From ac499537ed0ae381e12a5b983d1047442ccdf2b3 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Tue, 11 Apr 2023 16:58:16 +0100 Subject: [PATCH 035/102] feat: add RaycastHit.GetComponent and RaycastHit.TryGetComponent --- CHANGELOG.md | 1 + X10D.Unity/src/RaycastHitExtensions.cs | 109 +++++++++++++++++++++++++ 2 files changed, 110 insertions(+) create mode 100644 X10D.Unity/src/RaycastHitExtensions.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 6cdf854..5ea3856 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - X10D: Added `TextWriter.WriteLineNoAlloc(uint[, ReadOnlySpan[, IFormatProvider]])`. - X10D: Added `TextWriter.WriteLineNoAlloc(long[, ReadOnlySpan[, IFormatProvider]])`. - X10D: Added `TextWriter.WriteLineNoAlloc(ulong[, ReadOnlySpan[, IFormatProvider]])`. +- X10D.Unity: Added `RaycastHit.GetComponent` and `RaycastHit.TryGetComponent`. ### Changed diff --git a/X10D.Unity/src/RaycastHitExtensions.cs b/X10D.Unity/src/RaycastHitExtensions.cs new file mode 100644 index 0000000..5e44dca --- /dev/null +++ b/X10D.Unity/src/RaycastHitExtensions.cs @@ -0,0 +1,109 @@ +using System.Diagnostics.CodeAnalysis; +using UnityEngine; + +namespace X10D.Unity; + +/// +/// Extension methods for . +/// +public static class RaycastHitExtensions +{ + /// + /// Gets the component of the specified type from the object that was hit by the raycast. + /// + /// The raycast hit. + /// The type of the component to retrieve. + /// + /// The component of the specified type from the object that was hit by the raycast, or if no + /// component of the specified type was found. + /// + public static T? GetComponent(this RaycastHit hit) + { + if (hit.transform == null) + { + return default; + } + + return hit.transform.GetComponent(); + } + + /// + /// Gets the component of the specified type from the object that was hit by the raycast. + /// + /// The raycast hit. + /// The type of the component to retrieve. + /// + /// The component of the specified type from the object that was hit by the raycast, or if no + /// component of the specified type was found. + /// + /// is . + public static Component? GetComponent(this RaycastHit hit, Type componentType) + { + if (componentType is null) + { + throw new ArgumentNullException(nameof(componentType)); + } + + if (hit.transform == null) + { + return default; + } + + return hit.transform.GetComponent(componentType); + } + + + /// + /// Attempts to get the component of the specified type from the object that was hit by the raycast, and returns a value + /// that indicates whether the operation succeeded. + /// + /// The raycast hit. + /// + /// When this method returns, contains the component of the specified type from the object that was hit by the raycast, or + /// if no component of the specified type was found. + /// + /// The type of the component to retrieve. + /// + /// if the component of the specified type was found; otherwise, . + /// + public static bool TryGetComponent(this RaycastHit hit, [NotNullWhen(true)] out T? component) + { + if (hit.transform == null) + { + component = default; + return false; + } + + return hit.transform.TryGetComponent(out component); + } + + /// + /// Attempts to get the component of the specified type from the object that was hit by the raycast, and returns a value + /// that indicates whether the operation succeeded. + /// + /// The raycast hit. + /// The type of the component to retrieve. + /// + /// When this method returns, contains the component of the specified type from the object that was hit by the raycast, or + /// if no component of the specified type was found. + /// + /// + /// if the component of the specified type was found; otherwise, . + /// + /// is . + public static bool TryGetComponent(this RaycastHit hit, Type componentType, [NotNullWhen(true)] out Component? component) + { + if (componentType is null) + { + throw new ArgumentNullException(nameof(componentType)); + } + + if (hit.transform == null) + { + component = default; + return false; + } + + return hit.transform.TryGetComponent(componentType, out component); + } +} From 5ff521073cdcef13f45f529009fb782b7a7fe027 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Tue, 11 Apr 2023 17:04:09 +0100 Subject: [PATCH 036/102] fix: suppress CA5394 This analysis warning is irrelevant. We're making extension methods here, dammit! This will be the consumer's responsibility to worry about. --- X10D.Unity/src/Drawing/RandomExtensions.cs | 2 ++ X10D.Unity/src/Numerics/RandomExtensions.cs | 2 ++ 2 files changed, 4 insertions(+) diff --git a/X10D.Unity/src/Drawing/RandomExtensions.cs b/X10D.Unity/src/Drawing/RandomExtensions.cs index 2e90807..c8b4bd7 100644 --- a/X10D.Unity/src/Drawing/RandomExtensions.cs +++ b/X10D.Unity/src/Drawing/RandomExtensions.cs @@ -2,6 +2,8 @@ using X10D.Core; using Random = System.Random; +#pragma warning disable CA5394 + namespace X10D.Unity.Drawing; /// diff --git a/X10D.Unity/src/Numerics/RandomExtensions.cs b/X10D.Unity/src/Numerics/RandomExtensions.cs index 3b10b79..07b54a2 100644 --- a/X10D.Unity/src/Numerics/RandomExtensions.cs +++ b/X10D.Unity/src/Numerics/RandomExtensions.cs @@ -2,6 +2,8 @@ using X10D.Core; using Random = System.Random; +#pragma warning disable CA5394 + namespace X10D.Unity.Numerics; /// From 2e9f27b6b7a40bb4a80644b8b4108ca1369bc541 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Tue, 11 Apr 2023 17:05:58 +0100 Subject: [PATCH 037/102] fix: validate null arguments for Polygon and PolygonF extensions --- X10D.Unity/src/Drawing/PolygonExtensions.cs | 21 ++++++++++ X10D.Unity/src/Drawing/PolygonFExtensions.cs | 42 ++++++++++++++++++++ 2 files changed, 63 insertions(+) diff --git a/X10D.Unity/src/Drawing/PolygonExtensions.cs b/X10D.Unity/src/Drawing/PolygonExtensions.cs index 8a72df8..b1b962f 100644 --- a/X10D.Unity/src/Drawing/PolygonExtensions.cs +++ b/X10D.Unity/src/Drawing/PolygonExtensions.cs @@ -14,8 +14,14 @@ public static class PolygonExtensions /// /// The polygon whose points to update. /// The point to add. + /// is . public static void AddVertex(this Polygon polygon, Vector2Int point) { + if (polygon is null) + { + throw new ArgumentNullException(nameof(polygon)); + } + polygon.AddVertex(point.ToSystemPoint()); } @@ -24,8 +30,23 @@ public static class PolygonExtensions /// /// The polygon whose vertices to update. /// The vertices to add. + /// + /// is . + /// -or- + /// is . + /// public static void AddVertices(this Polygon polygon, IEnumerable vertices) { + if (polygon is null) + { + throw new ArgumentNullException(nameof(polygon)); + } + + if (vertices is null) + { + throw new ArgumentNullException(nameof(vertices)); + } + foreach (Vector2Int vertex in vertices) { polygon.AddVertex(vertex); diff --git a/X10D.Unity/src/Drawing/PolygonFExtensions.cs b/X10D.Unity/src/Drawing/PolygonFExtensions.cs index 0042904..1b91d0c 100644 --- a/X10D.Unity/src/Drawing/PolygonFExtensions.cs +++ b/X10D.Unity/src/Drawing/PolygonFExtensions.cs @@ -14,8 +14,14 @@ public static class PolygonFExtensions /// /// The polygon whose vertices to update. /// The vertex to add. + /// is . public static void AddVertex(this PolygonF polygon, Vector2Int vertex) { + if (polygon is null) + { + throw new ArgumentNullException(nameof(polygon)); + } + polygon.AddVertex(vertex.ToSystemPoint()); } @@ -24,8 +30,14 @@ public static class PolygonFExtensions /// /// The polygon whose vertices to update. /// The vertex to add. + /// is . public static void AddVertex(this PolygonF polygon, Vector2 vertex) { + if (polygon is null) + { + throw new ArgumentNullException(nameof(polygon)); + } + polygon.AddVertex(vertex.ToSystemPointF()); } @@ -34,8 +46,23 @@ public static class PolygonFExtensions /// /// The polygon whose vertices to update. /// The vertices to add. + /// + /// is . + /// -or- + /// is . + /// public static void AddVertices(this PolygonF polygon, IEnumerable vertices) { + if (polygon is null) + { + throw new ArgumentNullException(nameof(polygon)); + } + + if (vertices is null) + { + throw new ArgumentNullException(nameof(vertices)); + } + foreach (Vector2Int vertex in vertices) { polygon.AddVertex(vertex); @@ -47,8 +74,23 @@ public static class PolygonFExtensions /// /// The polygon whose vertices to update. /// The vertices to add. + /// + /// is . + /// -or- + /// is . + /// public static void AddVertices(this PolygonF polygon, IEnumerable vertices) { + if (polygon is null) + { + throw new ArgumentNullException(nameof(polygon)); + } + + if (vertices is null) + { + throw new ArgumentNullException(nameof(vertices)); + } + foreach (Vector2 vertex in vertices) { polygon.AddVertex(vertex); From e6025b1a4cd6a188a358c150ec3e2e43bf835733 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Tue, 11 Apr 2023 17:09:14 +0100 Subject: [PATCH 038/102] fix: validate null arguments in X10D.Unity The CA runs are really testing me today. --- X10D.Unity/src/ComponentExtensions.cs | 6 +++ .../src/Drawing/PolyhedronExtensions.cs | 42 +++++++++++++++++++ X10D.Unity/src/GameObjectExtensions.cs | 6 +++ 3 files changed, 54 insertions(+) diff --git a/X10D.Unity/src/ComponentExtensions.cs b/X10D.Unity/src/ComponentExtensions.cs index 6ad7388..01d0a27 100644 --- a/X10D.Unity/src/ComponentExtensions.cs +++ b/X10D.Unity/src/ComponentExtensions.cs @@ -14,8 +14,14 @@ public static class ComponentExtensions /// The component whose child components to retrieve. /// The type of the components to retrieve. /// An array representing the child components. + /// is . public static T[] GetComponentsInChildrenOnly(this Component component) { + if (component == null) + { + throw new ArgumentNullException(nameof(component)); + } + return component.gameObject.GetComponentsInChildrenOnly(); } } diff --git a/X10D.Unity/src/Drawing/PolyhedronExtensions.cs b/X10D.Unity/src/Drawing/PolyhedronExtensions.cs index 108b9a8..94cd4ed 100644 --- a/X10D.Unity/src/Drawing/PolyhedronExtensions.cs +++ b/X10D.Unity/src/Drawing/PolyhedronExtensions.cs @@ -14,8 +14,14 @@ public static class PolyhedronExtensions /// /// The polyhedron whose vertices to update. /// The vertex to add. + /// is . public static void AddVertex(this Polyhedron polyhedron, Vector3Int vertex) { + if (polyhedron is null) + { + throw new ArgumentNullException(nameof(polyhedron)); + } + polyhedron.AddVertex(vertex.ToSystemVector()); } @@ -24,8 +30,14 @@ public static class PolyhedronExtensions /// /// The polyhedron whose vertices to update. /// The vertex to add. + /// is . public static void AddVertex(this Polyhedron polyhedron, Vector3 vertex) { + if (polyhedron is null) + { + throw new ArgumentNullException(nameof(polyhedron)); + } + polyhedron.AddVertex(vertex.ToSystemVector()); } @@ -34,8 +46,23 @@ public static class PolyhedronExtensions /// /// The polyhedron whose vertices to update. /// The vertices to add. + /// + /// is . + /// -or- + /// is . + /// public static void AddVertices(this Polyhedron polyhedron, IEnumerable vertices) { + if (polyhedron is null) + { + throw new ArgumentNullException(nameof(polyhedron)); + } + + if (vertices is null) + { + throw new ArgumentNullException(nameof(vertices)); + } + foreach (Vector3Int vertex in vertices) { polyhedron.AddVertex(vertex); @@ -47,8 +74,23 @@ public static class PolyhedronExtensions /// /// The polyhedron whose vertices to update. /// The vertices to add. + /// + /// is . + /// -or- + /// is . + /// public static void AddVertices(this Polyhedron polyhedron, IEnumerable vertices) { + if (polyhedron is null) + { + throw new ArgumentNullException(nameof(polyhedron)); + } + + if (vertices is null) + { + throw new ArgumentNullException(nameof(vertices)); + } + foreach (Vector3 vertex in vertices) { polyhedron.AddVertex(vertex); diff --git a/X10D.Unity/src/GameObjectExtensions.cs b/X10D.Unity/src/GameObjectExtensions.cs index 23d7f3c..559ee39 100644 --- a/X10D.Unity/src/GameObjectExtensions.cs +++ b/X10D.Unity/src/GameObjectExtensions.cs @@ -13,8 +13,14 @@ public static class GameObjectExtensions /// The game object whose child components to retrieve. /// The type of the components to retrieve. /// An array representing the child components. + /// is . public static T[] GetComponentsInChildrenOnly(this GameObject gameObject) { + if (gameObject == null) + { + throw new ArgumentNullException(nameof(gameObject)); + } + Transform rootTransform = gameObject.transform; var components = new List(gameObject.GetComponentsInChildren()); From f13907a4d069fb50127ca60d2f0b4d08edb4ee7c Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Tue, 11 Apr 2023 22:23:12 +0100 Subject: [PATCH 039/102] style: move Write/WriteLine overloads to files This change should help to organise this entire class a bit better, due to the number of overloads that exist. --- ...WriterExtensions.WriteLineNoAlloc.Int32.cs | 83 +++ ...WriterExtensions.WriteLineNoAlloc.Int64.cs | 85 +++ ...riterExtensions.WriteLineNoAlloc.UInt32.cs | 88 +++ ...riterExtensions.WriteLineNoAlloc.UInt64.cs | 88 +++ ...TextWriterExtensions.WriteNoAlloc.Int32.cs | 92 +++ ...TextWriterExtensions.WriteNoAlloc.Int64.cs | 95 +++ ...extWriterExtensions.WriteNoAlloc.UInt32.cs | 98 +++ ...extWriterExtensions.WriteNoAlloc.UInt64.cs | 98 +++ X10D/src/IO/TextWriterExtensions.cs | 681 +----------------- 9 files changed, 729 insertions(+), 679 deletions(-) create mode 100644 X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.Int32.cs create mode 100644 X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.Int64.cs create mode 100644 X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.UInt32.cs create mode 100644 X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.UInt64.cs create mode 100644 X10D/src/IO/TextWriterExtensions.WriteNoAlloc.Int32.cs create mode 100644 X10D/src/IO/TextWriterExtensions.WriteNoAlloc.Int64.cs create mode 100644 X10D/src/IO/TextWriterExtensions.WriteNoAlloc.UInt32.cs create mode 100644 X10D/src/IO/TextWriterExtensions.WriteNoAlloc.UInt64.cs diff --git a/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.Int32.cs b/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.Int32.cs new file mode 100644 index 0000000..8836d63 --- /dev/null +++ b/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.Int32.cs @@ -0,0 +1,83 @@ +using System.Globalization; + +namespace X10D.IO; + +public static partial class TextWriterExtensions +{ + /// + /// Writes the text representation of a 4-byte signed integer to the text stream, followed by a line terminator, without + /// allocating a string. + /// + /// The to write to. + /// The 4-byte signed integer to write. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + public static void WriteLineNoAlloc(this TextWriter writer, int value) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + writer.WriteLineNoAlloc(value, "N0".AsSpan(), CultureInfo.CurrentCulture); + } + + /// + /// Writes the text representation of a 4-byte signed integer to the text stream, followed by a line terminator, without + /// allocating a string. + /// + /// The to write to. + /// The 4-byte signed integer to write. + /// A standard or custom numeric format string. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + public static void WriteLineNoAlloc(this TextWriter writer, int value, ReadOnlySpan format) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + WriteLineNoAlloc(writer, (long)value, format, CultureInfo.CurrentCulture); + } + + /// + /// Writes the text representation of a 4-byte signed integer to the text stream, followed by a line terminator, without + /// allocating a string. + /// + /// The to write to. + /// The 4-byte signed integer to write. + /// A standard or custom numeric format string. + /// An object that supplies culture-specific formatting information. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + public static void WriteLineNoAlloc(this TextWriter writer, int value, ReadOnlySpan format, + IFormatProvider? formatProvider) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + writer.WriteNoAlloc(value, format, formatProvider); + writer.WriteLine(); + } +} diff --git a/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.Int64.cs b/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.Int64.cs new file mode 100644 index 0000000..83deadd --- /dev/null +++ b/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.Int64.cs @@ -0,0 +1,85 @@ +using System.Globalization; + +namespace X10D.IO; + +public static partial class TextWriterExtensions +{ + /// + /// Writes the text representation of an 8-byte signed integer to the text stream, followed by a line terminator, without + /// allocating a string. + /// + /// The to write to. + /// The 8-byte signed integer to write. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + public static void WriteLineNoAlloc(this TextWriter writer, long value) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + writer.WriteLineNoAlloc(value, "N0".AsSpan(), CultureInfo.CurrentCulture); + } + + /// + /// Writes the text representation of an 8-byte signed integer to the text stream, followed by a line terminator, without + /// allocating a string. + /// + /// The to write to. + /// The 8-byte signed integer to write. + /// A standard or custom numeric format string. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + public static void WriteLineNoAlloc(this TextWriter writer, long value, ReadOnlySpan format) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + writer.WriteLineNoAlloc(value, format, CultureInfo.CurrentCulture); + } + + /// + /// Writes the text representation of an 8-byte signed integer to the text stream, followed by a line terminator, without + /// allocating a string. + /// + /// The to write to. + /// The 8-byte signed integer to write. + /// A standard or custom numeric format string. + /// An object that supplies culture-specific formatting information. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + public static void WriteLineNoAlloc(this TextWriter writer, + long value, + ReadOnlySpan format, + IFormatProvider? formatProvider) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + writer.WriteNoAlloc(value, format, formatProvider); + writer.WriteLine(); + } +} diff --git a/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.UInt32.cs b/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.UInt32.cs new file mode 100644 index 0000000..98e9d42 --- /dev/null +++ b/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.UInt32.cs @@ -0,0 +1,88 @@ +using System.Globalization; + +namespace X10D.IO; + +public static partial class TextWriterExtensions +{ + /// + /// Writes the text representation of a 4-byte unsigned integer to the text stream, followed by a line terminator, without + /// allocating a string. + /// + /// The to write to. + /// The 4-byte unsigned integer to write. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + [CLSCompliant(false)] + public static void WriteLineNoAlloc(this TextWriter writer, uint value) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + writer.WriteLineNoAlloc(value, "N0".AsSpan(), CultureInfo.CurrentCulture); + } + + /// + /// Writes the text representation of a 4-byte unsigned integer to the text stream, followed by a line terminator, without + /// allocating a string. + /// + /// The to write to. + /// The 4-byte unsigned integer to write. + /// A standard or custom numeric format string. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + [CLSCompliant(false)] + public static void WriteLineNoAlloc(this TextWriter writer, uint value, ReadOnlySpan format) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + WriteLineNoAlloc(writer, (long)value, format, CultureInfo.CurrentCulture); + } + + /// + /// Writes the text representation of a 4-byte unsigned integer to the text stream, followed by a line terminator, without + /// allocating a string. + /// + /// The to write to. + /// The 4-byte unsigned integer to write. + /// A standard or custom numeric format string. + /// An object that supplies culture-specific formatting information. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + [CLSCompliant(false)] + public static void WriteLineNoAlloc(this TextWriter writer, + uint value, + ReadOnlySpan format, + IFormatProvider? formatProvider) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + writer.WriteNoAlloc(value, format, formatProvider); + writer.WriteLine(); + } +} diff --git a/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.UInt64.cs b/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.UInt64.cs new file mode 100644 index 0000000..68f397f --- /dev/null +++ b/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.UInt64.cs @@ -0,0 +1,88 @@ +using System.Globalization; + +namespace X10D.IO; + +public static partial class TextWriterExtensions +{ + /// + /// Writes the text representation of an 8-byte unsigned integer to the text stream, followed by a line terminator, + /// without allocating a string. + /// + /// The to write to. + /// The 8-byte unsigned integer to write. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + [CLSCompliant(false)] + public static void WriteLineNoAlloc(this TextWriter writer, ulong value) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + writer.WriteLineNoAlloc(value, "N0".AsSpan(), CultureInfo.CurrentCulture); + } + + /// + /// Writes the text representation of an 8-byte unsigned integer to the text stream, followed by a line terminator, + /// without allocating a string. + /// + /// The to write to. + /// The 8-byte unsigned integer to write. + /// A standard or custom numeric format string. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + [CLSCompliant(false)] + public static void WriteLineNoAlloc(this TextWriter writer, ulong value, ReadOnlySpan format) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + writer.WriteLineNoAlloc(value, format, CultureInfo.CurrentCulture); + } + + /// + /// Writes the text representation of an 8-byte unsigned integer to the text stream, followed by a line terminator, + /// without allocating a string. + /// + /// The to write to. + /// The 8-byte unsigned integer to write. + /// A standard or custom numeric format string. + /// An object that supplies culture-specific formatting information. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + [CLSCompliant(false)] + public static void WriteLineNoAlloc(this TextWriter writer, + ulong value, + ReadOnlySpan format, + IFormatProvider? formatProvider) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + writer.WriteNoAlloc(value, format, formatProvider); + writer.WriteLine(); + } +} diff --git a/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.Int32.cs b/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.Int32.cs new file mode 100644 index 0000000..c2366bf --- /dev/null +++ b/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.Int32.cs @@ -0,0 +1,92 @@ +using System.Globalization; +using X10D.Math; + +namespace X10D.IO; + +public static partial class TextWriterExtensions +{ + /// + /// Writes the text representation of a 4-byte signed integer to the text stream, without allocating a string. + /// + /// The to write to. + /// The 4-byte signed integer to write. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + public static void WriteNoAlloc(this TextWriter writer, int value) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + WriteNoAlloc(writer, value, "N0".AsSpan(), CultureInfo.CurrentCulture); + } + + /// + /// Writes the text representation of a 4-byte signed integer to the text stream, without allocating a string. + /// + /// The to write to. + /// The 4-byte signed integer to write. + /// A standard or custom numeric format string. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + public static void WriteNoAlloc(this TextWriter writer, int value, ReadOnlySpan format) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + WriteNoAlloc(writer, value, format, CultureInfo.CurrentCulture); + } + + /// + /// Writes the text representation of a 4-byte signed integer to the text stream, without allocating a string. + /// + /// The to write to. + /// The 4-byte signed integer to write. + /// A standard or custom numeric format string. + /// An object that supplies culture-specific formatting information. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + public static void WriteNoAlloc(this TextWriter writer, int value, ReadOnlySpan format, IFormatProvider? formatProvider) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + int digitCount = value.CountDigits(); + Span buffer = stackalloc char[System.Math.Max(value < 0 ? digitCount + 1 : digitCount, 100)]; + if (value.TryFormat(buffer, out int charsWritten, format, formatProvider)) + { + Span truncated = buffer[..charsWritten]; + for (var index = 0; index < truncated.Length; index++) + { + writer.Write(truncated[index]); + } + } + else + { + writer.Write(value.ToString(format.ToString(), formatProvider)); + } + } +} diff --git a/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.Int64.cs b/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.Int64.cs new file mode 100644 index 0000000..049d891 --- /dev/null +++ b/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.Int64.cs @@ -0,0 +1,95 @@ +using System.Globalization; +using X10D.Math; + +namespace X10D.IO; + +public static partial class TextWriterExtensions +{ + /// + /// Writes the text representation of an 8-byte signed integer to the text stream, without allocating a string. + /// + /// The to write to. + /// The 8-byte signed integer to write. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + public static void WriteNoAlloc(this TextWriter writer, long value) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + WriteNoAlloc(writer, value, "N0".AsSpan(), CultureInfo.CurrentCulture); + } + + /// + /// Writes the text representation of an 8-byte signed integer to the text stream, without allocating a string. + /// + /// The to write to. + /// The 8-byte signed integer to write. + /// A standard or custom numeric format string. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + public static void WriteNoAlloc(this TextWriter writer, long value, ReadOnlySpan format) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + WriteNoAlloc(writer, value, format, CultureInfo.CurrentCulture); + } + + /// + /// Writes the text representation of an 8-byte signed integer to the text stream, without allocating a string. + /// + /// The to write to. + /// The 8-byte signed integer to write. + /// A standard or custom numeric format string. + /// An object that supplies culture-specific formatting information. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + public static void WriteNoAlloc(this TextWriter writer, + long value, + ReadOnlySpan format, + IFormatProvider? formatProvider) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + int digitCount = value.CountDigits(); + Span buffer = stackalloc char[System.Math.Max(value < 0 ? digitCount + 1 : digitCount, 100)]; + if (value.TryFormat(buffer, out int charsWritten, format, formatProvider)) + { + Span truncated = buffer[..charsWritten]; + for (var index = 0; index < truncated.Length; index++) + { + writer.Write(truncated[index]); + } + } + else + { + writer.Write(value.ToString(format.ToString(), formatProvider)); + } + } +} diff --git a/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.UInt32.cs b/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.UInt32.cs new file mode 100644 index 0000000..f8d32a2 --- /dev/null +++ b/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.UInt32.cs @@ -0,0 +1,98 @@ +using System.Globalization; +using X10D.Math; + +namespace X10D.IO; + +public static partial class TextWriterExtensions +{ + /// + /// Writes the text representation of a 4-byte unsigned integer to the text stream, without allocating a string. + /// + /// The to write to. + /// The 4-byte unsigned integer to write. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + [CLSCompliant(false)] + public static void WriteNoAlloc(this TextWriter writer, uint value) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + WriteNoAlloc(writer, value, "N0".AsSpan(), CultureInfo.CurrentCulture); + } + + /// + /// Writes the text representation of a 4-byte unsigned integer to the text stream, without allocating a string. + /// + /// The to write to. + /// The 4-byte unsigned integer to write. + /// A standard or custom numeric format string. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + [CLSCompliant(false)] + public static void WriteNoAlloc(this TextWriter writer, uint value, ReadOnlySpan format) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + WriteNoAlloc(writer, value, format, CultureInfo.CurrentCulture); + } + + /// + /// Writes the text representation of a 4-byte unsigned integer to the text stream, without allocating a string. + /// + /// The to write to. + /// The 4-byte unsigned integer to write. + /// A standard or custom numeric format string. + /// An object that supplies culture-specific formatting information. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + [CLSCompliant(false)] + public static void WriteNoAlloc(this TextWriter writer, + uint value, + ReadOnlySpan format, + IFormatProvider? formatProvider) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + int digitCount = value.CountDigits(); + Span buffer = stackalloc char[System.Math.Max(digitCount, 100)]; + if (value.TryFormat(buffer, out int charsWritten, format, formatProvider)) + { + Span truncated = buffer[..charsWritten]; + for (var index = 0; index < truncated.Length; index++) + { + writer.Write(truncated[index]); + } + } + else + { + writer.Write(value.ToString(format.ToString(), formatProvider)); + } + } +} diff --git a/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.UInt64.cs b/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.UInt64.cs new file mode 100644 index 0000000..5e266e4 --- /dev/null +++ b/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.UInt64.cs @@ -0,0 +1,98 @@ +using System.Globalization; +using X10D.Math; + +namespace X10D.IO; + +public static partial class TextWriterExtensions +{ + /// + /// Writes the text representation of an 8-byte unsigned integer to the text stream, without allocating a string. + /// + /// The to write to. + /// The 8-byte unsigned integer to write. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + [CLSCompliant(false)] + public static void WriteNoAlloc(this TextWriter writer, ulong value) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + WriteNoAlloc(writer, value, "N0".AsSpan(), CultureInfo.CurrentCulture); + } + + /// + /// Writes the text representation of an 8-byte signed integer to the text stream, without allocating a string. + /// + /// The to write to. + /// The 8-byte unsigned integer to write. + /// A standard or custom numeric format string. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + [CLSCompliant(false)] + public static void WriteNoAlloc(this TextWriter writer, ulong value, ReadOnlySpan format) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + WriteNoAlloc(writer, value, format, CultureInfo.CurrentCulture); + } + + /// + /// Writes the text representation of an 8-byte signed integer to the text stream, without allocating a string. + /// + /// The to write to. + /// The 8-byte unsigned integer to write. + /// A standard or custom numeric format string. + /// An object that supplies culture-specific formatting information. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + [CLSCompliant(false)] + public static void WriteNoAlloc(this TextWriter writer, + ulong value, + ReadOnlySpan format, + IFormatProvider? formatProvider) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + int digitCount = value.CountDigits(); + Span buffer = stackalloc char[System.Math.Max(digitCount, 100)]; + if (value.TryFormat(buffer, out int charsWritten, format, formatProvider)) + { + Span truncated = buffer[..charsWritten]; + for (var index = 0; index < truncated.Length; index++) + { + writer.Write(truncated[index]); + } + } + else + { + writer.Write(value.ToString(format.ToString(), formatProvider)); + } + } +} diff --git a/X10D/src/IO/TextWriterExtensions.cs b/X10D/src/IO/TextWriterExtensions.cs index 7d1b3c5..f590205 100644 --- a/X10D/src/IO/TextWriterExtensions.cs +++ b/X10D/src/IO/TextWriterExtensions.cs @@ -1,685 +1,8 @@ -using System.Globalization; -using X10D.Math; - -namespace X10D.IO; +namespace X10D.IO; /// /// IO-related extension methods for . /// -public static class TextWriterExtensions +public static partial class TextWriterExtensions { - /// - /// Writes the text representation of a 4-byte signed integer to the text stream, without allocating a string. - /// - /// The to write to. - /// The 4-byte signed integer to write. - /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. - /// is . - /// The is closed. - /// An I/O error occurs. - public static void WriteNoAlloc(this TextWriter writer, int value) - { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else - if (writer is null) - { - throw new ArgumentNullException(nameof(writer)); - } -#endif - - WriteNoAlloc(writer, value, "N0".AsSpan(), CultureInfo.CurrentCulture); - } - - /// - /// Writes the text representation of a 4-byte signed integer to the text stream, without allocating a string. - /// - /// The to write to. - /// The 4-byte signed integer to write. - /// A standard or custom numeric format string. - /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. - /// is . - /// The is closed. - /// An I/O error occurs. - public static void WriteNoAlloc(this TextWriter writer, int value, ReadOnlySpan format) - { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else - if (writer is null) - { - throw new ArgumentNullException(nameof(writer)); - } -#endif - - WriteNoAlloc(writer, value, format, CultureInfo.CurrentCulture); - } - - /// - /// Writes the text representation of a 4-byte signed integer to the text stream, without allocating a string. - /// - /// The to write to. - /// The 4-byte signed integer to write. - /// A standard or custom numeric format string. - /// An object that supplies culture-specific formatting information. - /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. - /// is . - /// The is closed. - /// An I/O error occurs. - public static void WriteNoAlloc(this TextWriter writer, int value, ReadOnlySpan format, IFormatProvider? formatProvider) - { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else - if (writer is null) - { - throw new ArgumentNullException(nameof(writer)); - } -#endif - - int digitCount = value.CountDigits(); - Span buffer = stackalloc char[System.Math.Max(value < 0 ? digitCount + 1 : digitCount, 1000)]; - if (value.TryFormat(buffer, out int charsWritten, format, formatProvider)) - { - Span truncated = buffer[..charsWritten]; - for (var index = 0; index < truncated.Length; index++) - { - writer.Write(truncated[index]); - } - } - else - { - writer.Write(value.ToString(format.ToString(), formatProvider)); - } - } - - /// - /// Writes the text representation of a 4-byte unsigned integer to the text stream, without allocating a string. - /// - /// The to write to. - /// The 4-byte unsigned integer to write. - /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. - /// is . - /// The is closed. - /// An I/O error occurs. - [CLSCompliant(false)] - public static void WriteNoAlloc(this TextWriter writer, uint value) - { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else - if (writer is null) - { - throw new ArgumentNullException(nameof(writer)); - } -#endif - - WriteNoAlloc(writer, value, "N0".AsSpan(), CultureInfo.CurrentCulture); - } - - /// - /// Writes the text representation of a 4-byte unsigned integer to the text stream, without allocating a string. - /// - /// The to write to. - /// The 4-byte unsigned integer to write. - /// A standard or custom numeric format string. - /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. - /// is . - /// The is closed. - /// An I/O error occurs. - [CLSCompliant(false)] - public static void WriteNoAlloc(this TextWriter writer, uint value, ReadOnlySpan format) - { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else - if (writer is null) - { - throw new ArgumentNullException(nameof(writer)); - } -#endif - - WriteNoAlloc(writer, value, format, CultureInfo.CurrentCulture); - } - - /// - /// Writes the text representation of a 4-byte unsigned integer to the text stream, without allocating a string. - /// - /// The to write to. - /// The 4-byte unsigned integer to write. - /// A standard or custom numeric format string. - /// An object that supplies culture-specific formatting information. - /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. - /// is . - /// The is closed. - /// An I/O error occurs. - [CLSCompliant(false)] - public static void WriteNoAlloc(this TextWriter writer, - uint value, - ReadOnlySpan format, - IFormatProvider? formatProvider) - { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else - if (writer is null) - { - throw new ArgumentNullException(nameof(writer)); - } -#endif - - int digitCount = value.CountDigits(); - Span buffer = stackalloc char[System.Math.Max(digitCount, 1000)]; - if (value.TryFormat(buffer, out int charsWritten, format, formatProvider)) - { - Span truncated = buffer[..charsWritten]; - for (var index = 0; index < truncated.Length; index++) - { - writer.Write(truncated[index]); - } - } - else - { - writer.Write(value.ToString(format.ToString(), formatProvider)); - } - } - - /// - /// Writes the text representation of a 8-byte signed integer to the text stream, without allocating a string. - /// - /// The to write to. - /// The 8-byte signed integer to write. - /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. - /// is . - /// The is closed. - /// An I/O error occurs. - public static void WriteNoAlloc(this TextWriter writer, long value) - { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else - if (writer is null) - { - throw new ArgumentNullException(nameof(writer)); - } -#endif - - WriteNoAlloc(writer, value, "N0".AsSpan(), CultureInfo.CurrentCulture); - } - - /// - /// Writes the text representation of a 8-byte signed integer to the text stream, without allocating a string. - /// - /// The to write to. - /// The 8-byte signed integer to write. - /// A standard or custom numeric format string. - /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. - /// is . - /// The is closed. - /// An I/O error occurs. - public static void WriteNoAlloc(this TextWriter writer, long value, ReadOnlySpan format) - { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else - if (writer is null) - { - throw new ArgumentNullException(nameof(writer)); - } -#endif - - WriteNoAlloc(writer, value, format, CultureInfo.CurrentCulture); - } - - /// - /// Writes the text representation of a 8-byte signed integer to the text stream, without allocating a string. - /// - /// The to write to. - /// The 8-byte signed integer to write. - /// A standard or custom numeric format string. - /// An object that supplies culture-specific formatting information. - /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. - /// is . - /// The is closed. - /// An I/O error occurs. - public static void WriteNoAlloc(this TextWriter writer, - long value, - ReadOnlySpan format, - IFormatProvider? formatProvider) - { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else - if (writer is null) - { - throw new ArgumentNullException(nameof(writer)); - } -#endif - - int digitCount = value.CountDigits(); - Span buffer = stackalloc char[System.Math.Max(value < 0 ? digitCount + 1 : digitCount, 1000)]; - if (value.TryFormat(buffer, out int charsWritten, format, formatProvider)) - { - Span truncated = buffer[..charsWritten]; - for (var index = 0; index < truncated.Length; index++) - { - writer.Write(truncated[index]); - } - } - else - { - writer.Write(value.ToString(format.ToString(), formatProvider)); - } - } - - /// - /// Writes the text representation of a 8-byte unsigned integer to the text stream, without allocating a string. - /// - /// The to write to. - /// The 8-byte unsigned integer to write. - /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. - /// is . - /// The is closed. - /// An I/O error occurs. - [CLSCompliant(false)] - public static void WriteNoAlloc(this TextWriter writer, ulong value) - { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else - if (writer is null) - { - throw new ArgumentNullException(nameof(writer)); - } -#endif - - WriteNoAlloc(writer, value, "N0".AsSpan(), CultureInfo.CurrentCulture); - } - - /// - /// Writes the text representation of a 8-byte signed integer to the text stream, without allocating a string. - /// - /// The to write to. - /// The 8-byte unsigned integer to write. - /// A standard or custom numeric format string. - /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. - /// is . - /// The is closed. - /// An I/O error occurs. - [CLSCompliant(false)] - public static void WriteNoAlloc(this TextWriter writer, ulong value, ReadOnlySpan format) - { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else - if (writer is null) - { - throw new ArgumentNullException(nameof(writer)); - } -#endif - - WriteNoAlloc(writer, value, format, CultureInfo.CurrentCulture); - } - - /// - /// Writes the text representation of a 8-byte signed integer to the text stream, without allocating a string. - /// - /// The to write to. - /// The 8-byte unsigned integer to write. - /// A standard or custom numeric format string. - /// An object that supplies culture-specific formatting information. - /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. - /// is . - /// The is closed. - /// An I/O error occurs. - [CLSCompliant(false)] - public static void WriteNoAlloc(this TextWriter writer, - ulong value, - ReadOnlySpan format, - IFormatProvider? formatProvider) - { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else - if (writer is null) - { - throw new ArgumentNullException(nameof(writer)); - } -#endif - - int digitCount = value.CountDigits(); - Span buffer = stackalloc char[System.Math.Max(digitCount, 1000)]; - if (value.TryFormat(buffer, out int charsWritten, format, formatProvider)) - { - Span truncated = buffer[..charsWritten]; - for (var index = 0; index < truncated.Length; index++) - { - writer.Write(truncated[index]); - } - } - else - { - writer.Write(value.ToString(format.ToString(), formatProvider)); - } - } - - /// - /// Writes the text representation of a 4-byte signed integer to the text stream, followed by a line terminator, without - /// allocating a string. - /// - /// The to write to. - /// The 4-byte signed integer to write. - /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. - /// is . - /// The is closed. - /// An I/O error occurs. - public static void WriteLineNoAlloc(this TextWriter writer, int value) - { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else - if (writer is null) - { - throw new ArgumentNullException(nameof(writer)); - } -#endif - - writer.WriteLineNoAlloc(value, "N0".AsSpan(), CultureInfo.CurrentCulture); - } - - /// - /// Writes the text representation of a 4-byte signed integer to the text stream, followed by a line terminator, without - /// allocating a string. - /// - /// The to write to. - /// The 4-byte signed integer to write. - /// A standard or custom numeric format string. - /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. - /// is . - /// The is closed. - /// An I/O error occurs. - public static void WriteLineNoAlloc(this TextWriter writer, int value, ReadOnlySpan format) - { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else - if (writer is null) - { - throw new ArgumentNullException(nameof(writer)); - } -#endif - - writer.WriteLineNoAlloc(value, format, CultureInfo.CurrentCulture); - } - - /// - /// Writes the text representation of a 4-byte signed integer to the text stream, followed by a line terminator, without - /// allocating a string. - /// - /// The to write to. - /// The 4-byte signed integer to write. - /// A standard or custom numeric format string. - /// An object that supplies culture-specific formatting information. - /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. - /// is . - /// The is closed. - /// An I/O error occurs. - public static void WriteLineNoAlloc(this TextWriter writer, int value, ReadOnlySpan format, - IFormatProvider? formatProvider) - { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else - if (writer is null) - { - throw new ArgumentNullException(nameof(writer)); - } -#endif - - writer.WriteNoAlloc(value, format, formatProvider); - writer.WriteLine(); - } - - /// - /// Writes the text representation of a 4-byte unsigned integer to the text stream, followed by a line terminator, without - /// allocating a string. - /// - /// The to write to. - /// The 4-byte unsigned integer to write. - /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. - /// is . - /// The is closed. - /// An I/O error occurs. - [CLSCompliant(false)] - public static void WriteLineNoAlloc(this TextWriter writer, uint value) - { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else - if (writer is null) - { - throw new ArgumentNullException(nameof(writer)); - } -#endif - - writer.WriteLineNoAlloc(value, "N0".AsSpan(), CultureInfo.CurrentCulture); - } - - /// - /// Writes the text representation of a 4-byte unsigned integer to the text stream, followed by a line terminator, without - /// allocating a string. - /// - /// The to write to. - /// The 4-byte unsigned integer to write. - /// A standard or custom numeric format string. - /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. - /// is . - /// The is closed. - /// An I/O error occurs. - [CLSCompliant(false)] - public static void WriteLineNoAlloc(this TextWriter writer, uint value, ReadOnlySpan format) - { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else - if (writer is null) - { - throw new ArgumentNullException(nameof(writer)); - } -#endif - - writer.WriteLineNoAlloc(value, format, CultureInfo.CurrentCulture); - } - - /// - /// Writes the text representation of a 4-byte unsigned integer to the text stream, followed by a line terminator, without - /// allocating a string. - /// - /// The to write to. - /// The 4-byte unsigned integer to write. - /// A standard or custom numeric format string. - /// An object that supplies culture-specific formatting information. - /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. - /// is . - /// The is closed. - /// An I/O error occurs. - [CLSCompliant(false)] - public static void WriteLineNoAlloc(this TextWriter writer, - uint value, - ReadOnlySpan format, - IFormatProvider? formatProvider) - { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else - if (writer is null) - { - throw new ArgumentNullException(nameof(writer)); - } -#endif - - writer.WriteNoAlloc(value, format, formatProvider); - writer.WriteLine(); - } - - /// - /// Writes the text representation of a 8-byte signed integer to the text stream, followed by a line terminator, without - /// allocating a string. - /// - /// The to write to. - /// The 8-byte signed integer to write. - /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. - /// is . - /// The is closed. - /// An I/O error occurs. - public static void WriteLineNoAlloc(this TextWriter writer, long value) - { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else - if (writer is null) - { - throw new ArgumentNullException(nameof(writer)); - } -#endif - - writer.WriteLineNoAlloc(value, "N0".AsSpan(), CultureInfo.CurrentCulture); - } - - /// - /// Writes the text representation of a 8-byte signed integer to the text stream, followed by a line terminator, without - /// allocating a string. - /// - /// The to write to. - /// The 8-byte signed integer to write. - /// A standard or custom numeric format string. - /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. - /// is . - /// The is closed. - /// An I/O error occurs. - public static void WriteLineNoAlloc(this TextWriter writer, long value, ReadOnlySpan format) - { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else - if (writer is null) - { - throw new ArgumentNullException(nameof(writer)); - } -#endif - - writer.WriteLineNoAlloc(value, format, CultureInfo.CurrentCulture); - } - - /// - /// Writes the text representation of a 8-byte signed integer to the text stream, followed by a line terminator, without - /// allocating a string. - /// - /// The to write to. - /// The 8-byte signed integer to write. - /// A standard or custom numeric format string. - /// An object that supplies culture-specific formatting information. - /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. - /// is . - /// The is closed. - /// An I/O error occurs. - public static void WriteLineNoAlloc(this TextWriter writer, - long value, - ReadOnlySpan format, - IFormatProvider? formatProvider) - { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else - if (writer is null) - { - throw new ArgumentNullException(nameof(writer)); - } -#endif - - writer.WriteNoAlloc(value, format, formatProvider); - writer.WriteLine(); - } - - /// - /// Writes the text representation of a 8-byte unsigned integer to the text stream, followed by a line terminator, without - /// allocating a string. - /// - /// The to write to. - /// The 8-byte unsigned integer to write. - /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. - /// is . - /// The is closed. - /// An I/O error occurs. - [CLSCompliant(false)] - public static void WriteLineNoAlloc(this TextWriter writer, ulong value) - { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else - if (writer is null) - { - throw new ArgumentNullException(nameof(writer)); - } -#endif - - writer.WriteLineNoAlloc(value, "N0".AsSpan(), CultureInfo.CurrentCulture); - } - - /// - /// Writes the text representation of a 8-byte signed integer to the text stream, followed by a line terminator, without - /// allocating a string. - /// - /// The to write to. - /// The 8-byte unsigned integer to write. - /// A standard or custom numeric format string. - /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. - /// is . - /// The is closed. - /// An I/O error occurs. - [CLSCompliant(false)] - public static void WriteLineNoAlloc(this TextWriter writer, ulong value, ReadOnlySpan format) - { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else - if (writer is null) - { - throw new ArgumentNullException(nameof(writer)); - } -#endif - - writer.WriteLineNoAlloc(value, format, CultureInfo.CurrentCulture); - } - - /// - /// Writes the text representation of a 8-byte signed integer to the text stream, followed by a line terminator, without - /// allocating a string. - /// - /// The to write to. - /// The 8-byte unsigned integer to write. - /// A standard or custom numeric format string. - /// An object that supplies culture-specific formatting information. - /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. - /// is . - /// The is closed. - /// An I/O error occurs. - [CLSCompliant(false)] - public static void WriteLineNoAlloc(this TextWriter writer, - ulong value, - ReadOnlySpan format, - IFormatProvider? formatProvider) - { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else - if (writer is null) - { - throw new ArgumentNullException(nameof(writer)); - } -#endif - - writer.WriteNoAlloc(value, format, formatProvider); - writer.WriteLine(); - } } From b8a63c0d5ce7a8fad9e91f3ddc777c58734d9926 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Tue, 11 Apr 2023 22:27:31 +0100 Subject: [PATCH 040/102] feat: add float/double support for WriteNoAlloc and WriteLineNoAlloc --- X10D.Tests/src/IO/TextWriterTests.Double.cs | 131 ++++++++++++++++++ X10D.Tests/src/IO/TextWriterTests.Single.cs | 131 ++++++++++++++++++ ...riterExtensions.WriteLineNoAlloc.Double.cs | 83 +++++++++++ ...riterExtensions.WriteLineNoAlloc.Single.cs | 83 +++++++++++ ...extWriterExtensions.WriteNoAlloc.Double.cs | 91 ++++++++++++ ...extWriterExtensions.WriteNoAlloc.Single.cs | 91 ++++++++++++ 6 files changed, 610 insertions(+) create mode 100644 X10D.Tests/src/IO/TextWriterTests.Double.cs create mode 100644 X10D.Tests/src/IO/TextWriterTests.Single.cs create mode 100644 X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.Double.cs create mode 100644 X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.Single.cs create mode 100644 X10D/src/IO/TextWriterExtensions.WriteNoAlloc.Double.cs create mode 100644 X10D/src/IO/TextWriterExtensions.WriteNoAlloc.Single.cs diff --git a/X10D.Tests/src/IO/TextWriterTests.Double.cs b/X10D.Tests/src/IO/TextWriterTests.Double.cs new file mode 100644 index 0000000..6f6ed7f --- /dev/null +++ b/X10D.Tests/src/IO/TextWriterTests.Double.cs @@ -0,0 +1,131 @@ +using System.Globalization; +using System.Text; +using NUnit.Framework; +using X10D.IO; + +namespace X10D.Tests.IO; + +public partial class TextWriterTests +{ + [Test] + public void WriteNoAlloc_ShouldThrowArgumentNullException_GivenDouble_AndNullWriter() + { + TextWriter writer = null!; + Assert.Throws(() => writer.WriteNoAlloc(420.0)); + Assert.Throws(() => writer.WriteNoAlloc(420.0, "N0")); + Assert.Throws(() => writer.WriteNoAlloc(420.0, "N0", null)); + } + + [Test] + public void WriteNoAlloc_ShouldThrowObjectDisposedException_GivenDouble_AndDisposedStream() + { + var stream = new MemoryStream(); + var writer = new StreamWriter(stream, Encoding.UTF8); + writer.Dispose(); + stream.Dispose(); + + Assert.Throws(() => writer.WriteNoAlloc(420.0)); + Assert.Throws(() => writer.WriteNoAlloc(420.0, "N0")); + Assert.Throws(() => writer.WriteNoAlloc(420.0, "N0", null)); + } + + [Test] + public void WriteLineNoAlloc_ShouldThrowArgumentNullException_GivenDouble_AndNullWriter() + { + TextWriter writer = null!; + Assert.Throws(() => writer.WriteLineNoAlloc(420.0)); + Assert.Throws(() => writer.WriteLineNoAlloc(420.0, "N0")); + Assert.Throws(() => writer.WriteLineNoAlloc(420.0, "N0", null)); + } + + [Test] + public void WriteLineNoAlloc_ShouldThrowObjectDisposedException_GivenDouble_AndDisposedStream() + { + var stream = new MemoryStream(); + var writer = new StreamWriter(stream, Encoding.UTF8); + writer.Dispose(); + stream.Dispose(); + + Assert.Throws(() => writer.WriteLineNoAlloc(420.0)); + Assert.Throws(() => writer.WriteLineNoAlloc(420.0, "N0")); + Assert.Throws(() => writer.WriteLineNoAlloc(420.0, "N0", null)); + } + + [Test] + public void WriteNoAlloc_ShouldWriteTextValue_GivenDouble() + { + Assert.That(_stream.Length, Is.Zero); + _writer.WriteNoAlloc(420.0); + _writer.Flush(); + + string actual = Encoding.UTF8.GetString(_stream.ToArray()); + const string expected = "420"; + + Assert.That(actual, Is.EqualTo(expected)); + } + + [Test] + public void WriteNoAlloc_ShouldWriteTextValue_GivenDouble_AndFormatString() + { + Assert.That(_stream.Length, Is.Zero); + _writer.WriteNoAlloc(420.0, "N0"); + _writer.Flush(); + + string actual = Encoding.UTF8.GetString(_stream.ToArray()); + const string expected = "420"; + + Assert.That(actual, Is.EqualTo(expected)); + } + + [Test] + public void WriteNoAlloc_ShouldWriteTextValue_GivenDouble_AndFormatString_AndCultureInfo() + { + Assert.That(_stream.Length, Is.Zero); + _writer.WriteNoAlloc(420.0, "N0", CultureInfo.CurrentCulture); + _writer.Flush(); + + string actual = Encoding.UTF8.GetString(_stream.ToArray()); + const string expected = "420"; + + Assert.That(actual, Is.EqualTo(expected)); + } + + [Test] + public void WriteLineNoAlloc_ShouldWriteTextValue_GivenDouble() + { + Assert.That(_stream.Length, Is.Zero); + _writer.WriteLineNoAlloc(420.0); + _writer.Flush(); + + string actual = Encoding.UTF8.GetString(_stream.ToArray()); + var expected = $"420{Environment.NewLine}"; + + Assert.That(actual, Is.EqualTo(expected)); + } + + [Test] + public void WriteLineNoAlloc_ShouldWriteTextValue_GivenDouble_AndFormatString() + { + Assert.That(_stream.Length, Is.Zero); + _writer.WriteLineNoAlloc(420.0, "N0"); + _writer.Flush(); + + string actual = Encoding.UTF8.GetString(_stream.ToArray()); + var expected = $"420{Environment.NewLine}"; + + Assert.That(actual, Is.EqualTo(expected)); + } + + [Test] + public void WriteLineNoAlloc_ShouldWriteTextValue_GivenDouble_AndFormatString_AndCultureInfo() + { + Assert.That(_stream.Length, Is.Zero); + _writer.WriteLineNoAlloc(420.0, "N0", CultureInfo.CurrentCulture); + _writer.Flush(); + + string actual = Encoding.UTF8.GetString(_stream.ToArray()); + var expected = $"420{Environment.NewLine}"; + + Assert.That(actual, Is.EqualTo(expected)); + } +} diff --git a/X10D.Tests/src/IO/TextWriterTests.Single.cs b/X10D.Tests/src/IO/TextWriterTests.Single.cs new file mode 100644 index 0000000..3ccba4f --- /dev/null +++ b/X10D.Tests/src/IO/TextWriterTests.Single.cs @@ -0,0 +1,131 @@ +using System.Globalization; +using System.Text; +using NUnit.Framework; +using X10D.IO; + +namespace X10D.Tests.IO; + +public partial class TextWriterTests +{ + [Test] + public void WriteNoAlloc_ShouldThrowArgumentNullException_GivenSingle_AndNullWriter() + { + TextWriter writer = null!; + Assert.Throws(() => writer.WriteNoAlloc(420.0f)); + Assert.Throws(() => writer.WriteNoAlloc(420.0f, "N0")); + Assert.Throws(() => writer.WriteNoAlloc(420.0f, "N0", null)); + } + + [Test] + public void WriteNoAlloc_ShouldThrowObjectDisposedException_GivenSingle_AndDisposedStream() + { + var stream = new MemoryStream(); + var writer = new StreamWriter(stream, Encoding.UTF8); + writer.Dispose(); + stream.Dispose(); + + Assert.Throws(() => writer.WriteNoAlloc(420.0f)); + Assert.Throws(() => writer.WriteNoAlloc(420.0f, "N0")); + Assert.Throws(() => writer.WriteNoAlloc(420.0f, "N0", null)); + } + + [Test] + public void WriteLineNoAlloc_ShouldThrowArgumentNullException_GivenSingle_AndNullWriter() + { + TextWriter writer = null!; + Assert.Throws(() => writer.WriteLineNoAlloc(420.0f)); + Assert.Throws(() => writer.WriteLineNoAlloc(420.0f, "N0")); + Assert.Throws(() => writer.WriteLineNoAlloc(420.0f, "N0", null)); + } + + [Test] + public void WriteLineNoAlloc_ShouldThrowObjectDisposedException_GivenSingle_AndDisposedStream() + { + var stream = new MemoryStream(); + var writer = new StreamWriter(stream, Encoding.UTF8); + writer.Dispose(); + stream.Dispose(); + + Assert.Throws(() => writer.WriteLineNoAlloc(420.0f)); + Assert.Throws(() => writer.WriteLineNoAlloc(420.0f, "N0")); + Assert.Throws(() => writer.WriteLineNoAlloc(420.0f, "N0", null)); + } + + [Test] + public void WriteNoAlloc_ShouldWriteTextValue_GivenSingle() + { + Assert.That(_stream.Length, Is.Zero); + _writer.WriteNoAlloc(420.0f); + _writer.Flush(); + + string actual = Encoding.UTF8.GetString(_stream.ToArray()); + const string expected = "420"; + + Assert.That(actual, Is.EqualTo(expected)); + } + + [Test] + public void WriteNoAlloc_ShouldWriteTextValue_GivenSingle_AndFormatString() + { + Assert.That(_stream.Length, Is.Zero); + _writer.WriteNoAlloc(420.0f, "N0"); + _writer.Flush(); + + string actual = Encoding.UTF8.GetString(_stream.ToArray()); + const string expected = "420"; + + Assert.That(actual, Is.EqualTo(expected)); + } + + [Test] + public void WriteNoAlloc_ShouldWriteTextValue_GivenSingle_AndFormatString_AndCultureInfo() + { + Assert.That(_stream.Length, Is.Zero); + _writer.WriteNoAlloc(420.0f, "N0", CultureInfo.CurrentCulture); + _writer.Flush(); + + string actual = Encoding.UTF8.GetString(_stream.ToArray()); + const string expected = "420"; + + Assert.That(actual, Is.EqualTo(expected)); + } + + [Test] + public void WriteLineNoAlloc_ShouldWriteTextValue_GivenSingle() + { + Assert.That(_stream.Length, Is.Zero); + _writer.WriteLineNoAlloc(420.0f); + _writer.Flush(); + + string actual = Encoding.UTF8.GetString(_stream.ToArray()); + var expected = $"420{Environment.NewLine}"; + + Assert.That(actual, Is.EqualTo(expected)); + } + + [Test] + public void WriteLineNoAlloc_ShouldWriteTextValue_GivenSingle_AndFormatString() + { + Assert.That(_stream.Length, Is.Zero); + _writer.WriteLineNoAlloc(420.0f, "N0"); + _writer.Flush(); + + string actual = Encoding.UTF8.GetString(_stream.ToArray()); + var expected = $"420{Environment.NewLine}"; + + Assert.That(actual, Is.EqualTo(expected)); + } + + [Test] + public void WriteLineNoAlloc_ShouldWriteTextValue_GivenSingle_AndFormatString_AndCultureInfo() + { + Assert.That(_stream.Length, Is.Zero); + _writer.WriteLineNoAlloc(420.0f, "N0", CultureInfo.CurrentCulture); + _writer.Flush(); + + string actual = Encoding.UTF8.GetString(_stream.ToArray()); + var expected = $"420{Environment.NewLine}"; + + Assert.That(actual, Is.EqualTo(expected)); + } +} diff --git a/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.Double.cs b/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.Double.cs new file mode 100644 index 0000000..1a63f42 --- /dev/null +++ b/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.Double.cs @@ -0,0 +1,83 @@ +using System.Globalization; + +namespace X10D.IO; + +public static partial class TextWriterExtensions +{ + /// + /// Writes the text representation of an 8-byte floating-point value to the text stream, followed by a line terminator, + /// without allocating a string. + /// + /// The to write to. + /// The 8-byte floating-point value to write. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + public static void WriteLineNoAlloc(this TextWriter writer, double value) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + writer.WriteLineNoAlloc(value, "N0".AsSpan(), CultureInfo.CurrentCulture); + } + + /// + /// Writes the text representation of an 8-byte floating-point value to the text stream, followed by a line terminator, + /// without allocating a string. + /// + /// The to write to. + /// The 8-byte floating-point value to write. + /// A standard or custom numeric format string. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + public static void WriteLineNoAlloc(this TextWriter writer, double value, ReadOnlySpan format) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + WriteLineNoAlloc(writer, value, format, CultureInfo.CurrentCulture); + } + + /// + /// Writes the text representation of an 8-byte floating-point value to the text stream, followed by a line terminator, + /// without allocating a string. + /// + /// The to write to. + /// The 8-byte floating-point value to write. + /// A standard or custom numeric format string. + /// An object that supplies culture-specific formatting information. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + public static void WriteLineNoAlloc(this TextWriter writer, double value, ReadOnlySpan format, + IFormatProvider? formatProvider) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + writer.WriteNoAlloc(value, format, formatProvider); + writer.WriteLine(); + } +} diff --git a/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.Single.cs b/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.Single.cs new file mode 100644 index 0000000..bb6d2e0 --- /dev/null +++ b/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.Single.cs @@ -0,0 +1,83 @@ +using System.Globalization; + +namespace X10D.IO; + +public static partial class TextWriterExtensions +{ + /// + /// Writes the text representation of a 4-byte floating-point value to the text stream, followed by a line terminator, + /// without allocating a string. + /// + /// The to write to. + /// The 4-byte floating-point value to write. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + public static void WriteLineNoAlloc(this TextWriter writer, float value) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + writer.WriteLineNoAlloc(value, "N0".AsSpan(), CultureInfo.CurrentCulture); + } + + /// + /// Writes the text representation of a 4-byte floating-point value to the text stream, followed by a line terminator, + /// without allocating a string. + /// + /// The to write to. + /// The 4-byte floating-point value to write. + /// A standard or custom numeric format string. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + public static void WriteLineNoAlloc(this TextWriter writer, float value, ReadOnlySpan format) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + WriteLineNoAlloc(writer, value, format, CultureInfo.CurrentCulture); + } + + /// + /// Writes the text representation of a 4-byte floating-point value to the text stream, followed by a line terminator, + /// without allocating a string. + /// + /// The to write to. + /// The 4-byte floating-point value to write. + /// A standard or custom numeric format string. + /// An object that supplies culture-specific formatting information. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + public static void WriteLineNoAlloc(this TextWriter writer, float value, ReadOnlySpan format, + IFormatProvider? formatProvider) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + writer.WriteNoAlloc(value, format, formatProvider); + writer.WriteLine(); + } +} diff --git a/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.Double.cs b/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.Double.cs new file mode 100644 index 0000000..6b6de18 --- /dev/null +++ b/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.Double.cs @@ -0,0 +1,91 @@ +using System.Globalization; + +namespace X10D.IO; + +public static partial class TextWriterExtensions +{ + /// + /// Writes the text representation of an 8-byte floating-point value to the text stream, without allocating a string. + /// + /// The to write to. + /// The 8-byte floating-point value to write. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + public static void WriteNoAlloc(this TextWriter writer, double value) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + WriteNoAlloc(writer, value, "N0".AsSpan(), CultureInfo.CurrentCulture); + } + + /// + /// Writes the text representation of an 8-byte floating-point value to the text stream, without allocating a string. + /// + /// The to write to. + /// The 8-byte floating-point value to write. + /// A standard or custom numeric format string. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + public static void WriteNoAlloc(this TextWriter writer, double value, ReadOnlySpan format) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + WriteNoAlloc(writer, value, format, CultureInfo.CurrentCulture); + } + + /// + /// Writes the text representation of an 8-byte floating-point value to the text stream, without allocating a string. + /// + /// The to write to. + /// The 8-byte floating-point value to write. + /// A standard or custom numeric format string. + /// An object that supplies culture-specific formatting information. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + public static void WriteNoAlloc(this TextWriter writer, double value, ReadOnlySpan format, + IFormatProvider? formatProvider) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + Span buffer = stackalloc char[100]; + if (value.TryFormat(buffer, out int charsWritten, format, formatProvider)) + { + Span truncated = buffer[..charsWritten]; + for (var index = 0; index < truncated.Length; index++) + { + writer.Write(truncated[index]); + } + } + else + { + writer.Write(value.ToString(format.ToString(), formatProvider)); + } + } +} diff --git a/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.Single.cs b/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.Single.cs new file mode 100644 index 0000000..f595593 --- /dev/null +++ b/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.Single.cs @@ -0,0 +1,91 @@ +using System.Globalization; + +namespace X10D.IO; + +public static partial class TextWriterExtensions +{ + /// + /// Writes the text representation of a 4-byte floating-point value to the text stream, without allocating a string. + /// + /// The to write to. + /// The 4-byte floating-point value to write. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + public static void WriteNoAlloc(this TextWriter writer, float value) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + WriteNoAlloc(writer, value, "N0".AsSpan(), CultureInfo.CurrentCulture); + } + + /// + /// Writes the text representation of a 4-byte floating-point value to the text stream, without allocating a string. + /// + /// The to write to. + /// The 4-byte floating-point value to write. + /// A standard or custom numeric format string. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + public static void WriteNoAlloc(this TextWriter writer, float value, ReadOnlySpan format) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + WriteNoAlloc(writer, value, format, CultureInfo.CurrentCulture); + } + + /// + /// Writes the text representation of a 4-byte floating-point value to the text stream, without allocating a string. + /// + /// The to write to. + /// The 4-byte floating-point value to write. + /// A standard or custom numeric format string. + /// An object that supplies culture-specific formatting information. + /// This method may still allocate if the integer is too large to fit in a stack-allocated buffer. + /// is . + /// The is closed. + /// An I/O error occurs. + public static void WriteNoAlloc(this TextWriter writer, float value, ReadOnlySpan format, + IFormatProvider? formatProvider) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(writer); +#else + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } +#endif + + Span buffer = stackalloc char[100]; + if (value.TryFormat(buffer, out int charsWritten, format, formatProvider)) + { + Span truncated = buffer[..charsWritten]; + for (var index = 0; index < truncated.Length; index++) + { + writer.Write(truncated[index]); + } + } + else + { + writer.Write(value.ToString(format.ToString(), formatProvider)); + } + } +} From c5ea6cca5820cdb369c8b32d271cf9fe027129cf Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Wed, 12 Apr 2023 12:47:32 +0100 Subject: [PATCH 041/102] [ci skip] docs: add conventional commit to contrib guidelines --- CONTRIBUTING.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c1d7f77..5aae0b4 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -9,6 +9,10 @@ This project uses C# 11.0 language features where feasible, and adheres to Style There is an `.editorconfig` included in this repository. For quick and painless pull requests, ensure that the analyzer does not throw warnings. +Please ensure that you follow the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) +specification, as the GitHub release for this project is automatically generated from the commit history, and formatted using the +convetional commits specification. + ### Code style Below are a few pointers to which you may refer, but keep in mind this is not an exhaustive list: From 3f08f5270f537aea749403734b7983b8e071b4ff Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Thu, 13 Apr 2023 01:48:58 +0100 Subject: [PATCH 042/102] feat: add DebugUtility.DrawFunction --- CHANGELOG.md | 1 + .../Tests/DebugUtilityIntegrationTests.cs | 6 +- .../src/DebugUtility/DebugUtility.Function.cs | 69 +++++++++++++++++++ .../DebugUtility/DebugUtility.Polyhedron.cs | 45 +++++++++++- 4 files changed, 119 insertions(+), 2 deletions(-) create mode 100644 X10D.Unity/src/DebugUtility/DebugUtility.Function.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 5ea3856..633397e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - X10D: Added `TextWriter.WriteLineNoAlloc(long[, ReadOnlySpan[, IFormatProvider]])`. - X10D: Added `TextWriter.WriteLineNoAlloc(ulong[, ReadOnlySpan[, IFormatProvider]])`. - X10D.Unity: Added `RaycastHit.GetComponent` and `RaycastHit.TryGetComponent`. +- X10D.Unity: Added `DebugUtility.DrawFunction`, and `DebugUtility.DrawUnjoinedPolyhedron` on which it relies. ### Changed diff --git a/X10D.Unity.Tests/Assets/Tests/DebugUtilityIntegrationTests.cs b/X10D.Unity.Tests/Assets/Tests/DebugUtilityIntegrationTests.cs index 1c625e5..157f6a9 100644 --- a/X10D.Unity.Tests/Assets/Tests/DebugUtilityIntegrationTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/DebugUtilityIntegrationTests.cs @@ -1,4 +1,5 @@ -using UnityEngine; +using System; +using UnityEngine; using X10D.Drawing; using X10D.Unity.Drawing; using Color = UnityEngine.Color; @@ -34,6 +35,9 @@ namespace X10D.Unity.Tests var sphere = new Sphere(System.Numerics.Vector3.Zero, 0.5f); DebugUtility.DrawSphere(sphere, 25, new Vector2(0.0f, -1.5f), Color.white); + DebugUtility.DrawFunction(x => MathF.Sin(x + UnityEngine.Time.time % (2 * MathF.PI)), -10, 10, 0.1f, Vector3.up * 4, + Color.yellow, 0.0f, false); + DebugUtility.Assert(true); } } diff --git a/X10D.Unity/src/DebugUtility/DebugUtility.Function.cs b/X10D.Unity/src/DebugUtility/DebugUtility.Function.cs new file mode 100644 index 0000000..4b7f33c --- /dev/null +++ b/X10D.Unity/src/DebugUtility/DebugUtility.Function.cs @@ -0,0 +1,69 @@ +using UnityEngine; +using X10D.Drawing; +using X10D.Numerics; +using X10D.Unity.Numerics; +using Quaternion = System.Numerics.Quaternion; + +namespace X10D.Unity; + +public static partial class DebugUtility +{ + /// + /// Draws a function plot. + /// + /// The function to plot. + /// The minimum X value. + /// The maximum X value. + public static void DrawFunction(Func function, float xMin, float xMax) + { + DrawFunction(function, xMin, xMax, 0.1f, Vector3.zero, Color.white, 0.0f, false); + } + + /// + /// Draws a function plot. + /// + /// The function to plot. + /// The minimum X value. + /// The maximum X value. + /// The X increment. + /// The drawing offset of the circle. + /// The color of the circle. + /// + /// The duration of the circle's visibility, in seconds. If 0 is passed, the circle is visible for a single frame. + /// + /// + /// if depth test should be applied; otherwise, . Passing + /// will have the circle be obscured by objects closer to the camera. + /// + /// is . + public static void DrawFunction(Func function, float xMin, float xMax, float step, in Vector3 offset, + in Color color, float duration, + bool depthTest) + { + if (function is null) + { + throw new ArgumentNullException(nameof(function)); + } + + DrawUnjoinedPolyhedron(CreateFunction(function, xMin, xMax, step, Vector3.zero), offset, color, duration, depthTest); + } + + private static Polyhedron CreateFunction(Func function, float xMin, float xMax, float step, in Vector3 axis) + { + var points = new List(); + for (float x = xMin; x < xMax; x += step) + { + float y = function(x); + var vector = new System.Numerics.Vector3(x, y, 0); + + if (axis != Vector3.zero) + { + vector = Quaternion.CreateFromAxisAngle(axis.ToSystemVector(), MathF.PI / 2.0f).Multiply(vector); + } + + points.Add(vector); + } + + return new Polyhedron(points); + } +} diff --git a/X10D.Unity/src/DebugUtility/DebugUtility.Polyhedron.cs b/X10D.Unity/src/DebugUtility/DebugUtility.Polyhedron.cs index 7ab51a0..205dfff 100644 --- a/X10D.Unity/src/DebugUtility/DebugUtility.Polyhedron.cs +++ b/X10D.Unity/src/DebugUtility/DebugUtility.Polyhedron.cs @@ -1,4 +1,4 @@ -using UnityEngine; +using UnityEngine; using X10D.Drawing; using X10D.Unity.Numerics; @@ -126,4 +126,47 @@ public static partial class DebugUtility DrawLine(start, end, color, duration, depthTest); } } + + /// + /// Draws a polyhedron. + /// + /// The polyhedron to draw. + /// The drawing offset of the polyhedron. + /// The color to use for drawing. + /// + /// The duration of the polyhedron's visibility, in seconds. If 0 is passed, the polyhedron is visible for a single frame. + /// + /// + /// if depth test should be applied; otherwise, . Passing + /// will have the box be obscured by objects closer to the camera. + /// + /// is . + public static void DrawUnjoinedPolyhedron(Polyhedron polyhedron, in Vector3 offset, in Color color, float duration, + bool depthTest) + { + if (polyhedron is null) + { + throw new ArgumentNullException(nameof(polyhedron)); + } + + IReadOnlyList points = polyhedron.Vertices; + if (points.Count < 2) + { + return; + } + + for (var i = 0; i < points.Count; i++) + { + if (i >= points.Count - 2) + { + break; + } + + int j = i + 1; + Vector3 start = points[i].ToUnityVector() + offset; + Vector3 end = points[j].ToUnityVector() + offset; + + DrawLine(start, end, color, duration, depthTest); + } + } } From 3655e33a9cd171e058ec122c999b110e684eddb5 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Thu, 13 Apr 2023 01:50:26 +0100 Subject: [PATCH 043/102] chore(test): update test project to 2021.3.22f1 ref b6c551784ba3 --- X10D.Unity.Tests/ProjectSettings/ProjectVersion.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/X10D.Unity.Tests/ProjectSettings/ProjectVersion.txt b/X10D.Unity.Tests/ProjectSettings/ProjectVersion.txt index bca3d02..f8251a7 100644 --- a/X10D.Unity.Tests/ProjectSettings/ProjectVersion.txt +++ b/X10D.Unity.Tests/ProjectSettings/ProjectVersion.txt @@ -1,2 +1,2 @@ -m_EditorVersion: 2021.3.21f1 -m_EditorVersionWithRevision: 2021.3.21f1 (1b156197d683) +m_EditorVersion: 2021.3.22f1 +m_EditorVersionWithRevision: 2021.3.22f1 (b6c551784ba3) From 1be3f75538270a8368f40303f6aa2ac23b5b3c13 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Thu, 13 Apr 2023 02:27:35 +0100 Subject: [PATCH 044/102] docs: add initial docfx intro --- docfx_project/api/index.md | 5 +++-- docfx_project/index.md | 7 +++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/docfx_project/api/index.md b/docfx_project/api/index.md index 78dc9c0..30fec73 100644 --- a/docfx_project/api/index.md +++ b/docfx_project/api/index.md @@ -1,2 +1,3 @@ -# PLACEHOLDER -TODO: Add .NET projects to the *src* folder and run `docfx` to generate **REAL** *API Documentation*! +# Introduction + +X10D (pronounced *extend*), is a .NET package that provides extension methods for numerous types. The purpose of this library is to simplify a codebase by reducing the need for repeated code when performing common operations. Simplify your codebase. Take advantage of .NET. Use extension methods. diff --git a/docfx_project/index.md b/docfx_project/index.md index 3ae2506..30fec73 100644 --- a/docfx_project/index.md +++ b/docfx_project/index.md @@ -1,4 +1,3 @@ -# This is the **HOMEPAGE**. -Refer to [Markdown](http://daringfireball.net/projects/markdown/) for how to write markdown files. -## Quick Start Notes: -1. Add images to the *images* folder if the file is referencing an image. +# Introduction + +X10D (pronounced *extend*), is a .NET package that provides extension methods for numerous types. The purpose of this library is to simplify a codebase by reducing the need for repeated code when performing common operations. Simplify your codebase. Take advantage of .NET. Use extension methods. From 2f5d1aee4c77d0504a11d51a699e46422487e0be Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Thu, 13 Apr 2023 02:31:21 +0100 Subject: [PATCH 045/102] docs: add favicon and app title to docfx project --- .github/workflows/docfx.yml | 28 +++++++++++++++++----------- docfx_project/docfx.json | 14 +++++++++++++- 2 files changed, 30 insertions(+), 12 deletions(-) diff --git a/.github/workflows/docfx.yml b/.github/workflows/docfx.yml index 556f434..e46ef08 100644 --- a/.github/workflows/docfx.yml +++ b/.github/workflows/docfx.yml @@ -9,14 +9,20 @@ jobs: runs-on: ubuntu-latest name: Publish Documentation steps: - - uses: actions/checkout@v3 - - uses: nikeee/docfx-action@v1.0.0 - name: Build Documentation - with: - args: docfx_project/docfx.json - - uses: maxheld83/ghpages@master - name: Publish Documentation on GitHub Pages - env: - BUILD_DIR: docfx_project/_site - GH_PAT: ${{ secrets.GH_PAT }} - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + - name: Checkout + uses: actions/checkout@v3 + + - name: Copy favicon + run: cp brandin_Icon.png docfx_project/images/favicon.png + + - name: Build documentation + uses: nikeee/docfx-action@v1.0.0 + with: + args: docfx_project/docfx.json + + - name: Publish documentation on GitHub Pages + uses: maxheld83/ghpages@master + env: + BUILD_DIR: docfx_project/_site + GH_PAT: ${{ secrets.GH_PAT }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/docfx_project/docfx.json b/docfx_project/docfx.json index 304c063..4cc5662 100644 --- a/docfx_project/docfx.json +++ b/docfx_project/docfx.json @@ -51,7 +51,19 @@ } ], "dest": "_site", - "globalMetadataFiles": [], + "globalMetadata": { + "_appTitle": "X10D", + "_appName": "X10D", + "_appFaviconPath": "images/favicon.png", + "_appLogoPath": "images/favicon.png", + "_appFooter": "DocFX + Singulink = ♥", + "_copyrightFooter": "© Singulink. All rights reserved.", + "_enableSearch": true, + "_disableSideFilter": false, + "_enableNewTab": true, + "_disableContribution": false, + "_disableBreadcrumb": false, + }, "fileMetadataFiles": [], "template": [ "default", "templates/singulinkfx" From 25ef4e68ef9e5b73ae0cba36f29cd1ef72c889b5 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Thu, 13 Apr 2023 02:35:44 +0100 Subject: [PATCH 046/102] fix(docs): fix cp source (+g. oops) --- .github/workflows/docfx.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/docfx.yml b/.github/workflows/docfx.yml index e46ef08..3aae86f 100644 --- a/.github/workflows/docfx.yml +++ b/.github/workflows/docfx.yml @@ -13,7 +13,7 @@ jobs: uses: actions/checkout@v3 - name: Copy favicon - run: cp brandin_Icon.png docfx_project/images/favicon.png + run: cp branding_Icon.png docfx_project/images/favicon.png - name: Build documentation uses: nikeee/docfx-action@v1.0.0 From a23be6dd777139facb95daf0297258d53e22b4d2 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Thu, 13 Apr 2023 02:38:17 +0100 Subject: [PATCH 047/102] [ci skip] fix(ci): mkdir docfx_project/images --- .github/workflows/docfx.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/docfx.yml b/.github/workflows/docfx.yml index 3aae86f..e460ace 100644 --- a/.github/workflows/docfx.yml +++ b/.github/workflows/docfx.yml @@ -13,7 +13,9 @@ jobs: uses: actions/checkout@v3 - name: Copy favicon - run: cp branding_Icon.png docfx_project/images/favicon.png + run: | + mkdir docfx_project/images + cp branding_Icon.png docfx_project/images/favicon.png - name: Build documentation uses: nikeee/docfx-action@v1.0.0 From 847af30945b1907655313587594f58d1208c7634 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Thu, 13 Apr 2023 20:54:07 +0100 Subject: [PATCH 048/102] docs: properly document ArgumentNullException --- X10D/src/Collections/EnumerableExtensions.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/X10D/src/Collections/EnumerableExtensions.cs b/X10D/src/Collections/EnumerableExtensions.cs index 78707e1..c38e4df 100644 --- a/X10D/src/Collections/EnumerableExtensions.cs +++ b/X10D/src/Collections/EnumerableExtensions.cs @@ -349,7 +349,9 @@ public static class EnumerableExtensions /// /// An that contains elements from the input sequence that do not satisfy the condition. /// - /// or is null. + /// + /// or is . + /// [Pure] public static IEnumerable WhereNot(this IEnumerable source, Func predicate) { @@ -381,6 +383,7 @@ public static class EnumerableExtensions /// An that contains elements from the input sequence that are not /// ( in Visual Basic). /// + /// is . public static IEnumerable WhereNotNull(this IEnumerable source) { #if NET6_0_OR_GREATER From 0ae377250c6ffa565d388b9f547a5bbd2b2632ee Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Thu, 13 Apr 2023 20:55:24 +0100 Subject: [PATCH 049/102] feat: add IEnumerable.Except(T) LINQ-provided Except method filters by array, but there's no way to filter a single value. This method introduces single-value filtering. --- CHANGELOG.md | 3 ++- X10D.Tests/src/Linq/EnumerableTests.cs | 25 +++++++++++++++++++++++++ X10D/src/Linq/EnumerableExtensions.cs | 25 +++++++++++++++++++++++++ 3 files changed, 52 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 633397e..9482e2e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,7 +13,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - X10D: Added math-related extension methods for `BigInteger`. - X10D: Added `Span.Replace(T, T)`. - X10D: Added `CountDigits` for integer types. -- X10D: Added `Progress.OnProgressChanged([T])`; +- X10D: Added `IEnumerable.Except(T)`. +- X10D: Added `Progress.OnProgressChanged([T])`. - X10D: Added `TextWriter.WriteNoAlloc(int[, ReadOnlySpan[, IFormatProvider]])`. - X10D: Added `TextWriter.WriteNoAlloc(uint[, ReadOnlySpan[, IFormatProvider]])`. - X10D: Added `TextWriter.WriteNoAlloc(long[, ReadOnlySpan[, IFormatProvider]])`. diff --git a/X10D.Tests/src/Linq/EnumerableTests.cs b/X10D.Tests/src/Linq/EnumerableTests.cs index 6d0a2e4..c478578 100644 --- a/X10D.Tests/src/Linq/EnumerableTests.cs +++ b/X10D.Tests/src/Linq/EnumerableTests.cs @@ -37,6 +37,31 @@ public class EnumerableTests Assert.Throws(() => source!.ConcatOne("Foobar").ToArray()); } + [Test] + public void Except_ShouldFilterElements_GivenMatchingElements() + { + int[] source = Enumerable.Range(1, 10).ToArray(); + int[] result = source.Except(5).ToArray(); + + Assert.That(result, Is.EquivalentTo(new[] {1, 2, 3, 4, 6, 7, 8, 9, 10})); + } + + [Test] + public void Except_ShouldReturnSameElements_GivenNoMatchingElements() + { + int[] source = Enumerable.Range(1, 10).ToArray(); + int[] result = source.Except(11).ToArray(); + + Assert.That(result, Is.EquivalentTo(source)); + } + + [Test] + public void Except_ShouldThrowArgumentNullException_GivenNullSource() + { + IEnumerable source = null!; + Assert.Throws(() => source.Except(42)); + } + [Test] public void MinMax_ShouldReturnCorrectValues_UsingDefaultComparer() { diff --git a/X10D/src/Linq/EnumerableExtensions.cs b/X10D/src/Linq/EnumerableExtensions.cs index 4362dd2..92592bf 100644 --- a/X10D/src/Linq/EnumerableExtensions.cs +++ b/X10D/src/Linq/EnumerableExtensions.cs @@ -39,6 +39,31 @@ public static class EnumerableExtensions yield return value; } + /// + /// Filters a sequence of values by omitting elements that match a specified value. + /// + /// An to filter. + /// The value to omit. + /// The type of the elements of . + /// + /// An that contains elements from the input sequence that do not match the specified + /// value. + /// + /// is . + public static IEnumerable Except(this IEnumerable source, TSource item) + { +#if NET6_0_OR_GREATER + ArgumentNullException.ThrowIfNull(source); +#else + if (source is null) + { + throw new ArgumentNullException(nameof(source)); + } +#endif + + return source.Where(i => !Equals(i, item)); + } + /// /// Returns the minimum and maximum values in a sequence of values. /// From b5f4c16266a3a4700adc17e63d81ce0934603a8f Mon Sep 17 00:00:00 2001 From: Oliver Booth <1129769+oliverbooth@users.noreply.github.com> Date: Thu, 13 Apr 2023 21:39:00 +0100 Subject: [PATCH 050/102] [ci skip] update bug-report.yml Adds 3.2.0 and "nightly/other" to version options. --- .github/ISSUE_TEMPLATE/bug-report.yml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.github/ISSUE_TEMPLATE/bug-report.yml b/.github/ISSUE_TEMPLATE/bug-report.yml index 1f26214..207dc5a 100644 --- a/.github/ISSUE_TEMPLATE/bug-report.yml +++ b/.github/ISSUE_TEMPLATE/bug-report.yml @@ -37,6 +37,8 @@ body: label: Version description: What version of the package are you running? options: + - Nightly / other + - 3.2.0 - 3.1.0 - 3.0.0 - 2.6.0 @@ -47,6 +49,12 @@ body: - 2.1.0 validations: required: true + - type: input + id: other-version + attributes: + label: Other version + description: If you selected "nightly / other", please enter the full version number here. + placeholder: "Example: 4.0.0-nightly-230" - type: textarea id: logs attributes: From 1c584037081a6df5bd642afa38d421df9cc7408c Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Thu, 13 Apr 2023 21:55:00 +0100 Subject: [PATCH 051/102] [ci skip] ci: add workflow_dispatch trigger for sonarcloud --- .github/workflows/sonarcloud.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/sonarcloud.yml b/.github/workflows/sonarcloud.yml index 3ac8f1b..7ee1360 100644 --- a/.github/workflows/sonarcloud.yml +++ b/.github/workflows/sonarcloud.yml @@ -3,6 +3,7 @@ on: push: branches: - main + workflow_dispatch: pull_request: types: [opened, synchronize, reopened] jobs: From a0d70eaa357f5242feb9ac317dbf5c06ccb93d0f Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Thu, 13 Apr 2023 21:55:20 +0100 Subject: [PATCH 052/102] [ci skip] ci: add workflows for push to any branch --- .github/workflows/dotnet.yml | 3 +-- .github/workflows/source_validator.yml | 3 +-- .github/workflows/unity.yml | 3 +-- 3 files changed, 3 insertions(+), 6 deletions(-) diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml index 1a43ce2..b5c7648 100644 --- a/.github/workflows/dotnet.yml +++ b/.github/workflows/dotnet.yml @@ -3,8 +3,7 @@ name: .NET on: push: branches: - - main - - develop + - '*' pull_request: branches: - main diff --git a/.github/workflows/source_validator.yml b/.github/workflows/source_validator.yml index a0a21a8..aad570f 100644 --- a/.github/workflows/source_validator.yml +++ b/.github/workflows/source_validator.yml @@ -3,8 +3,7 @@ name: Source Validator on: push: branches: - - main - - develop + - '*' pull_request: types: [opened, synchronize, reopened] diff --git a/.github/workflows/unity.yml b/.github/workflows/unity.yml index 9db7ec3..e6b8c7a 100644 --- a/.github/workflows/unity.yml +++ b/.github/workflows/unity.yml @@ -3,8 +3,7 @@ name: Unity Test Runner on: push: branches: - - main - - develop + - '*' pull_request: branches: - main From 3b5fb7b2be66d881c4a92ce2827110ffdb16329c Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Thu, 13 Apr 2023 22:35:43 +0100 Subject: [PATCH 053/102] refactor: remove throw helpers in X10D.DSharpPlus (#80) --- .../src/DiscordChannelExtensions.cs | 9 ------ .../src/DiscordClientExtensions.cs | 8 ----- .../src/DiscordEmbedBuilderExtensions.cs | 31 ++----------------- X10D.DSharpPlus/src/DiscordGuildExtensions.cs | 13 -------- .../src/DiscordMemberExtensions.cs | 10 ------ .../src/DiscordMessageExtensions.cs | 13 -------- X10D.DSharpPlus/src/DiscordUserExtensions.cs | 19 ------------ 7 files changed, 2 insertions(+), 101 deletions(-) diff --git a/X10D.DSharpPlus/src/DiscordChannelExtensions.cs b/X10D.DSharpPlus/src/DiscordChannelExtensions.cs index 2734af9..820ced0 100644 --- a/X10D.DSharpPlus/src/DiscordChannelExtensions.cs +++ b/X10D.DSharpPlus/src/DiscordChannelExtensions.cs @@ -19,14 +19,10 @@ public static class DiscordChannelExtensions /// is . public static DiscordChannel? GetCategory(this DiscordChannel channel) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(channel); -#else if (channel is null) { throw new ArgumentNullException(nameof(channel)); } -#endif while (true) { @@ -60,10 +56,6 @@ public static class DiscordChannelExtensions /// public static async Task NormalizeClientAsync(this DiscordChannel channel, DiscordClient client) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(channel); - ArgumentNullException.ThrowIfNull(client); -#else if (channel is null) { throw new ArgumentNullException(nameof(channel)); @@ -73,7 +65,6 @@ public static class DiscordChannelExtensions { throw new ArgumentNullException(nameof(client)); } -#endif return await client.GetChannelAsync(channel.Id).ConfigureAwait(false); } diff --git a/X10D.DSharpPlus/src/DiscordClientExtensions.cs b/X10D.DSharpPlus/src/DiscordClientExtensions.cs index f3d8964..5dfd415 100644 --- a/X10D.DSharpPlus/src/DiscordClientExtensions.cs +++ b/X10D.DSharpPlus/src/DiscordClientExtensions.cs @@ -20,14 +20,10 @@ public static class DiscordClientExtensions /// is . public static void AutoJoinThreads(this DiscordClient client, bool rejoinIfRemoved = true) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(client); -#else if (client is null) { throw new ArgumentNullException(nameof(client)); } -#endif client.GuildAvailable += (_, args) => args.Guild.JoinAllThreadsAsync(); client.ThreadCreated += (_, args) => args.Thread.JoinThreadAsync(); @@ -53,14 +49,10 @@ public static class DiscordClientExtensions /// is . public static async Task GetUserOrNullAsync(this DiscordClient client, ulong userId) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(client); -#else if (client is null) { throw new ArgumentNullException(nameof(client)); } -#endif try { diff --git a/X10D.DSharpPlus/src/DiscordEmbedBuilderExtensions.cs b/X10D.DSharpPlus/src/DiscordEmbedBuilderExtensions.cs index 4a23a34..1c2c479 100644 --- a/X10D.DSharpPlus/src/DiscordEmbedBuilderExtensions.cs +++ b/X10D.DSharpPlus/src/DiscordEmbedBuilderExtensions.cs @@ -23,14 +23,10 @@ public static class DiscordEmbedBuilderExtensions T? value, bool inline = false) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(builder); -#else if (builder is null) { throw new ArgumentNullException(nameof(builder)); } -#endif return builder.AddField(name, value?.ToString(), inline); } @@ -53,14 +49,10 @@ public static class DiscordEmbedBuilderExtensions T? value, bool inline = false) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(builder); -#else if (builder is null) { throw new ArgumentNullException(nameof(builder)); } -#endif if (condition) { @@ -92,10 +84,6 @@ public static class DiscordEmbedBuilderExtensions T? value, bool inline = false) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(builder); - ArgumentNullException.ThrowIfNull(predicate); -#else if (builder is null) { throw new ArgumentNullException(nameof(builder)); @@ -105,7 +93,6 @@ public static class DiscordEmbedBuilderExtensions { throw new ArgumentNullException(nameof(predicate)); } -#endif if (predicate.Invoke()) { @@ -139,11 +126,6 @@ public static class DiscordEmbedBuilderExtensions Func valueFactory, bool inline = false) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(builder); - ArgumentNullException.ThrowIfNull(predicate); - ArgumentNullException.ThrowIfNull(valueFactory); -#else if (builder is null) { throw new ArgumentNullException(nameof(builder)); @@ -158,7 +140,6 @@ public static class DiscordEmbedBuilderExtensions { throw new ArgumentNullException(nameof(valueFactory)); } -#endif if (predicate.Invoke()) { @@ -190,19 +171,15 @@ public static class DiscordEmbedBuilderExtensions Func valueFactory, bool inline = false) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(builder); - ArgumentNullException.ThrowIfNull(valueFactory); -#else if (builder is null) { throw new ArgumentNullException(nameof(builder)); } + if (valueFactory is null) { throw new ArgumentNullException(nameof(valueFactory)); } -#endif if (condition) { @@ -220,19 +197,15 @@ public static class DiscordEmbedBuilderExtensions /// The current instance of . public static DiscordEmbedBuilder WithAuthor(this DiscordEmbedBuilder builder, DiscordUser user) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(builder); - ArgumentNullException.ThrowIfNull(user); -#else if (builder is null) { throw new ArgumentNullException(nameof(builder)); } + if (user is null) { throw new ArgumentNullException(nameof(user)); } -#endif return builder.WithAuthor(user.GetUsernameWithDiscriminator(), iconUrl: user.AvatarUrl); } diff --git a/X10D.DSharpPlus/src/DiscordGuildExtensions.cs b/X10D.DSharpPlus/src/DiscordGuildExtensions.cs index c03016b..ff4636e 100644 --- a/X10D.DSharpPlus/src/DiscordGuildExtensions.cs +++ b/X10D.DSharpPlus/src/DiscordGuildExtensions.cs @@ -16,14 +16,10 @@ public static class DiscordGuildExtensions /// is . public static async Task JoinAllThreadsAsync(this DiscordGuild guild) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(guild); -#else if (guild is null) { throw new ArgumentNullException(nameof(guild)); } -#endif await Task.WhenAll(guild.Threads.Values.Select(t => t.JoinThreadAsync())).ConfigureAwait(false); } @@ -37,14 +33,10 @@ public static class DiscordGuildExtensions /// is . public static async Task GetMemberOrNullAsync(this DiscordGuild guild, ulong userId) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(guild); -#else if (guild is null) { throw new ArgumentNullException(nameof(guild)); } -#endif try { @@ -77,10 +69,6 @@ public static class DiscordGuildExtensions /// public static async Task NormalizeClientAsync(this DiscordGuild guild, DiscordClient client) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(guild); - ArgumentNullException.ThrowIfNull(client); -#else if (guild is null) { throw new ArgumentNullException(nameof(guild)); @@ -90,7 +78,6 @@ public static class DiscordGuildExtensions { throw new ArgumentNullException(nameof(client)); } -#endif return await client.GetGuildAsync(guild.Id).ConfigureAwait(false); } diff --git a/X10D.DSharpPlus/src/DiscordMemberExtensions.cs b/X10D.DSharpPlus/src/DiscordMemberExtensions.cs index 3fd2020..7ec9925 100644 --- a/X10D.DSharpPlus/src/DiscordMemberExtensions.cs +++ b/X10D.DSharpPlus/src/DiscordMemberExtensions.cs @@ -18,10 +18,6 @@ public static class DiscordMemberExtensions /// public static bool HasRole(this DiscordMember member, DiscordRole role) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(member); - ArgumentNullException.ThrowIfNull(role); -#else if (member is null) { throw new ArgumentNullException(nameof(member)); @@ -31,7 +27,6 @@ public static class DiscordMemberExtensions { throw new ArgumentNullException(nameof(role)); } -#endif return member.Roles.Contains(role); } @@ -52,10 +47,6 @@ public static class DiscordMemberExtensions /// public static async Task NormalizeClientAsync(this DiscordMember member, DiscordClient client) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(member); - ArgumentNullException.ThrowIfNull(client); -#else if (member is null) { throw new ArgumentNullException(nameof(member)); @@ -65,7 +56,6 @@ public static class DiscordMemberExtensions { throw new ArgumentNullException(nameof(client)); } -#endif DiscordGuild guild = await member.Guild.NormalizeClientAsync(client).ConfigureAwait(false); return await guild.GetMemberAsync(member.Id).ConfigureAwait(false); diff --git a/X10D.DSharpPlus/src/DiscordMessageExtensions.cs b/X10D.DSharpPlus/src/DiscordMessageExtensions.cs index f8317c7..f43116d 100644 --- a/X10D.DSharpPlus/src/DiscordMessageExtensions.cs +++ b/X10D.DSharpPlus/src/DiscordMessageExtensions.cs @@ -17,14 +17,10 @@ public static class DiscordMessageExtensions /// is . public static async Task DeleteAfterAsync(this DiscordMessage message, TimeSpan delay, string? reason = null) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(message); -#else if (message is null) { throw new ArgumentNullException(nameof(message)); } -#endif await Task.Delay(delay).ConfigureAwait(false); await message.DeleteAsync(reason).ConfigureAwait(false); @@ -39,14 +35,10 @@ public static class DiscordMessageExtensions /// is . public static async Task DeleteAfterAsync(this Task task, TimeSpan delay, string? reason = null) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(task); -#else if (task is null) { throw new ArgumentNullException(nameof(task)); } -#endif DiscordMessage message = await task.ConfigureAwait(false); await message.DeleteAfterAsync(delay, reason).ConfigureAwait(false); @@ -68,10 +60,6 @@ public static class DiscordMessageExtensions /// public static async Task NormalizeClientAsync(this DiscordMessage message, DiscordClient client) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(message); - ArgumentNullException.ThrowIfNull(client); -#else if (message is null) { throw new ArgumentNullException(nameof(message)); @@ -81,7 +69,6 @@ public static class DiscordMessageExtensions { throw new ArgumentNullException(nameof(client)); } -#endif DiscordChannel channel = await message.Channel.NormalizeClientAsync(client).ConfigureAwait(false); return await channel.GetMessageAsync(message.Id).ConfigureAwait(false); diff --git a/X10D.DSharpPlus/src/DiscordUserExtensions.cs b/X10D.DSharpPlus/src/DiscordUserExtensions.cs index 6ab8314..adfd477 100644 --- a/X10D.DSharpPlus/src/DiscordUserExtensions.cs +++ b/X10D.DSharpPlus/src/DiscordUserExtensions.cs @@ -25,10 +25,6 @@ public static class DiscordUserExtensions /// public static async Task GetAsMemberOfAsync(this DiscordUser user, DiscordGuild guild) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(user); - ArgumentNullException.ThrowIfNull(guild); -#else if (user is null) { throw new ArgumentNullException(nameof(user)); @@ -38,7 +34,6 @@ public static class DiscordUserExtensions { throw new ArgumentNullException(nameof(guild)); } -#endif if (user is DiscordMember member && member.Guild == guild) { @@ -68,14 +63,10 @@ public static class DiscordUserExtensions /// is . public static string GetUsernameWithDiscriminator(this DiscordUser user) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(user); -#else if (user is null) { throw new ArgumentNullException(nameof(user)); } -#endif return $"{user.Username}#{user.Discriminator}"; } @@ -91,10 +82,6 @@ public static class DiscordUserExtensions /// public static async Task IsInGuildAsync(this DiscordUser user, DiscordGuild guild) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(user); - ArgumentNullException.ThrowIfNull(guild); -#else if (user is null) { throw new ArgumentNullException(nameof(user)); @@ -104,7 +91,6 @@ public static class DiscordUserExtensions { throw new ArgumentNullException(nameof(guild)); } -#endif if (guild.Members.TryGetValue(user.Id, out _)) { @@ -138,10 +124,6 @@ public static class DiscordUserExtensions /// public static async Task NormalizeClientAsync(this DiscordUser user, DiscordClient client) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(user); - ArgumentNullException.ThrowIfNull(client); -#else if (user is null) { throw new ArgumentNullException(nameof(user)); @@ -151,7 +133,6 @@ public static class DiscordUserExtensions { throw new ArgumentNullException(nameof(client)); } -#endif return await client.GetUserAsync(user.Id).ConfigureAwait(false); } From bb3659c0472fa701c4499ef79c5c500d573ddcf6 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Thu, 13 Apr 2023 22:52:46 +0100 Subject: [PATCH 054/102] refactor: remove throw helpers (#80) --- X10D/src/Collections/ArrayExtensions.cs | 12 --- X10D/src/Collections/BoolListExtensions.cs | 16 ---- X10D/src/Collections/CollectionExtensions.cs | 8 -- X10D/src/Collections/DictionaryExtensions.cs | 64 -------------- X10D/src/Collections/EnumerableExtensions.cs | 56 ------------- X10D/src/Collections/ListExtensions.cs | 45 ---------- X10D/src/Core/RandomExtensions.cs | 66 --------------- X10D/src/Drawing/Polygon.cs | 16 ---- X10D/src/Drawing/PolygonF.cs | 24 ------ X10D/src/Drawing/Polyhedron.cs | 16 ---- X10D/src/Drawing/RandomExtensions.cs | 8 -- X10D/src/IO/DirectoryInfoExtensions.cs | 4 - X10D/src/IO/FileInfoExtensions.cs | 8 -- X10D/src/IO/ListOfByteExtensions.cs | 41 --------- X10D/src/IO/StreamExtensions.cs | 80 ------------------ X10D/src/IO/TextReaderExtensions.cs | 8 -- ...riterExtensions.WriteLineNoAlloc.Double.cs | 12 --- ...WriterExtensions.WriteLineNoAlloc.Int32.cs | 12 --- ...WriterExtensions.WriteLineNoAlloc.Int64.cs | 12 --- ...riterExtensions.WriteLineNoAlloc.Single.cs | 12 --- ...riterExtensions.WriteLineNoAlloc.UInt32.cs | 12 --- ...riterExtensions.WriteLineNoAlloc.UInt64.cs | 12 --- ...extWriterExtensions.WriteNoAlloc.Double.cs | 12 --- ...TextWriterExtensions.WriteNoAlloc.Int32.cs | 12 --- ...TextWriterExtensions.WriteNoAlloc.Int64.cs | 12 --- ...extWriterExtensions.WriteNoAlloc.Single.cs | 12 --- ...extWriterExtensions.WriteNoAlloc.UInt32.cs | 12 --- ...extWriterExtensions.WriteNoAlloc.UInt64.cs | 12 --- X10D/src/Linq/ByteExtensions.cs | 16 ---- X10D/src/Linq/DecimalExtensions.cs | 8 -- X10D/src/Linq/DoubleExtensions.cs | 8 -- X10D/src/Linq/EnumerableExtensions.cs | 36 -------- X10D/src/Linq/Int32Extensions.cs | 16 ---- X10D/src/Linq/Int64Extensions.cs | 16 ---- X10D/src/Linq/ReadOnlySpanExtensions.cs | 12 --- X10D/src/Linq/SingleExtensions.cs | 8 -- X10D/src/Linq/SpanExtensions.cs | 12 --- X10D/src/Math/ComparableExtensions.cs | 32 ------- X10D/src/Net/EndPointExtensions.cs | 8 -- X10D/src/Net/IPAddressExtensions.cs | 8 -- X10D/src/Numerics/RandomExtensions.cs | 16 ---- X10D/src/Reactive/ObservableDisposer.cs | 19 +---- X10D/src/Reactive/ProgressExtensions.cs | 8 -- X10D/src/Reactive/ProgressObservable.cs | 4 - X10D/src/Reflection/MemberInfoExtensions.cs | 20 +---- X10D/src/Reflection/TypeExtensions.cs | 18 ---- X10D/src/Text/EnumerableExtensions.cs | 10 --- X10D/src/Text/StringBuilderReader.cs | 4 - X10D/src/Text/StringExtensions.cs | 83 ------------------- X10D/src/Time/StringExtensions.cs | 4 - 50 files changed, 3 insertions(+), 979 deletions(-) diff --git a/X10D/src/Collections/ArrayExtensions.cs b/X10D/src/Collections/ArrayExtensions.cs index c6ed75b..7dd5863 100644 --- a/X10D/src/Collections/ArrayExtensions.cs +++ b/X10D/src/Collections/ArrayExtensions.cs @@ -17,14 +17,10 @@ public static class ArrayExtensions [Pure] public static IReadOnlyCollection AsReadOnly(this T[] array) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(array); -#else if (array is null) { throw new ArgumentNullException(nameof(array)); } -#endif return Array.AsReadOnly(array); } @@ -49,14 +45,10 @@ public static class ArrayExtensions /// is . public static void Clear(this T?[] array, Range range) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(array); -#else if (array is null) { throw new ArgumentNullException(nameof(array)); } -#endif (int offset, int length) = range.GetOffsetAndLength(array.Length); array.Clear(offset, length); @@ -79,14 +71,10 @@ public static class ArrayExtensions /// public static void Clear(this T?[] array, int index, int length) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(array); -#else if (array is null) { throw new ArgumentNullException(nameof(array)); } -#endif if (length == 0 || array.Length == 0) { diff --git a/X10D/src/Collections/BoolListExtensions.cs b/X10D/src/Collections/BoolListExtensions.cs index 347d19b..6258617 100644 --- a/X10D/src/Collections/BoolListExtensions.cs +++ b/X10D/src/Collections/BoolListExtensions.cs @@ -18,14 +18,10 @@ public static class BoolListExtensions [Pure] public static byte PackByte(this IReadOnlyList source) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif if (source.Count > 8) { @@ -52,14 +48,10 @@ public static class BoolListExtensions [Pure] public static short PackInt16(this IReadOnlyList source) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif if (source.Count > 16) { @@ -86,14 +78,10 @@ public static class BoolListExtensions [Pure] public static int PackInt32(this IReadOnlyList source) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif if (source.Count > 32) { @@ -120,14 +108,10 @@ public static class BoolListExtensions [Pure] public static long PackInt64(this IReadOnlyList source) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif if (source.Count > 64) { diff --git a/X10D/src/Collections/CollectionExtensions.cs b/X10D/src/Collections/CollectionExtensions.cs index 3554586..e9b2c6e 100644 --- a/X10D/src/Collections/CollectionExtensions.cs +++ b/X10D/src/Collections/CollectionExtensions.cs @@ -16,14 +16,10 @@ public static class CollectionExtensions /// public static void ClearAndDisposeAll(this ICollection source) where T : IDisposable { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif if (source.IsReadOnly) { @@ -55,14 +51,10 @@ public static class CollectionExtensions /// public static async Task ClearAndDisposeAllAsync(this ICollection source) where T : IAsyncDisposable { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif if (source.IsReadOnly) { diff --git a/X10D/src/Collections/DictionaryExtensions.cs b/X10D/src/Collections/DictionaryExtensions.cs index 66823b0..241efe9 100644 --- a/X10D/src/Collections/DictionaryExtensions.cs +++ b/X10D/src/Collections/DictionaryExtensions.cs @@ -37,10 +37,6 @@ public static class DictionaryExtensions Func updateValueFactory) where TKey : notnull { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(dictionary); - ArgumentNullException.ThrowIfNull(updateValueFactory); -#else if (dictionary is null) { throw new ArgumentNullException(nameof(dictionary)); @@ -50,7 +46,6 @@ public static class DictionaryExtensions { throw new ArgumentNullException(nameof(updateValueFactory)); } -#endif #if NET6_0_OR_GREATER ref var value = ref CollectionsMarshal.GetValueRefOrAddDefault(dictionary, key, out bool exists); @@ -97,10 +92,6 @@ public static class DictionaryExtensions Func updateValueFactory) where TKey : notnull { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(dictionary); - ArgumentNullException.ThrowIfNull(updateValueFactory); -#else if (dictionary is null) { throw new ArgumentNullException(nameof(dictionary)); @@ -110,7 +101,6 @@ public static class DictionaryExtensions { throw new ArgumentNullException(nameof(updateValueFactory)); } -#endif if (dictionary.TryGetValue(key, out TValue? old)) { @@ -152,11 +142,6 @@ public static class DictionaryExtensions Func addValueFactory, Func updateValueFactory) where TKey : notnull { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(dictionary); - ArgumentNullException.ThrowIfNull(addValueFactory); - ArgumentNullException.ThrowIfNull(updateValueFactory); -#else if (dictionary is null) { throw new ArgumentNullException(nameof(dictionary)); @@ -171,7 +156,6 @@ public static class DictionaryExtensions { throw new ArgumentNullException(nameof(updateValueFactory)); } -#endif #if NET6_0_OR_GREATER ref TValue? value = ref CollectionsMarshal.GetValueRefOrAddDefault(dictionary, key, out bool exists); @@ -222,11 +206,6 @@ public static class DictionaryExtensions Func addValueFactory, Func updateValueFactory) where TKey : notnull { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(dictionary); - ArgumentNullException.ThrowIfNull(addValueFactory); - ArgumentNullException.ThrowIfNull(updateValueFactory); -#else if (dictionary is null) { throw new ArgumentNullException(nameof(dictionary)); @@ -241,7 +220,6 @@ public static class DictionaryExtensions { throw new ArgumentNullException(nameof(updateValueFactory)); } -#endif if (dictionary.TryGetValue(key, out TValue? old)) { @@ -291,11 +269,6 @@ public static class DictionaryExtensions Func addValueFactory, Func updateValueFactory, TArg factoryArgument) where TKey : notnull { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(dictionary); - ArgumentNullException.ThrowIfNull(addValueFactory); - ArgumentNullException.ThrowIfNull(updateValueFactory); -#else if (dictionary is null) { throw new ArgumentNullException(nameof(dictionary)); @@ -310,7 +283,6 @@ public static class DictionaryExtensions { throw new ArgumentNullException(nameof(updateValueFactory)); } -#endif #if NET6_0_OR_GREATER ref TValue? value = ref CollectionsMarshal.GetValueRefOrAddDefault(dictionary, key, out bool exists); @@ -367,11 +339,6 @@ public static class DictionaryExtensions Func addValueFactory, Func updateValueFactory, TArg factoryArgument) where TKey : notnull { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(dictionary); - ArgumentNullException.ThrowIfNull(addValueFactory); - ArgumentNullException.ThrowIfNull(updateValueFactory); -#else if (dictionary is null) { throw new ArgumentNullException(nameof(dictionary)); @@ -386,7 +353,6 @@ public static class DictionaryExtensions { throw new ArgumentNullException(nameof(updateValueFactory)); } -#endif if (dictionary.TryGetValue(key, out TValue? old)) { @@ -414,14 +380,10 @@ public static class DictionaryExtensions [Pure] public static string ToConnectionString(this IEnumerable> source) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif static string SanitizeValue(string? value) { @@ -461,10 +423,6 @@ public static class DictionaryExtensions public static string ToConnectionString(this IEnumerable> source, Func selector) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); - ArgumentNullException.ThrowIfNull(selector); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); @@ -474,7 +432,6 @@ public static class DictionaryExtensions { throw new ArgumentNullException(nameof(selector)); } -#endif static string SanitizeValue(string? value) { @@ -520,11 +477,6 @@ public static class DictionaryExtensions Func keySelector, Func valueSelector) where TKey : notnull { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); - ArgumentNullException.ThrowIfNull(keySelector); - ArgumentNullException.ThrowIfNull(valueSelector); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); @@ -539,7 +491,6 @@ public static class DictionaryExtensions { throw new ArgumentNullException(nameof(valueSelector)); } -#endif static string SanitizeValue(string? value) { @@ -571,14 +522,10 @@ public static class DictionaryExtensions public static string ToGetParameters(this IEnumerable> source) where TKey : notnull { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif static string GetQueryParameter(KeyValuePair pair) { @@ -610,10 +557,6 @@ public static class DictionaryExtensions Func selector) where TKey : notnull { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); - ArgumentNullException.ThrowIfNull(selector); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); @@ -623,7 +566,6 @@ public static class DictionaryExtensions { throw new ArgumentNullException(nameof(selector)); } -#endif // can't static here because of 'selector' parameter string GetQueryParameter(KeyValuePair pair) @@ -661,11 +603,6 @@ public static class DictionaryExtensions Func keySelector, Func valueSelector) where TKey : notnull { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); - ArgumentNullException.ThrowIfNull(keySelector); - ArgumentNullException.ThrowIfNull(valueSelector); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); @@ -680,7 +617,6 @@ public static class DictionaryExtensions { throw new ArgumentNullException(nameof(valueSelector)); } -#endif // can't static here because of selector parameters string GetQueryParameter(KeyValuePair pair) diff --git a/X10D/src/Collections/EnumerableExtensions.cs b/X10D/src/Collections/EnumerableExtensions.cs index c38e4df..a183c2b 100644 --- a/X10D/src/Collections/EnumerableExtensions.cs +++ b/X10D/src/Collections/EnumerableExtensions.cs @@ -24,10 +24,6 @@ public static class EnumerableExtensions [Pure] public static int CountWhereNot(this IEnumerable source, Func predicate) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); - ArgumentNullException.ThrowIfNull(predicate); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); @@ -37,7 +33,6 @@ public static class EnumerableExtensions { throw new ArgumentNullException(nameof(predicate)); } -#endif return source.Count(item => !predicate(item)); } @@ -58,10 +53,6 @@ public static class EnumerableExtensions [Pure] public static TSource FirstWhereNot(this IEnumerable source, Func predicate) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); - ArgumentNullException.ThrowIfNull(predicate); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); @@ -71,7 +62,6 @@ public static class EnumerableExtensions { throw new ArgumentNullException(nameof(predicate)); } -#endif return source.First(item => !predicate(item)); } @@ -91,10 +81,6 @@ public static class EnumerableExtensions [Pure] public static TSource? FirstWhereNotOrDefault(this IEnumerable source, Func predicate) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); - ArgumentNullException.ThrowIfNull(predicate); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); @@ -104,7 +90,6 @@ public static class EnumerableExtensions { throw new ArgumentNullException(nameof(predicate)); } -#endif return source.FirstOrDefault(item => !predicate(item)); } @@ -127,10 +112,6 @@ public static class EnumerableExtensions /// public static void For(this IEnumerable source, Action action) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); - ArgumentNullException.ThrowIfNull(action); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); @@ -140,7 +121,6 @@ public static class EnumerableExtensions { throw new ArgumentNullException(nameof(action)); } -#endif var index = 0; foreach (T item in source) @@ -166,10 +146,6 @@ public static class EnumerableExtensions /// public static void ForEach(this IEnumerable source, Action action) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); - ArgumentNullException.ThrowIfNull(action); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); @@ -179,7 +155,6 @@ public static class EnumerableExtensions { throw new ArgumentNullException(nameof(action)); } -#endif foreach (T item in source) { @@ -196,14 +171,10 @@ public static class EnumerableExtensions /// public static void DisposeAll(this IEnumerable source) where T : IDisposable { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif foreach (T item in source) { @@ -227,14 +198,10 @@ public static class EnumerableExtensions /// public static async Task DisposeAllAsync(this IEnumerable source) where T : IAsyncDisposable { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif foreach (T item in source) { @@ -264,10 +231,6 @@ public static class EnumerableExtensions [Pure] public static TSource LastWhereNot(this IEnumerable source, Func predicate) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); - ArgumentNullException.ThrowIfNull(predicate); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); @@ -277,7 +240,6 @@ public static class EnumerableExtensions { throw new ArgumentNullException(nameof(predicate)); } -#endif return source.Last(item => !predicate(item)); } @@ -297,10 +259,6 @@ public static class EnumerableExtensions [Pure] public static TSource? LastWhereNotOrDefault(this IEnumerable source, Func predicate) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); - ArgumentNullException.ThrowIfNull(predicate); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); @@ -310,7 +268,6 @@ public static class EnumerableExtensions { throw new ArgumentNullException(nameof(predicate)); } -#endif return source.LastOrDefault(item => !predicate(item)); } @@ -326,14 +283,10 @@ public static class EnumerableExtensions [Pure] public static IReadOnlyCollection Shuffled(this IEnumerable source, Random? random = null) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif var list = new List(source); list.Shuffle(random); @@ -355,10 +308,6 @@ public static class EnumerableExtensions [Pure] public static IEnumerable WhereNot(this IEnumerable source, Func predicate) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); - ArgumentNullException.ThrowIfNull(predicate); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); @@ -368,7 +317,6 @@ public static class EnumerableExtensions { throw new ArgumentNullException(nameof(predicate)); } -#endif return source.Where(item => !predicate(item)); } @@ -386,14 +334,10 @@ public static class EnumerableExtensions /// is . public static IEnumerable WhereNotNull(this IEnumerable source) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif return source.Where(item => item is not null).Select(item => item!); } diff --git a/X10D/src/Collections/ListExtensions.cs b/X10D/src/Collections/ListExtensions.cs index 69292b4..be53ee8 100644 --- a/X10D/src/Collections/ListExtensions.cs +++ b/X10D/src/Collections/ListExtensions.cs @@ -19,14 +19,10 @@ public static class ListExtensions /// is . public static void Fill(this IList source, T value) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif for (var i = 0; i < source.Count; i++) { @@ -53,14 +49,10 @@ public static class ListExtensions /// public static void Fill(this IList source, T value, int startIndex, int count) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif if (startIndex < 0) { @@ -105,14 +97,10 @@ public static class ListExtensions /// is . public static int IndexOf(this IReadOnlyList source, T? item) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif return source.IndexOf(item, 0, source.Count); } @@ -138,14 +126,10 @@ public static class ListExtensions /// public static int IndexOf(this IReadOnlyList source, T? item, int startIndex) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif return source.IndexOf(item, startIndex, source.Count - startIndex); } @@ -182,14 +166,10 @@ public static class ListExtensions /// public static int IndexOf(this IReadOnlyList source, T? item, int startIndex, int count) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif if (startIndex < 0 || startIndex > source.Count) { @@ -233,14 +213,10 @@ public static class ListExtensions [Pure] public static T Random(this IReadOnlyList source, Random? random = null) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif random ??= RandomExtensions.GetShared(); return random.NextFrom(source); @@ -260,14 +236,10 @@ public static class ListExtensions /// public static void RemoveRange(this IList source, Range range) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif int start = range.Start.IsFromEnd ? source.Count - range.Start.Value : range.Start.Value; int end = range.End.IsFromEnd ? source.Count - range.End.Value : range.End.Value; @@ -300,14 +272,10 @@ public static class ListExtensions /// is . public static void Shuffle(this IList source, Random? random = null) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif random ??= RandomExtensions.GetShared(); @@ -334,14 +302,10 @@ public static class ListExtensions /// public static IReadOnlyList Slice(this IReadOnlyList source, int start) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif return source.Slice(start, source.Count - start); } @@ -363,14 +327,10 @@ public static class ListExtensions /// public static IReadOnlyList Slice(this IReadOnlyList source, int start, int length) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif if (start < 0 || start > source.Count) { @@ -406,10 +366,6 @@ public static class ListExtensions /// public static void Swap(this IList source, IList other) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); - ArgumentNullException.ThrowIfNull(other); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); @@ -419,7 +375,6 @@ public static class ListExtensions { throw new ArgumentNullException(nameof(other)); } -#endif int min = System.Math.Min(source.Count, other.Count); for (var index = 0; index < min; index++) diff --git a/X10D/src/Core/RandomExtensions.cs b/X10D/src/Core/RandomExtensions.cs index 32acc3b..49e8634 100644 --- a/X10D/src/Core/RandomExtensions.cs +++ b/X10D/src/Core/RandomExtensions.cs @@ -27,14 +27,10 @@ public static class RandomExtensions public static T Next(this Random random) where T : struct, Enum { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(random); -#else if (random is null) { throw new ArgumentNullException(nameof(random)); } -#endif var values = Enum.GetValues(typeof(T)); return (T)values.GetValue(random.Next(values.Length))!; @@ -54,14 +50,10 @@ public static class RandomExtensions /// is . public static bool NextBoolean(this Random random) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(random); -#else if (random is null) { throw new ArgumentNullException(nameof(random)); } -#endif return random.NextDouble() >= 0.5; } @@ -81,14 +73,10 @@ public static class RandomExtensions /// is less than 0. public static double NextDouble(this Random random, double maxValue) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(random); -#else if (random is null) { throw new ArgumentNullException(nameof(random)); } -#endif if (maxValue < 0) { @@ -117,14 +105,10 @@ public static class RandomExtensions /// public static double NextDouble(this Random random, double minValue, double maxValue) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(random); -#else if (random is null) { throw new ArgumentNullException(nameof(random)); } -#endif if (maxValue < minValue) { @@ -155,10 +139,6 @@ public static class RandomExtensions /// public static T NextFrom(this Random random, IEnumerable source) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(random); - ArgumentNullException.ThrowIfNull(source); -#else if (random is null) { throw new ArgumentNullException(nameof(random)); @@ -168,7 +148,6 @@ public static class RandomExtensions { throw new ArgumentNullException(nameof(source)); } -#endif if (source is T[] array) { @@ -206,14 +185,10 @@ public static class RandomExtensions /// public static T NextFrom(this Random random, Span source) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(random); -#else if (random is null) { throw new ArgumentNullException(nameof(random)); } -#endif return source[random.Next(source.Length)]; } @@ -242,14 +217,10 @@ public static class RandomExtensions /// public static T NextFrom(this Random random, ReadOnlySpan source) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(random); -#else if (random is null) { throw new ArgumentNullException(nameof(random)); } -#endif return source[random.Next(source.Length)]; } @@ -264,14 +235,10 @@ public static class RandomExtensions /// is . public static byte NextByte(this Random random) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(random); -#else if (random is null) { throw new ArgumentNullException(nameof(random)); } -#endif return random.NextByte(byte.MaxValue); } @@ -292,14 +259,10 @@ public static class RandomExtensions /// is . public static byte NextByte(this Random random, byte maxValue) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(random); -#else if (random is null) { throw new ArgumentNullException(nameof(random)); } -#endif return random.NextByte(0, maxValue); } @@ -325,14 +288,10 @@ public static class RandomExtensions /// public static byte NextByte(this Random random, byte minValue, byte maxValue) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(random); -#else if (random is null) { throw new ArgumentNullException(nameof(random)); } -#endif return (byte)random.Next(minValue, maxValue); } @@ -347,14 +306,10 @@ public static class RandomExtensions /// is . public static short NextInt16(this Random random) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(random); -#else if (random is null) { throw new ArgumentNullException(nameof(random)); } -#endif return random.NextInt16(short.MaxValue); } @@ -376,14 +331,10 @@ public static class RandomExtensions /// is less than 0. public static short NextInt16(this Random random, short maxValue) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(random); -#else if (random is null) { throw new ArgumentNullException(nameof(random)); } -#endif if (maxValue < 0) { @@ -414,14 +365,10 @@ public static class RandomExtensions /// is . public static short NextInt16(this Random random, short minValue, short maxValue) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(random); -#else if (random is null) { throw new ArgumentNullException(nameof(random)); } -#endif return (short)random.Next(minValue, maxValue); } @@ -459,14 +406,10 @@ public static class RandomExtensions /// is less than 0. public static float NextSingle(this Random random, float maxValue) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(random); -#else if (random is null) { throw new ArgumentNullException(nameof(random)); } -#endif if (maxValue < 0) { @@ -495,14 +438,10 @@ public static class RandomExtensions /// public static float NextSingle(this Random random, float minValue, float maxValue) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(random); -#else if (random is null) { throw new ArgumentNullException(nameof(random)); } -#endif if (maxValue < minValue) { @@ -530,10 +469,6 @@ public static class RandomExtensions /// is less than 0. public static string NextString(this Random random, IReadOnlyList source, int length) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(random); - ArgumentNullException.ThrowIfNull(source); -#else if (random is null) { throw new ArgumentNullException(nameof(random)); @@ -543,7 +478,6 @@ public static class RandomExtensions { throw new ArgumentNullException(nameof(source)); } -#endif if (length < 0) { diff --git a/X10D/src/Drawing/Polygon.cs b/X10D/src/Drawing/Polygon.cs index 63abae8..9f03b58 100644 --- a/X10D/src/Drawing/Polygon.cs +++ b/X10D/src/Drawing/Polygon.cs @@ -22,14 +22,10 @@ public class Polygon : IEquatable /// public Polygon(Polygon polygon) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(polygon); -#else if (polygon is null) { throw new ArgumentNullException(nameof(polygon)); } -#endif _vertices = new List(); for (var index = 0; index < polygon._vertices.Count; index++) @@ -45,14 +41,10 @@ public class Polygon : IEquatable /// An enumerable collection of vertices from which the polygon should be constructed. public Polygon(IEnumerable vertices) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(vertices); -#else if (vertices is null) { throw new ArgumentNullException(nameof(vertices)); } -#endif _vertices = new List(vertices); } @@ -176,14 +168,10 @@ public class Polygon : IEquatable /// is . public static Polygon FromPolygonF(PolygonF polygon) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(polygon); -#else if (polygon is null) { throw new ArgumentNullException(nameof(polygon)); } -#endif var vertices = new List(); @@ -211,14 +199,10 @@ public class Polygon : IEquatable /// is . public void AddVertices(IEnumerable vertices) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(vertices); -#else if (vertices is null) { throw new ArgumentNullException(nameof(vertices)); } -#endif foreach (Point vertex in vertices) { diff --git a/X10D/src/Drawing/PolygonF.cs b/X10D/src/Drawing/PolygonF.cs index 51d9eeb..074edc3 100644 --- a/X10D/src/Drawing/PolygonF.cs +++ b/X10D/src/Drawing/PolygonF.cs @@ -25,14 +25,10 @@ public class PolygonF /// is . public PolygonF(PolygonF polygon) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(polygon); -#else if (polygon is null) { throw new ArgumentNullException(nameof(polygon)); } -#endif _vertices = new List(); for (var index = 0; index < polygon._vertices.Count; index++) { @@ -48,14 +44,10 @@ public class PolygonF /// is . public PolygonF(IEnumerable vertices) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(vertices); -#else if (vertices is null) { throw new ArgumentNullException(nameof(vertices)); } -#endif _vertices = new List(); foreach (Vector2 vertex in vertices) @@ -71,14 +63,10 @@ public class PolygonF /// is . public PolygonF(IEnumerable vertices) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(vertices); -#else if (vertices is null) { throw new ArgumentNullException(nameof(vertices)); } -#endif _vertices = new List(vertices); } @@ -202,14 +190,10 @@ public class PolygonF /// is . public static PolygonF FromPolygon(Polygon polygon) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(polygon); -#else if (polygon is null) { throw new ArgumentNullException(nameof(polygon)); } -#endif var vertices = new List(); @@ -246,14 +230,10 @@ public class PolygonF /// is . public void AddVertices(IEnumerable vertices) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(vertices); -#else if (vertices is null) { throw new ArgumentNullException(nameof(vertices)); } -#endif foreach (PointF vertex in vertices) { @@ -268,14 +248,10 @@ public class PolygonF /// is . public void AddVertices(IEnumerable vertices) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(vertices); -#else if (vertices is null) { throw new ArgumentNullException(nameof(vertices)); } -#endif foreach (Vector2 vertex in vertices) { diff --git a/X10D/src/Drawing/Polyhedron.cs b/X10D/src/Drawing/Polyhedron.cs index 2f46ca0..6be327e 100644 --- a/X10D/src/Drawing/Polyhedron.cs +++ b/X10D/src/Drawing/Polyhedron.cs @@ -34,14 +34,10 @@ public class Polyhedron : IEquatable /// is . public Polyhedron(IEnumerable vertices) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(vertices); -#else if (vertices is null) { throw new ArgumentNullException(nameof(vertices)); } -#endif _vertices = new List(vertices); } @@ -137,14 +133,10 @@ public class Polyhedron : IEquatable /// is . public static Polyhedron FromPolygon(Polygon polygon) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(polygon); -#else if (polygon is null) { throw new ArgumentNullException(nameof(polygon)); } -#endif var vertices = new List(); @@ -164,14 +156,10 @@ public class Polyhedron : IEquatable /// is . public static Polyhedron FromPolygonF(PolygonF polygon) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(polygon); -#else if (polygon is null) { throw new ArgumentNullException(nameof(polygon)); } -#endif var vertices = new List(); @@ -199,14 +187,10 @@ public class Polyhedron : IEquatable /// is . public void AddVertices(IEnumerable vertices) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(vertices); -#else if (vertices is null) { throw new ArgumentNullException(nameof(vertices)); } -#endif foreach (Vector3 vertex in vertices) { diff --git a/X10D/src/Drawing/RandomExtensions.cs b/X10D/src/Drawing/RandomExtensions.cs index 24c7419..880cd84 100644 --- a/X10D/src/Drawing/RandomExtensions.cs +++ b/X10D/src/Drawing/RandomExtensions.cs @@ -17,14 +17,10 @@ public static class RandomExtensions /// is . public static Color NextColorRgb(this Random random) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(random); -#else if (random is null) { throw new ArgumentNullException(nameof(random)); } -#endif int rgb = random.Next(); return Color.FromArgb(0xFF, (byte)(rgb >> 16 & 0xFF), (byte)(rgb >> 8 & 0xFF), (byte)(rgb & 0xFF)); @@ -38,14 +34,10 @@ public static class RandomExtensions /// is . public static Color NextColorArgb(this Random random) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(random); -#else if (random is null) { throw new ArgumentNullException(nameof(random)); } -#endif int argb = random.Next(); return Color.FromArgb(argb); diff --git a/X10D/src/IO/DirectoryInfoExtensions.cs b/X10D/src/IO/DirectoryInfoExtensions.cs index 5eb0a92..c6c7e81 100644 --- a/X10D/src/IO/DirectoryInfoExtensions.cs +++ b/X10D/src/IO/DirectoryInfoExtensions.cs @@ -33,14 +33,10 @@ public static class DirectoryInfoExtensions /// This directory or one of its children contain a read-only file. public static void Clear(this DirectoryInfo directory) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(directory); -#else if (directory is null) { throw new ArgumentNullException(nameof(directory)); } -#endif if (!directory.Exists) { diff --git a/X10D/src/IO/FileInfoExtensions.cs b/X10D/src/IO/FileInfoExtensions.cs index a0878bc..e1a4e69 100644 --- a/X10D/src/IO/FileInfoExtensions.cs +++ b/X10D/src/IO/FileInfoExtensions.cs @@ -29,14 +29,10 @@ public static class FileInfoExtensions public static byte[] GetHash(this FileInfo value) where T : HashAlgorithm { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(value); -#else if (value is null) { throw new ArgumentNullException(nameof(value)); } -#endif using FileStream stream = value.OpenRead(); return stream.GetHash(); @@ -69,14 +65,10 @@ public static class FileInfoExtensions public static bool TryWriteHash(this FileInfo value, Span destination, out int bytesWritten) where T : HashAlgorithm { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(value); -#else if (value is null) { throw new ArgumentNullException(nameof(value)); } -#endif using FileStream stream = value.OpenRead(); return stream.TryWriteHash(destination, out bytesWritten); diff --git a/X10D/src/IO/ListOfByteExtensions.cs b/X10D/src/IO/ListOfByteExtensions.cs index 3289fef..5d9122f 100644 --- a/X10D/src/IO/ListOfByteExtensions.cs +++ b/X10D/src/IO/ListOfByteExtensions.cs @@ -19,14 +19,10 @@ public static class ListOfByteExtensions /// is . public static string AsString(this IReadOnlyList source) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif return BitConverter.ToString(source.ToArray()); } @@ -54,14 +50,10 @@ public static class ListOfByteExtensions /// is . public static double ToDouble(this IReadOnlyList source, int startIndex) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif return BitConverter.ToDouble(source.ToArray(), startIndex); } @@ -86,14 +78,10 @@ public static class ListOfByteExtensions /// is . public static short ToInt16(this IReadOnlyList source, int startIndex) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif return BitConverter.ToInt16(source.ToArray(), startIndex); } @@ -118,14 +106,10 @@ public static class ListOfByteExtensions /// is . public static int ToInt32(this IReadOnlyList source, int startIndex) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif return BitConverter.ToInt32(source.ToArray(), startIndex); } @@ -150,14 +134,10 @@ public static class ListOfByteExtensions /// is . public static long ToInt64(this IReadOnlyList source, int startIndex) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif return BitConverter.ToInt64(source.ToArray(), startIndex); } @@ -183,14 +163,10 @@ public static class ListOfByteExtensions /// is . public static float ToSingle(this IReadOnlyList source, int startIndex) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif return BitConverter.ToSingle(source.ToArray(), startIndex); } @@ -208,10 +184,6 @@ public static class ListOfByteExtensions /// public static string ToString(this IReadOnlyList source, Encoding encoding) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); - ArgumentNullException.ThrowIfNull(encoding); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); @@ -221,7 +193,6 @@ public static class ListOfByteExtensions { throw new ArgumentNullException(nameof(encoding)); } -#endif return encoding.GetString(source.ToArray()); } @@ -248,14 +219,10 @@ public static class ListOfByteExtensions [CLSCompliant(false)] public static ushort ToUInt16(this IReadOnlyList source, int startIndex) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif return BitConverter.ToUInt16(source.ToArray(), startIndex); } @@ -282,14 +249,10 @@ public static class ListOfByteExtensions [CLSCompliant(false)] public static uint ToUInt32(this IReadOnlyList source, int startIndex) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif return BitConverter.ToUInt32(source.ToArray(), startIndex); } @@ -316,14 +279,10 @@ public static class ListOfByteExtensions [CLSCompliant(false)] public static ulong ToUInt64(this IReadOnlyList source, int startIndex) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif return BitConverter.ToUInt64(source.ToArray(), startIndex); } diff --git a/X10D/src/IO/StreamExtensions.cs b/X10D/src/IO/StreamExtensions.cs index c55b784..d1d44db 100644 --- a/X10D/src/IO/StreamExtensions.cs +++ b/X10D/src/IO/StreamExtensions.cs @@ -33,14 +33,10 @@ public static class StreamExtensions public static byte[] GetHash(this Stream stream) where T : HashAlgorithm { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(stream); -#else if (stream is null) { throw new ArgumentNullException(nameof(stream)); } -#endif if (!stream.CanRead) { @@ -87,14 +83,10 @@ public static class StreamExtensions /// A decimal value read from the stream. public static decimal ReadDecimal(this Stream stream, Endianness endianness) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(stream); -#else if (stream is null) { throw new ArgumentNullException(nameof(stream)); } -#endif #if NET5_0_OR_GREATER if (!Enum.IsDefined(endianness)) @@ -151,14 +143,10 @@ public static class StreamExtensions /// A double-precision floating point value read from the stream. public static double ReadDouble(this Stream stream, Endianness endianness) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(stream); -#else if (stream is null) { throw new ArgumentNullException(nameof(stream)); } -#endif #if NET5_0_OR_GREATER if (!Enum.IsDefined(endianness)) @@ -211,14 +199,10 @@ public static class StreamExtensions /// An two-byte unsigned integer read from the stream. public static short ReadInt16(this Stream stream, Endianness endianness) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(stream); -#else if (stream is null) { throw new ArgumentNullException(nameof(stream)); } -#endif #if NET5_0_OR_GREATER if (!Enum.IsDefined(endianness)) @@ -265,14 +249,10 @@ public static class StreamExtensions /// An four-byte unsigned integer read from the stream. public static int ReadInt32(this Stream stream, Endianness endianness) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(stream); -#else if (stream is null) { throw new ArgumentNullException(nameof(stream)); } -#endif #if NET5_0_OR_GREATER if (!Enum.IsDefined(endianness)) @@ -319,14 +299,10 @@ public static class StreamExtensions /// An eight-byte unsigned integer read from the stream. public static long ReadInt64(this Stream stream, Endianness endianness) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(stream); -#else if (stream is null) { throw new ArgumentNullException(nameof(stream)); } -#endif #if NET5_0_OR_GREATER if (!Enum.IsDefined(endianness)) @@ -373,14 +349,10 @@ public static class StreamExtensions /// A single-precision floating point value read from the stream. public static float ReadSingle(this Stream stream, Endianness endianness) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(stream); -#else if (stream is null) { throw new ArgumentNullException(nameof(stream)); } -#endif #if NET5_0_OR_GREATER if (!Enum.IsDefined(endianness)) @@ -435,14 +407,10 @@ public static class StreamExtensions [CLSCompliant(false)] public static ushort ReadUInt16(this Stream stream, Endianness endianness) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(stream); -#else if (stream is null) { throw new ArgumentNullException(nameof(stream)); } -#endif #if NET5_0_OR_GREATER if (!Enum.IsDefined(endianness)) @@ -491,14 +459,10 @@ public static class StreamExtensions [CLSCompliant(false)] public static uint ReadUInt32(this Stream stream, Endianness endianness) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(stream); -#else if (stream is null) { throw new ArgumentNullException(nameof(stream)); } -#endif #if NET5_0_OR_GREATER if (!Enum.IsDefined(endianness)) @@ -547,14 +511,10 @@ public static class StreamExtensions [CLSCompliant(false)] public static ulong ReadUInt64(this Stream stream, Endianness endianness) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(stream); -#else if (stream is null) { throw new ArgumentNullException(nameof(stream)); } -#endif #if NET5_0_OR_GREATER if (!Enum.IsDefined(endianness)) @@ -607,14 +567,10 @@ public static class StreamExtensions public static bool TryWriteHash(this Stream stream, Span destination, out int bytesWritten) where T : HashAlgorithm { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(stream); -#else if (stream is null) { throw new ArgumentNullException(nameof(stream)); } -#endif if (!stream.CanRead) { @@ -671,14 +627,10 @@ public static class StreamExtensions /// The number of bytes written to the stream. public static int Write(this Stream stream, short value, Endianness endianness) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(stream); -#else if (stream is null) { throw new ArgumentNullException(nameof(stream)); } -#endif #if NET5_0_OR_GREATER if (!Enum.IsDefined(endianness)) @@ -735,14 +687,10 @@ public static class StreamExtensions /// is . public static int Write(this Stream stream, int value, Endianness endianness) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(stream); -#else if (stream is null) { throw new ArgumentNullException(nameof(stream)); } -#endif #if NET5_0_OR_GREATER if (!Enum.IsDefined(endianness)) @@ -800,14 +748,10 @@ public static class StreamExtensions /// is . public static int Write(this Stream stream, long value, Endianness endianness) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(stream); -#else if (stream is null) { throw new ArgumentNullException(nameof(stream)); } -#endif #if NET5_0_OR_GREATER if (!Enum.IsDefined(endianness)) @@ -867,14 +811,10 @@ public static class StreamExtensions [CLSCompliant(false)] public static int Write(this Stream stream, ushort value, Endianness endianness) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(stream); -#else if (stream is null) { throw new ArgumentNullException(nameof(stream)); } -#endif #if NET5_0_OR_GREATER if (!Enum.IsDefined(endianness)) @@ -934,14 +874,10 @@ public static class StreamExtensions [CLSCompliant(false)] public static int Write(this Stream stream, uint value, Endianness endianness) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(stream); -#else if (stream is null) { throw new ArgumentNullException(nameof(stream)); } -#endif #if NET5_0_OR_GREATER if (!Enum.IsDefined(endianness)) @@ -1001,14 +937,10 @@ public static class StreamExtensions [CLSCompliant(false)] public static int Write(this Stream stream, ulong value, Endianness endianness) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(stream); -#else if (stream is null) { throw new ArgumentNullException(nameof(stream)); } -#endif #if NET5_0_OR_GREATER if (!Enum.IsDefined(endianness)) @@ -1052,14 +984,10 @@ public static class StreamExtensions /// is . public static int Write(this Stream stream, float value, Endianness endianness) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(stream); -#else if (stream is null) { throw new ArgumentNullException(nameof(stream)); } -#endif #if NET5_0_OR_GREATER if (!Enum.IsDefined(endianness)) @@ -1135,14 +1063,10 @@ public static class StreamExtensions /// is . public static int Write(this Stream stream, double value, Endianness endianness) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(stream); -#else if (stream is null) { throw new ArgumentNullException(nameof(stream)); } -#endif #if NET5_0_OR_GREATER if (!Enum.IsDefined(endianness)) @@ -1219,14 +1143,10 @@ public static class StreamExtensions [ExcludeFromCodeCoverage] public static int Write(this Stream stream, decimal value, Endianness endianness) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(stream); -#else if (stream is null) { throw new ArgumentNullException(nameof(stream)); } -#endif #if NET5_0_OR_GREATER if (!Enum.IsDefined(endianness)) diff --git a/X10D/src/IO/TextReaderExtensions.cs b/X10D/src/IO/TextReaderExtensions.cs index 4ecb213..b8bef35 100644 --- a/X10D/src/IO/TextReaderExtensions.cs +++ b/X10D/src/IO/TextReaderExtensions.cs @@ -13,14 +13,10 @@ public static class TextReaderExtensions /// is . public static IEnumerable EnumerateLines(this TextReader reader) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(reader); -#else if (reader is null) { throw new ArgumentNullException(nameof(reader)); } -#endif while (reader.ReadLine() is { } line) { @@ -36,14 +32,10 @@ public static class TextReaderExtensions /// is . public static async IAsyncEnumerable EnumerateLinesAsync(this TextReader reader) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(reader); -#else if (reader is null) { throw new ArgumentNullException(nameof(reader)); } -#endif while (await reader.ReadLineAsync().ConfigureAwait(false) is { } line) { diff --git a/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.Double.cs b/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.Double.cs index 1a63f42..1317846 100644 --- a/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.Double.cs +++ b/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.Double.cs @@ -16,14 +16,10 @@ public static partial class TextWriterExtensions /// An I/O error occurs. public static void WriteLineNoAlloc(this TextWriter writer, double value) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else if (writer is null) { throw new ArgumentNullException(nameof(writer)); } -#endif writer.WriteLineNoAlloc(value, "N0".AsSpan(), CultureInfo.CurrentCulture); } @@ -41,14 +37,10 @@ public static partial class TextWriterExtensions /// An I/O error occurs. public static void WriteLineNoAlloc(this TextWriter writer, double value, ReadOnlySpan format) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else if (writer is null) { throw new ArgumentNullException(nameof(writer)); } -#endif WriteLineNoAlloc(writer, value, format, CultureInfo.CurrentCulture); } @@ -68,14 +60,10 @@ public static partial class TextWriterExtensions public static void WriteLineNoAlloc(this TextWriter writer, double value, ReadOnlySpan format, IFormatProvider? formatProvider) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else if (writer is null) { throw new ArgumentNullException(nameof(writer)); } -#endif writer.WriteNoAlloc(value, format, formatProvider); writer.WriteLine(); diff --git a/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.Int32.cs b/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.Int32.cs index 8836d63..9640a6a 100644 --- a/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.Int32.cs +++ b/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.Int32.cs @@ -16,14 +16,10 @@ public static partial class TextWriterExtensions /// An I/O error occurs. public static void WriteLineNoAlloc(this TextWriter writer, int value) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else if (writer is null) { throw new ArgumentNullException(nameof(writer)); } -#endif writer.WriteLineNoAlloc(value, "N0".AsSpan(), CultureInfo.CurrentCulture); } @@ -41,14 +37,10 @@ public static partial class TextWriterExtensions /// An I/O error occurs. public static void WriteLineNoAlloc(this TextWriter writer, int value, ReadOnlySpan format) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else if (writer is null) { throw new ArgumentNullException(nameof(writer)); } -#endif WriteLineNoAlloc(writer, (long)value, format, CultureInfo.CurrentCulture); } @@ -68,14 +60,10 @@ public static partial class TextWriterExtensions public static void WriteLineNoAlloc(this TextWriter writer, int value, ReadOnlySpan format, IFormatProvider? formatProvider) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else if (writer is null) { throw new ArgumentNullException(nameof(writer)); } -#endif writer.WriteNoAlloc(value, format, formatProvider); writer.WriteLine(); diff --git a/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.Int64.cs b/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.Int64.cs index 83deadd..8ca5855 100644 --- a/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.Int64.cs +++ b/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.Int64.cs @@ -16,14 +16,10 @@ public static partial class TextWriterExtensions /// An I/O error occurs. public static void WriteLineNoAlloc(this TextWriter writer, long value) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else if (writer is null) { throw new ArgumentNullException(nameof(writer)); } -#endif writer.WriteLineNoAlloc(value, "N0".AsSpan(), CultureInfo.CurrentCulture); } @@ -41,14 +37,10 @@ public static partial class TextWriterExtensions /// An I/O error occurs. public static void WriteLineNoAlloc(this TextWriter writer, long value, ReadOnlySpan format) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else if (writer is null) { throw new ArgumentNullException(nameof(writer)); } -#endif writer.WriteLineNoAlloc(value, format, CultureInfo.CurrentCulture); } @@ -70,14 +62,10 @@ public static partial class TextWriterExtensions ReadOnlySpan format, IFormatProvider? formatProvider) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else if (writer is null) { throw new ArgumentNullException(nameof(writer)); } -#endif writer.WriteNoAlloc(value, format, formatProvider); writer.WriteLine(); diff --git a/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.Single.cs b/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.Single.cs index bb6d2e0..9194c62 100644 --- a/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.Single.cs +++ b/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.Single.cs @@ -16,14 +16,10 @@ public static partial class TextWriterExtensions /// An I/O error occurs. public static void WriteLineNoAlloc(this TextWriter writer, float value) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else if (writer is null) { throw new ArgumentNullException(nameof(writer)); } -#endif writer.WriteLineNoAlloc(value, "N0".AsSpan(), CultureInfo.CurrentCulture); } @@ -41,14 +37,10 @@ public static partial class TextWriterExtensions /// An I/O error occurs. public static void WriteLineNoAlloc(this TextWriter writer, float value, ReadOnlySpan format) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else if (writer is null) { throw new ArgumentNullException(nameof(writer)); } -#endif WriteLineNoAlloc(writer, value, format, CultureInfo.CurrentCulture); } @@ -68,14 +60,10 @@ public static partial class TextWriterExtensions public static void WriteLineNoAlloc(this TextWriter writer, float value, ReadOnlySpan format, IFormatProvider? formatProvider) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else if (writer is null) { throw new ArgumentNullException(nameof(writer)); } -#endif writer.WriteNoAlloc(value, format, formatProvider); writer.WriteLine(); diff --git a/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.UInt32.cs b/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.UInt32.cs index 98e9d42..b812afb 100644 --- a/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.UInt32.cs +++ b/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.UInt32.cs @@ -17,14 +17,10 @@ public static partial class TextWriterExtensions [CLSCompliant(false)] public static void WriteLineNoAlloc(this TextWriter writer, uint value) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else if (writer is null) { throw new ArgumentNullException(nameof(writer)); } -#endif writer.WriteLineNoAlloc(value, "N0".AsSpan(), CultureInfo.CurrentCulture); } @@ -43,14 +39,10 @@ public static partial class TextWriterExtensions [CLSCompliant(false)] public static void WriteLineNoAlloc(this TextWriter writer, uint value, ReadOnlySpan format) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else if (writer is null) { throw new ArgumentNullException(nameof(writer)); } -#endif WriteLineNoAlloc(writer, (long)value, format, CultureInfo.CurrentCulture); } @@ -73,14 +65,10 @@ public static partial class TextWriterExtensions ReadOnlySpan format, IFormatProvider? formatProvider) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else if (writer is null) { throw new ArgumentNullException(nameof(writer)); } -#endif writer.WriteNoAlloc(value, format, formatProvider); writer.WriteLine(); diff --git a/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.UInt64.cs b/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.UInt64.cs index 68f397f..7b55571 100644 --- a/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.UInt64.cs +++ b/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.UInt64.cs @@ -17,14 +17,10 @@ public static partial class TextWriterExtensions [CLSCompliant(false)] public static void WriteLineNoAlloc(this TextWriter writer, ulong value) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else if (writer is null) { throw new ArgumentNullException(nameof(writer)); } -#endif writer.WriteLineNoAlloc(value, "N0".AsSpan(), CultureInfo.CurrentCulture); } @@ -43,14 +39,10 @@ public static partial class TextWriterExtensions [CLSCompliant(false)] public static void WriteLineNoAlloc(this TextWriter writer, ulong value, ReadOnlySpan format) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else if (writer is null) { throw new ArgumentNullException(nameof(writer)); } -#endif writer.WriteLineNoAlloc(value, format, CultureInfo.CurrentCulture); } @@ -73,14 +65,10 @@ public static partial class TextWriterExtensions ReadOnlySpan format, IFormatProvider? formatProvider) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else if (writer is null) { throw new ArgumentNullException(nameof(writer)); } -#endif writer.WriteNoAlloc(value, format, formatProvider); writer.WriteLine(); diff --git a/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.Double.cs b/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.Double.cs index 6b6de18..a8d5bbb 100644 --- a/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.Double.cs +++ b/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.Double.cs @@ -15,14 +15,10 @@ public static partial class TextWriterExtensions /// An I/O error occurs. public static void WriteNoAlloc(this TextWriter writer, double value) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else if (writer is null) { throw new ArgumentNullException(nameof(writer)); } -#endif WriteNoAlloc(writer, value, "N0".AsSpan(), CultureInfo.CurrentCulture); } @@ -39,14 +35,10 @@ public static partial class TextWriterExtensions /// An I/O error occurs. public static void WriteNoAlloc(this TextWriter writer, double value, ReadOnlySpan format) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else if (writer is null) { throw new ArgumentNullException(nameof(writer)); } -#endif WriteNoAlloc(writer, value, format, CultureInfo.CurrentCulture); } @@ -65,14 +57,10 @@ public static partial class TextWriterExtensions public static void WriteNoAlloc(this TextWriter writer, double value, ReadOnlySpan format, IFormatProvider? formatProvider) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else if (writer is null) { throw new ArgumentNullException(nameof(writer)); } -#endif Span buffer = stackalloc char[100]; if (value.TryFormat(buffer, out int charsWritten, format, formatProvider)) diff --git a/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.Int32.cs b/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.Int32.cs index c2366bf..2018363 100644 --- a/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.Int32.cs +++ b/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.Int32.cs @@ -16,14 +16,10 @@ public static partial class TextWriterExtensions /// An I/O error occurs. public static void WriteNoAlloc(this TextWriter writer, int value) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else if (writer is null) { throw new ArgumentNullException(nameof(writer)); } -#endif WriteNoAlloc(writer, value, "N0".AsSpan(), CultureInfo.CurrentCulture); } @@ -40,14 +36,10 @@ public static partial class TextWriterExtensions /// An I/O error occurs. public static void WriteNoAlloc(this TextWriter writer, int value, ReadOnlySpan format) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else if (writer is null) { throw new ArgumentNullException(nameof(writer)); } -#endif WriteNoAlloc(writer, value, format, CultureInfo.CurrentCulture); } @@ -65,14 +57,10 @@ public static partial class TextWriterExtensions /// An I/O error occurs. public static void WriteNoAlloc(this TextWriter writer, int value, ReadOnlySpan format, IFormatProvider? formatProvider) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else if (writer is null) { throw new ArgumentNullException(nameof(writer)); } -#endif int digitCount = value.CountDigits(); Span buffer = stackalloc char[System.Math.Max(value < 0 ? digitCount + 1 : digitCount, 100)]; diff --git a/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.Int64.cs b/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.Int64.cs index 049d891..c0cb32f 100644 --- a/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.Int64.cs +++ b/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.Int64.cs @@ -16,14 +16,10 @@ public static partial class TextWriterExtensions /// An I/O error occurs. public static void WriteNoAlloc(this TextWriter writer, long value) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else if (writer is null) { throw new ArgumentNullException(nameof(writer)); } -#endif WriteNoAlloc(writer, value, "N0".AsSpan(), CultureInfo.CurrentCulture); } @@ -40,14 +36,10 @@ public static partial class TextWriterExtensions /// An I/O error occurs. public static void WriteNoAlloc(this TextWriter writer, long value, ReadOnlySpan format) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else if (writer is null) { throw new ArgumentNullException(nameof(writer)); } -#endif WriteNoAlloc(writer, value, format, CultureInfo.CurrentCulture); } @@ -68,14 +60,10 @@ public static partial class TextWriterExtensions ReadOnlySpan format, IFormatProvider? formatProvider) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else if (writer is null) { throw new ArgumentNullException(nameof(writer)); } -#endif int digitCount = value.CountDigits(); Span buffer = stackalloc char[System.Math.Max(value < 0 ? digitCount + 1 : digitCount, 100)]; diff --git a/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.Single.cs b/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.Single.cs index f595593..b48a415 100644 --- a/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.Single.cs +++ b/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.Single.cs @@ -15,14 +15,10 @@ public static partial class TextWriterExtensions /// An I/O error occurs. public static void WriteNoAlloc(this TextWriter writer, float value) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else if (writer is null) { throw new ArgumentNullException(nameof(writer)); } -#endif WriteNoAlloc(writer, value, "N0".AsSpan(), CultureInfo.CurrentCulture); } @@ -39,14 +35,10 @@ public static partial class TextWriterExtensions /// An I/O error occurs. public static void WriteNoAlloc(this TextWriter writer, float value, ReadOnlySpan format) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else if (writer is null) { throw new ArgumentNullException(nameof(writer)); } -#endif WriteNoAlloc(writer, value, format, CultureInfo.CurrentCulture); } @@ -65,14 +57,10 @@ public static partial class TextWriterExtensions public static void WriteNoAlloc(this TextWriter writer, float value, ReadOnlySpan format, IFormatProvider? formatProvider) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else if (writer is null) { throw new ArgumentNullException(nameof(writer)); } -#endif Span buffer = stackalloc char[100]; if (value.TryFormat(buffer, out int charsWritten, format, formatProvider)) diff --git a/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.UInt32.cs b/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.UInt32.cs index f8d32a2..b38fa0a 100644 --- a/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.UInt32.cs +++ b/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.UInt32.cs @@ -17,14 +17,10 @@ public static partial class TextWriterExtensions [CLSCompliant(false)] public static void WriteNoAlloc(this TextWriter writer, uint value) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else if (writer is null) { throw new ArgumentNullException(nameof(writer)); } -#endif WriteNoAlloc(writer, value, "N0".AsSpan(), CultureInfo.CurrentCulture); } @@ -42,14 +38,10 @@ public static partial class TextWriterExtensions [CLSCompliant(false)] public static void WriteNoAlloc(this TextWriter writer, uint value, ReadOnlySpan format) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else if (writer is null) { throw new ArgumentNullException(nameof(writer)); } -#endif WriteNoAlloc(writer, value, format, CultureInfo.CurrentCulture); } @@ -71,14 +63,10 @@ public static partial class TextWriterExtensions ReadOnlySpan format, IFormatProvider? formatProvider) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else if (writer is null) { throw new ArgumentNullException(nameof(writer)); } -#endif int digitCount = value.CountDigits(); Span buffer = stackalloc char[System.Math.Max(digitCount, 100)]; diff --git a/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.UInt64.cs b/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.UInt64.cs index 5e266e4..d9a48f4 100644 --- a/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.UInt64.cs +++ b/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.UInt64.cs @@ -17,14 +17,10 @@ public static partial class TextWriterExtensions [CLSCompliant(false)] public static void WriteNoAlloc(this TextWriter writer, ulong value) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else if (writer is null) { throw new ArgumentNullException(nameof(writer)); } -#endif WriteNoAlloc(writer, value, "N0".AsSpan(), CultureInfo.CurrentCulture); } @@ -42,14 +38,10 @@ public static partial class TextWriterExtensions [CLSCompliant(false)] public static void WriteNoAlloc(this TextWriter writer, ulong value, ReadOnlySpan format) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else if (writer is null) { throw new ArgumentNullException(nameof(writer)); } -#endif WriteNoAlloc(writer, value, format, CultureInfo.CurrentCulture); } @@ -71,14 +63,10 @@ public static partial class TextWriterExtensions ReadOnlySpan format, IFormatProvider? formatProvider) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(writer); -#else if (writer is null) { throw new ArgumentNullException(nameof(writer)); } -#endif int digitCount = value.CountDigits(); Span buffer = stackalloc char[System.Math.Max(digitCount, 100)]; diff --git a/X10D/src/Linq/ByteExtensions.cs b/X10D/src/Linq/ByteExtensions.cs index 3d7524d..64d1c01 100644 --- a/X10D/src/Linq/ByteExtensions.cs +++ b/X10D/src/Linq/ByteExtensions.cs @@ -15,14 +15,10 @@ public static class ByteExtensions /// is . public static byte Product(this IEnumerable source) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif return source.Aggregate((byte)1, (current, value) => (byte)(current * value)); } @@ -36,14 +32,10 @@ public static class ByteExtensions [CLSCompliant(false)] public static sbyte Product(this IEnumerable source) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif return source.Aggregate((sbyte)1, (current, value) => (sbyte)(current * value)); } @@ -59,14 +51,10 @@ public static class ByteExtensions /// is . public static byte Product(this IEnumerable source, Func selector) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif return source.Select(selector).Product(); } @@ -83,14 +71,10 @@ public static class ByteExtensions [CLSCompliant(false)] public static sbyte Product(this IEnumerable source, Func selector) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif return source.Select(selector).Product(); } diff --git a/X10D/src/Linq/DecimalExtensions.cs b/X10D/src/Linq/DecimalExtensions.cs index 01dde51..c5e1bc7 100644 --- a/X10D/src/Linq/DecimalExtensions.cs +++ b/X10D/src/Linq/DecimalExtensions.cs @@ -13,14 +13,10 @@ public static class DecimalExtensions /// is . public static decimal Product(this IEnumerable source) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif return source.Aggregate(1m, (current, value) => (current * value)); } @@ -36,14 +32,10 @@ public static class DecimalExtensions /// is . public static decimal Product(this IEnumerable source, Func selector) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif return source.Select(selector).Product(); } diff --git a/X10D/src/Linq/DoubleExtensions.cs b/X10D/src/Linq/DoubleExtensions.cs index afb38ae..23628af 100644 --- a/X10D/src/Linq/DoubleExtensions.cs +++ b/X10D/src/Linq/DoubleExtensions.cs @@ -13,14 +13,10 @@ public static class DoubleExtensions /// is . public static double Product(this IEnumerable source) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif return source.Aggregate(1.0, (current, value) => (current * value)); } @@ -36,14 +32,10 @@ public static class DoubleExtensions /// is . public static double Product(this IEnumerable source, Func selector) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif return source.Select(selector).Product(); } diff --git a/X10D/src/Linq/EnumerableExtensions.cs b/X10D/src/Linq/EnumerableExtensions.cs index 92592bf..05004c9 100644 --- a/X10D/src/Linq/EnumerableExtensions.cs +++ b/X10D/src/Linq/EnumerableExtensions.cs @@ -22,14 +22,10 @@ public static class EnumerableExtensions /// is . public static IEnumerable ConcatOne(this IEnumerable source, TSource value) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif foreach (TSource item in source) { @@ -52,14 +48,10 @@ public static class EnumerableExtensions /// is . public static IEnumerable Except(this IEnumerable source, TSource item) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif return source.Where(i => !Equals(i, item)); } @@ -74,14 +66,10 @@ public static class EnumerableExtensions /// contains no elements. public static (T? Minimum, T? Maximum) MinMax(this IEnumerable source) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif return MinMax(source, Comparer.Default); } @@ -97,14 +85,10 @@ public static class EnumerableExtensions /// contains no elements. public static (T? Minimum, T? Maximum) MinMax(this IEnumerable source, IComparer? comparer) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif comparer ??= Comparer.Default; @@ -160,10 +144,6 @@ public static class EnumerableExtensions public static (TResult? Minimum, TResult? Maximum) MinMax(this IEnumerable source, Func selector) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); - ArgumentNullException.ThrowIfNull(selector); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); @@ -173,7 +153,6 @@ public static class EnumerableExtensions { throw new ArgumentNullException(nameof(selector)); } -#endif return MinMax(source, selector, Comparer.Default); } @@ -194,10 +173,6 @@ public static class EnumerableExtensions Func selector, IComparer? comparer) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); - ArgumentNullException.ThrowIfNull(selector); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); @@ -207,7 +182,6 @@ public static class EnumerableExtensions { throw new ArgumentNullException(nameof(selector)); } -#endif comparer ??= Comparer.Default; @@ -263,10 +237,6 @@ public static class EnumerableExtensions public static (TSource? Minimum, TSource? Maximum) MinMaxBy(this IEnumerable source, Func keySelector) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); - ArgumentNullException.ThrowIfNull(keySelector); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); @@ -276,7 +246,6 @@ public static class EnumerableExtensions { throw new ArgumentNullException(nameof(keySelector)); } -#endif return MinMaxBy(source, keySelector, Comparer.Default); } @@ -296,10 +265,6 @@ public static class EnumerableExtensions Func keySelector, IComparer? comparer) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); - ArgumentNullException.ThrowIfNull(keySelector); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); @@ -309,7 +274,6 @@ public static class EnumerableExtensions { throw new ArgumentNullException(nameof(keySelector)); } -#endif comparer ??= Comparer.Default; TSource? minValue; diff --git a/X10D/src/Linq/Int32Extensions.cs b/X10D/src/Linq/Int32Extensions.cs index 871e422..876f373 100644 --- a/X10D/src/Linq/Int32Extensions.cs +++ b/X10D/src/Linq/Int32Extensions.cs @@ -15,14 +15,10 @@ public static class Int32Extensions /// is . public static int Product(this IEnumerable source) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif return source.Aggregate(1, (current, value) => current * value); } @@ -36,14 +32,10 @@ public static class Int32Extensions [CLSCompliant(false)] public static uint Product(this IEnumerable source) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif return source.Aggregate(1u, (current, value) => current * value); } @@ -59,14 +51,10 @@ public static class Int32Extensions /// is . public static int Product(this IEnumerable source, Func selector) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif return source.Select(selector).Product(); } @@ -83,14 +71,10 @@ public static class Int32Extensions [CLSCompliant(false)] public static uint Product(this IEnumerable source, Func selector) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif return source.Select(selector).Product(); } diff --git a/X10D/src/Linq/Int64Extensions.cs b/X10D/src/Linq/Int64Extensions.cs index 07b9802..00061d4 100644 --- a/X10D/src/Linq/Int64Extensions.cs +++ b/X10D/src/Linq/Int64Extensions.cs @@ -15,14 +15,10 @@ public static class Int64Extensions /// is . public static long Product(this IEnumerable source) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif return source.Aggregate(1L, (current, value) => current * value); } @@ -36,14 +32,10 @@ public static class Int64Extensions [CLSCompliant(false)] public static ulong Product(this IEnumerable source) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif return source.Aggregate(1UL, (current, value) => current * value); } @@ -59,14 +51,10 @@ public static class Int64Extensions /// is . public static long Product(this IEnumerable source, Func selector) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif return source.Select(selector).Product(); } @@ -83,14 +71,10 @@ public static class Int64Extensions [CLSCompliant(false)] public static ulong Product(this IEnumerable source, Func selector) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif return source.Select(selector).Product(); } diff --git a/X10D/src/Linq/ReadOnlySpanExtensions.cs b/X10D/src/Linq/ReadOnlySpanExtensions.cs index bf0d1d3..9d20ff8 100644 --- a/X10D/src/Linq/ReadOnlySpanExtensions.cs +++ b/X10D/src/Linq/ReadOnlySpanExtensions.cs @@ -21,14 +21,10 @@ public static class ReadOnlySpanExtensions [Pure] public static bool All(this ReadOnlySpan source, Predicate predicate) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(predicate); -#else if (predicate is null) { throw new ArgumentNullException(nameof(predicate)); } -#endif if (source.IsEmpty) { @@ -60,14 +56,10 @@ public static class ReadOnlySpanExtensions [Pure] public static bool Any(this ReadOnlySpan source, Predicate predicate) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(predicate); -#else if (predicate is null) { throw new ArgumentNullException(nameof(predicate)); } -#endif if (source.IsEmpty) { @@ -97,14 +89,10 @@ public static class ReadOnlySpanExtensions /// is . public static int Count(this ReadOnlySpan source, Predicate predicate) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(predicate); -#else if (predicate is null) { throw new ArgumentNullException(nameof(predicate)); } -#endif if (source.IsEmpty) { diff --git a/X10D/src/Linq/SingleExtensions.cs b/X10D/src/Linq/SingleExtensions.cs index 9d48203..e80ed9b 100644 --- a/X10D/src/Linq/SingleExtensions.cs +++ b/X10D/src/Linq/SingleExtensions.cs @@ -13,14 +13,10 @@ public static class SingleExtensions /// is . public static float Product(this IEnumerable source) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif return source.Aggregate(1f, (current, value) => (current * value)); } @@ -36,14 +32,10 @@ public static class SingleExtensions /// is . public static float Product(this IEnumerable source, Func selector) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif return source.Select(selector).Product(); } diff --git a/X10D/src/Linq/SpanExtensions.cs b/X10D/src/Linq/SpanExtensions.cs index ce2e3f3..9b84308 100644 --- a/X10D/src/Linq/SpanExtensions.cs +++ b/X10D/src/Linq/SpanExtensions.cs @@ -21,14 +21,10 @@ public static class SpanExtensions [Pure] public static bool All(this Span source, Predicate predicate) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(predicate); -#else if (predicate is null) { throw new ArgumentNullException(nameof(predicate)); } -#endif if (source.IsEmpty) { @@ -60,14 +56,10 @@ public static class SpanExtensions [Pure] public static bool Any(this Span source, Predicate predicate) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(predicate); -#else if (predicate is null) { throw new ArgumentNullException(nameof(predicate)); } -#endif if (source.IsEmpty) { @@ -97,14 +89,10 @@ public static class SpanExtensions /// is . public static int Count(this Span source, Predicate predicate) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(predicate); -#else if (predicate is null) { throw new ArgumentNullException(nameof(predicate)); } -#endif if (source.IsEmpty) { diff --git a/X10D/src/Math/ComparableExtensions.cs b/X10D/src/Math/ComparableExtensions.cs index e1af91f..9aea7fc 100644 --- a/X10D/src/Math/ComparableExtensions.cs +++ b/X10D/src/Math/ComparableExtensions.cs @@ -56,14 +56,10 @@ public static class ComparableExtensions where T2 : IComparable where T3 : IComparable { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(value); -#else if (value is null) { throw new ArgumentNullException(nameof(value)); } -#endif if (lower.GreaterThan(upper)) { @@ -114,14 +110,10 @@ public static class ComparableExtensions public static T Clamp(this T value, T lower, T upper) where T : IComparable { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(value); -#else if (value is null) { throw new ArgumentNullException(nameof(value)); } -#endif if (lower.GreaterThan(upper)) { @@ -160,14 +152,10 @@ public static class ComparableExtensions public static bool GreaterThan(this T1 value, T2 other) where T1 : IComparable { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(value); -#else if (value is null) { throw new ArgumentNullException(nameof(value)); } -#endif return value.CompareTo(other) > 0; } @@ -199,14 +187,10 @@ public static class ComparableExtensions public static bool GreaterThanOrEqualTo(this T1 value, T2 other) where T1 : IComparable { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(value); -#else if (value is null) { throw new ArgumentNullException(nameof(value)); } -#endif return value.CompareTo(other) >= 0; } @@ -238,14 +222,10 @@ public static class ComparableExtensions public static bool LessThan(this T1 value, T2 other) where T1 : IComparable { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(value); -#else if (value is null) { throw new ArgumentNullException(nameof(value)); } -#endif return value.CompareTo(other) < 0; } @@ -277,14 +257,10 @@ public static class ComparableExtensions public static bool LessThanOrEqualTo(this T1 value, T2 other) where T1 : IComparable { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(value); -#else if (value is null) { throw new ArgumentNullException(nameof(value)); } -#endif return value.CompareTo(other) <= 0; } @@ -315,14 +291,10 @@ public static class ComparableExtensions public static T Max(this T value, T other) where T : IComparable { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(value); -#else if (value is null) { throw new ArgumentNullException(nameof(value)); } -#endif return value.GreaterThan(other) ? value : other; } @@ -353,14 +325,10 @@ public static class ComparableExtensions public static T Min(this T value, T other) where T : IComparable { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(value); -#else if (value is null) { throw new ArgumentNullException(nameof(value)); } -#endif return value.LessThan(other) ? value : other; } diff --git a/X10D/src/Net/EndPointExtensions.cs b/X10D/src/Net/EndPointExtensions.cs index 4bbfacd..da4147f 100644 --- a/X10D/src/Net/EndPointExtensions.cs +++ b/X10D/src/Net/EndPointExtensions.cs @@ -26,14 +26,10 @@ public static class EndPointExtensions [MethodImpl(CompilerResources.MethodImplOptions)] public static string GetHost(this EndPoint endPoint) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(endPoint); -#else if (endPoint is null) { throw new ArgumentNullException(nameof(endPoint)); } -#endif return endPoint switch { @@ -59,14 +55,10 @@ public static class EndPointExtensions [MethodImpl(CompilerResources.MethodImplOptions)] public static int GetPort(this EndPoint endPoint) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(endPoint); -#else if (endPoint is null) { throw new ArgumentNullException(nameof(endPoint)); } -#endif return endPoint switch { diff --git a/X10D/src/Net/IPAddressExtensions.cs b/X10D/src/Net/IPAddressExtensions.cs index bd79612..6c6dc43 100644 --- a/X10D/src/Net/IPAddressExtensions.cs +++ b/X10D/src/Net/IPAddressExtensions.cs @@ -23,14 +23,10 @@ public static class IPAddressExtensions [MethodImpl(CompilerResources.MethodImplOptions)] public static bool IsIPv4(this IPAddress address) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(address); -#else if (address is null) { throw new ArgumentNullException(nameof(address)); } -#endif return address.AddressFamily == AddressFamily.InterNetwork; } @@ -47,14 +43,10 @@ public static class IPAddressExtensions [MethodImpl(CompilerResources.MethodImplOptions)] public static bool IsIPv6(this IPAddress address) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(address); -#else if (address is null) { throw new ArgumentNullException(nameof(address)); } -#endif return address.AddressFamily == AddressFamily.InterNetworkV6; } diff --git a/X10D/src/Numerics/RandomExtensions.cs b/X10D/src/Numerics/RandomExtensions.cs index 5a89e94..ea2a19c 100644 --- a/X10D/src/Numerics/RandomExtensions.cs +++ b/X10D/src/Numerics/RandomExtensions.cs @@ -21,14 +21,10 @@ public static class RandomExtensions /// is . public static Quaternion NextRotation(this Random random) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(random); -#else if (random is null) { throw new ArgumentNullException(nameof(random)); } -#endif int seed = random.Next(); var seededRandom = new Random(seed); @@ -48,14 +44,10 @@ public static class RandomExtensions /// is . public static Quaternion NextRotationUniform(this Random random) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(random); -#else if (random is null) { throw new ArgumentNullException(nameof(random)); } -#endif int seed = random.Next(); var seededRandom = new Random(seed); @@ -84,14 +76,10 @@ public static class RandomExtensions /// public static Vector2 NextUnitVector2(this Random random) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(random); -#else if (random is null) { throw new ArgumentNullException(nameof(random)); } -#endif // no need to construct a seeded random here, since we only call Next once @@ -112,14 +100,10 @@ public static class RandomExtensions /// public static Vector3 NextUnitVector3(this Random random) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(random); -#else if (random is null) { throw new ArgumentNullException(nameof(random)); } -#endif int seed = random.Next(); var seededRandom = new Random(seed); diff --git a/X10D/src/Reactive/ObservableDisposer.cs b/X10D/src/Reactive/ObservableDisposer.cs index 9073ff9..b935112 100644 --- a/X10D/src/Reactive/ObservableDisposer.cs +++ b/X10D/src/Reactive/ObservableDisposer.cs @@ -17,23 +17,8 @@ internal readonly struct ObservableDisposer : IDisposable /// The additional action to run on dispose. public ObservableDisposer(HashSet> observers, IObserver observer, Action? additionalAction) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(observers); - ArgumentNullException.ThrowIfNull(observer); -#else - if (observers is null) - { - throw new ArgumentNullException(nameof(observers)); - } - - if (observer is null) - { - throw new ArgumentNullException(nameof(observer)); - } -#endif - - _observers = observers; - _observer = observer; + _observers = observers ?? throw new ArgumentNullException(nameof(observers)); + _observer = observer ?? throw new ArgumentNullException(nameof(observer)); _additionalAction = additionalAction; } diff --git a/X10D/src/Reactive/ProgressExtensions.cs b/X10D/src/Reactive/ProgressExtensions.cs index 6128a72..2eecdd8 100644 --- a/X10D/src/Reactive/ProgressExtensions.cs +++ b/X10D/src/Reactive/ProgressExtensions.cs @@ -18,14 +18,10 @@ public static class ProgressExtensions /// is . public static IObservable OnProgressChanged(this Progress progress) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(progress); -#else if (progress is null) { throw new ArgumentNullException(nameof(progress)); } -#endif var progressObservable = new ProgressObservable(); @@ -59,14 +55,10 @@ public static class ProgressExtensions /// is . public static IObservable OnProgressChanged(this Progress progress, T completeValue) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(progress); -#else if (progress is null) { throw new ArgumentNullException(nameof(progress)); } -#endif var progressObservable = new ProgressObservable(); var comparer = EqualityComparer.Default; diff --git a/X10D/src/Reactive/ProgressObservable.cs b/X10D/src/Reactive/ProgressObservable.cs index 29a8243..32a0870 100644 --- a/X10D/src/Reactive/ProgressObservable.cs +++ b/X10D/src/Reactive/ProgressObservable.cs @@ -25,14 +25,10 @@ internal sealed class ProgressObservable : IObservable /// An object which can be disposed to unsubscribe from progress tracking. public IDisposable Subscribe(IObserver observer) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(observer); -#else if (observer is null) { throw new ArgumentNullException(nameof(observer)); } -#endif _observers.Add(observer); return new ObservableDisposer(_observers, observer, OnDispose); diff --git a/X10D/src/Reflection/MemberInfoExtensions.cs b/X10D/src/Reflection/MemberInfoExtensions.cs index afe4722..362fdd9 100644 --- a/X10D/src/Reflection/MemberInfoExtensions.cs +++ b/X10D/src/Reflection/MemberInfoExtensions.cs @@ -26,14 +26,11 @@ public static class MemberInfoExtensions public static bool HasCustomAttribute(this MemberInfo member) where T : Attribute { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(member); -#else if (member is null) { throw new ArgumentNullException(nameof(member)); } -#endif + return Attribute.IsDefined(member, typeof(T)); } @@ -51,10 +48,6 @@ public static class MemberInfoExtensions [MethodImpl(CompilerResources.MethodImplOptions)] public static bool HasCustomAttribute(this MemberInfo member, Type attribute) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(member); - ArgumentNullException.ThrowIfNull(attribute); -#else if (member is null) { throw new ArgumentNullException(nameof(member)); @@ -64,7 +57,6 @@ public static class MemberInfoExtensions { throw new ArgumentNullException(nameof(attribute)); } -#endif if (!attribute.Inherits()) { @@ -94,10 +86,6 @@ public static class MemberInfoExtensions Func selector) where TAttribute : Attribute { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(member); - ArgumentNullException.ThrowIfNull(selector); -#else if (member is null) { throw new ArgumentNullException(nameof(member)); @@ -107,7 +95,6 @@ public static class MemberInfoExtensions { throw new ArgumentNullException(nameof(selector)); } -#endif return member.SelectFromCustomAttribute(selector, default); } @@ -132,10 +119,6 @@ public static class MemberInfoExtensions Func selector, TReturn? defaultValue) where TAttribute : Attribute { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(member); - ArgumentNullException.ThrowIfNull(selector); -#else if (member is null) { throw new ArgumentNullException(nameof(member)); @@ -145,7 +128,6 @@ public static class MemberInfoExtensions { throw new ArgumentNullException(nameof(selector)); } -#endif return member.GetCustomAttribute() is { } attribute ? selector(attribute) diff --git a/X10D/src/Reflection/TypeExtensions.cs b/X10D/src/Reflection/TypeExtensions.cs index b336b06..32b4d75 100644 --- a/X10D/src/Reflection/TypeExtensions.cs +++ b/X10D/src/Reflection/TypeExtensions.cs @@ -21,14 +21,10 @@ public static class TypeExtensions [MethodImpl(CompilerResources.MethodImplOptions)] public static bool Implements(this Type value) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(value); -#else if (value is null) { throw new ArgumentNullException(nameof(value)); } -#endif return value.Implements(typeof(T)); } @@ -48,10 +44,6 @@ public static class TypeExtensions [MethodImpl(CompilerResources.MethodImplOptions)] public static bool Implements(this Type value, Type interfaceType) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(value); - ArgumentNullException.ThrowIfNull(interfaceType); -#else if (value is null) { throw new ArgumentNullException(nameof(value)); @@ -61,7 +53,6 @@ public static class TypeExtensions { throw new ArgumentNullException(nameof(interfaceType)); } -#endif if (!interfaceType.IsInterface) { @@ -90,14 +81,10 @@ public static class TypeExtensions public static bool Inherits(this Type value) where T : class { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(value); -#else if (value is null) { throw new ArgumentNullException(nameof(value)); } -#endif return value.Inherits(typeof(T)); } @@ -125,10 +112,6 @@ public static class TypeExtensions [MethodImpl(CompilerResources.MethodImplOptions)] public static bool Inherits(this Type value, Type type) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(value); - ArgumentNullException.ThrowIfNull(type); -#else if (value is null) { throw new ArgumentNullException(nameof(value)); @@ -138,7 +121,6 @@ public static class TypeExtensions { throw new ArgumentNullException(nameof(type)); } -#endif if (!value.IsClass) { diff --git a/X10D/src/Text/EnumerableExtensions.cs b/X10D/src/Text/EnumerableExtensions.cs index c5552b3..e243ef0 100644 --- a/X10D/src/Text/EnumerableExtensions.cs +++ b/X10D/src/Text/EnumerableExtensions.cs @@ -18,10 +18,6 @@ public static class EnumerableExtensions /// public static IEnumerable Grep(this IEnumerable source, string pattern) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); - ArgumentNullException.ThrowIfNull(pattern); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); @@ -31,7 +27,6 @@ public static class EnumerableExtensions { throw new ArgumentNullException(nameof(pattern)); } -#endif return Grep(source, pattern, false); } @@ -50,10 +45,6 @@ public static class EnumerableExtensions /// public static IEnumerable Grep(this IEnumerable source, string pattern, bool ignoreCase) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); - ArgumentNullException.ThrowIfNull(pattern); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); @@ -63,7 +54,6 @@ public static class EnumerableExtensions { throw new ArgumentNullException(nameof(pattern)); } -#endif #if NET6_0_OR_GREATER if (source.TryGetNonEnumeratedCount(out int count) && count == 0) diff --git a/X10D/src/Text/StringBuilderReader.cs b/X10D/src/Text/StringBuilderReader.cs index 337a22c..fe6e969 100644 --- a/X10D/src/Text/StringBuilderReader.cs +++ b/X10D/src/Text/StringBuilderReader.cs @@ -55,14 +55,10 @@ public class StringBuilderReader : TextReader /// public override int Read(char[] buffer, int index, int count) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(buffer); -#else if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } -#endif if (index < 0) { diff --git a/X10D/src/Text/StringExtensions.cs b/X10D/src/Text/StringExtensions.cs index 052b4c5..44db6bd 100644 --- a/X10D/src/Text/StringExtensions.cs +++ b/X10D/src/Text/StringExtensions.cs @@ -60,14 +60,10 @@ public static class StringExtensions [MethodImpl(CompilerResources.MethodImplOptions)] public static string Base64Decode(this string value) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(value); -#else if (value is null) { throw new ArgumentNullException(nameof(value)); } -#endif return Convert.FromBase64String(value).ToString(Encoding.ASCII); } @@ -82,14 +78,10 @@ public static class StringExtensions [MethodImpl(CompilerResources.MethodImplOptions)] public static string Base64Encode(this string value) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(value); -#else if (value is null) { throw new ArgumentNullException(nameof(value)); } -#endif return Convert.ToBase64String(value.GetBytes(Encoding.ASCII)); } @@ -115,11 +107,6 @@ public static class StringExtensions [MethodImpl(CompilerResources.MethodImplOptions)] public static string ChangeEncoding(this string value, Encoding sourceEncoding, Encoding destinationEncoding) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(value); - ArgumentNullException.ThrowIfNull(sourceEncoding); - ArgumentNullException.ThrowIfNull(destinationEncoding); -#else if (value is null) { throw new ArgumentNullException(nameof(value)); @@ -134,7 +121,6 @@ public static class StringExtensions { throw new ArgumentNullException(nameof(destinationEncoding)); } -#endif return value.GetBytes(sourceEncoding).ToString(destinationEncoding); } @@ -179,14 +165,10 @@ public static class StringExtensions /// An integer representing the count of inside . public static int CountSubstring(this string haystack, char needle) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(haystack); -#else if (haystack is null) { throw new ArgumentNullException(nameof(haystack)); } -#endif return haystack.AsSpan().CountSubstring(needle); } @@ -211,14 +193,10 @@ public static class StringExtensions /// An integer representing the count of inside . public static int CountSubstring(this string haystack, string? needle, StringComparison comparison) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(haystack); -#else if (haystack is null) { throw new ArgumentNullException(nameof(haystack)); } -#endif if (string.IsNullOrWhiteSpace(needle)) { @@ -374,14 +352,10 @@ public static class StringExtensions public static T EnumParse(this string value, bool ignoreCase) where T : struct, Enum { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(value); -#else if (value is null) { throw new ArgumentNullException(nameof(value)); } -#endif value = value.Trim(); @@ -437,10 +411,6 @@ public static class StringExtensions [MethodImpl(CompilerResources.MethodImplOptions)] public static byte[] GetBytes(this string value, Encoding encoding) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(value); - ArgumentNullException.ThrowIfNull(encoding); -#else if (value is null) { throw new ArgumentNullException(nameof(value)); @@ -450,7 +420,6 @@ public static class StringExtensions { throw new ArgumentNullException(nameof(encoding)); } -#endif return encoding.GetBytes(value); } @@ -464,14 +433,10 @@ public static class StringExtensions [MethodImpl(CompilerResources.MethodImplOptions)] public static bool IsEmoji(this string value) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(value); -#else if (value is null) { throw new ArgumentNullException(nameof(value)); } -#endif return EmojiRegex.Value.IsMatch(value); } @@ -488,14 +453,10 @@ public static class StringExtensions [MethodImpl(CompilerResources.MethodImplOptions)] public static bool IsEmpty(this string value) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(value); -#else if (value is null) { throw new ArgumentNullException(nameof(value)); } -#endif return value.Length == 0; } @@ -512,14 +473,10 @@ public static class StringExtensions [MethodImpl(CompilerResources.MethodImplOptions)] public static bool IsLower(this string value) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(value); -#else if (value is null) { throw new ArgumentNullException(nameof(value)); } -#endif for (var index = 0; index < value.Length; index++) { @@ -599,14 +556,10 @@ public static class StringExtensions [MethodImpl(CompilerResources.MethodImplOptions)] public static bool IsPalindrome(this string value) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(value); -#else if (value is null) { throw new ArgumentNullException(nameof(value)); } -#endif if (string.IsNullOrWhiteSpace(value)) { @@ -673,14 +626,10 @@ public static class StringExtensions [MethodImpl(CompilerResources.MethodImplOptions)] public static bool IsUpper(this string value) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(value); -#else if (value is null) { throw new ArgumentNullException(nameof(value)); } -#endif for (var index = 0; index < value.Length; index++) { @@ -728,14 +677,10 @@ public static class StringExtensions [MethodImpl(CompilerResources.MethodImplOptions)] public static bool IsWhiteSpace(this string value) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(value); -#else if (value is null) { throw new ArgumentNullException(nameof(value)); } -#endif if (value.Length == 0) { @@ -765,14 +710,10 @@ public static class StringExtensions [MethodImpl(CompilerResources.MethodImplOptions)] public static string Repeat(this string value, int count) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(value); -#else if (value is null) { throw new ArgumentNullException(nameof(value)); } -#endif switch (count) { @@ -810,14 +751,10 @@ public static class StringExtensions [MethodImpl(CompilerResources.MethodImplOptions)] public static string Randomize(this string source, int length, Random? random = null) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); } -#endif if (length < 0) { @@ -852,14 +789,10 @@ public static class StringExtensions [MethodImpl(CompilerResources.MethodImplOptions)] public static string Reverse(this string value) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(value); -#else if (value is null) { throw new ArgumentNullException(nameof(value)); } -#endif if (value.Length < 2) { @@ -890,14 +823,10 @@ public static class StringExtensions [MethodImpl(CompilerResources.MethodImplOptions)] public static string Shuffled(this string value, Random? random = null) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(value); -#else if (value is null) { throw new ArgumentNullException(nameof(value)); } -#endif random ??= RandomExtensions.GetShared(); @@ -920,14 +849,10 @@ public static class StringExtensions [MethodImpl(CompilerResources.MethodImplOptions)] public static IEnumerable Split(this string value, int chunkSize) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(value); -#else if (value is null) { throw new ArgumentNullException(nameof(value)); } -#endif if (chunkSize == 0) { @@ -956,14 +881,10 @@ public static class StringExtensions /// public static bool StartsWithAny(this string? value, params string[] startValues) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(startValues); -#else if (startValues is null) { throw new ArgumentNullException(nameof(startValues)); } -#endif if (startValues.Length == 0 || string.IsNullOrWhiteSpace(value)) { @@ -989,14 +910,10 @@ public static class StringExtensions /// public static bool StartsWithAny(this string? value, StringComparison comparison, params string[] startValues) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(startValues); -#else if (startValues is null) { throw new ArgumentNullException(nameof(startValues)); } -#endif if (startValues.Length == 0 || string.IsNullOrWhiteSpace(value)) { diff --git a/X10D/src/Time/StringExtensions.cs b/X10D/src/Time/StringExtensions.cs index 4ebc4b0..668f26d 100644 --- a/X10D/src/Time/StringExtensions.cs +++ b/X10D/src/Time/StringExtensions.cs @@ -61,14 +61,10 @@ public static class StringExtensions [MethodImpl(CompilerResources.MethodImplOptions)] public static TimeSpan ToTimeSpan(this string input) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(input); -#else if (input is null) { throw new ArgumentNullException(nameof(input)); } -#endif return TimeSpanParser.TryParse(input, out TimeSpan result) ? result From dbc63b9b2663afd3b515ff0bebac0d86135a4147 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Thu, 13 Apr 2023 23:14:32 +0100 Subject: [PATCH 055/102] [ci skip] docs: bump version in README --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 85d2dbb..2f38a60 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ X10D (pronounced *extend*), is a .NET package that provides extension methods fo ## Installation ### NuGet installation ```ps -Install-Package X10D -Version 3.2.0 +Install-Package X10D -Version 4.0.0 ``` ### Manual installation From 545994389d8cd488331a78a45c1a5834b4f8d388 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Thu, 13 Apr 2023 23:26:54 +0100 Subject: [PATCH 056/102] [ci skip] ci: run dotnet and unity workflows from all branches --- .github/workflows/dotnet.yml | 3 +-- .github/workflows/unity.yml | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml index b5c7648..28a3441 100644 --- a/.github/workflows/dotnet.yml +++ b/.github/workflows/dotnet.yml @@ -6,8 +6,7 @@ on: - '*' pull_request: branches: - - main - - develop + - '*' jobs: build: diff --git a/.github/workflows/unity.yml b/.github/workflows/unity.yml index e6b8c7a..61d7c51 100644 --- a/.github/workflows/unity.yml +++ b/.github/workflows/unity.yml @@ -6,8 +6,7 @@ on: - '*' pull_request: branches: - - main - - develop + - '*' jobs: build: From 334c64e9955b34117c50fab4192ab046db7e1594 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Thu, 13 Apr 2023 23:27:08 +0100 Subject: [PATCH 057/102] [ci skip] ci: add workflow_dispatch trigger to nightly workflow --- .github/workflows/nightly.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 22d4a81..ca14ed1 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -4,6 +4,7 @@ on: push: branches: - main + workflow_dispatch: jobs: nightly: From 6f3a667e378eb77b87abffb820e51a55f66d603f Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Fri, 14 Apr 2023 13:55:52 +0100 Subject: [PATCH 058/102] feat: add string.ConcatIf --- CHANGELOG.md | 1 + X10D.Tests/src/Text/StringTests.cs | 38 +++++++++++++++ X10D/src/Text/StringExtensions.cs | 74 ++++++++++++++++++++++++++++++ 3 files changed, 113 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9482e2e..61bb729 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - X10D: Added `TextWriter.WriteLineNoAlloc(uint[, ReadOnlySpan[, IFormatProvider]])`. - X10D: Added `TextWriter.WriteLineNoAlloc(long[, ReadOnlySpan[, IFormatProvider]])`. - X10D: Added `TextWriter.WriteLineNoAlloc(ulong[, ReadOnlySpan[, IFormatProvider]])`. +- X10D: Added `string.ConcatIf`. - X10D.Unity: Added `RaycastHit.GetComponent` and `RaycastHit.TryGetComponent`. - X10D.Unity: Added `DebugUtility.DrawFunction`, and `DebugUtility.DrawUnjoinedPolyhedron` on which it relies. diff --git a/X10D.Tests/src/Text/StringTests.cs b/X10D.Tests/src/Text/StringTests.cs index 99fca98..d462186 100644 --- a/X10D.Tests/src/Text/StringTests.cs +++ b/X10D.Tests/src/Text/StringTests.cs @@ -105,6 +105,44 @@ public class StringTests Assert.Throws(() => _ = "Hello World".ChangeEncoding(Encoding.UTF8, null!)); } + [Test] + public void ConcatIf_ShouldConcatenateString_GivenTrueCondition() + { + Assert.Multiple(() => + { + Assert.That("Hello".ConcatIf(true, " World"), Is.EqualTo("Hello World")); + Assert.That("Hello".ConcatIf(true, () => " World"), Is.EqualTo("Hello World")); + Assert.That("Hello".ConcatIf(() => true, " World"), Is.EqualTo("Hello World")); + Assert.That("Hello".ConcatIf(() => true, () => " World"), Is.EqualTo("Hello World")); + }); + } + + [Test] + public void ConcatIf_ShouldNotConcatenateString_GivenFalseCondition() + { + Assert.Multiple(() => + { + Assert.That("Hello".ConcatIf(false, " World"), Is.EqualTo("Hello")); + Assert.That("Hello".ConcatIf(false, () => " World"), Is.EqualTo("Hello")); + Assert.That("Hello".ConcatIf(() => false, " World"), Is.EqualTo("Hello")); + Assert.That("Hello".ConcatIf(() => false, () => " World"), Is.EqualTo("Hello")); + }); + } + + [Test] + public void ConcatIf_ShouldThrowArgumentNullException_GivenNullConditionFactory() + { + Assert.Throws(() => _ = "".ConcatIf(null!, "Hello World")); + Assert.Throws(() => _ = "".ConcatIf(null!, () => "Hello World")); + } + + [Test] + public void ConcatIf_ShouldThrowArgumentNullException_GivenNullValueFactory() + { + Assert.Throws(() => _ = "".ConcatIf(true, (Func?)null!)); + Assert.Throws(() => _ = "".ConcatIf(() => true, (Func?)null!)); + } + [Test] public void CountSubstring_ShouldHonor_StringComparison() { diff --git a/X10D/src/Text/StringExtensions.cs b/X10D/src/Text/StringExtensions.cs index 44db6bd..4600931 100644 --- a/X10D/src/Text/StringExtensions.cs +++ b/X10D/src/Text/StringExtensions.cs @@ -125,6 +125,80 @@ public static class StringExtensions return value.GetBytes(sourceEncoding).ToString(destinationEncoding); } + /// + /// Appends a string to the current string if the specified condition evaluates to . + /// + /// The current string. + /// The condition to evaluate. + /// The string to append if the condition is true. + /// The concatenated string. + [Pure] + public static string? ConcatIf(this string? value, bool condition, string? appendValue) + { + return condition ? value + appendValue : value; + } + + /// + /// Appends a string to the current string if the specified condition evaluates to . + /// + /// The current string. + /// The function that returns the condition to evaluate. + /// The string to append if the condition is true. + /// The concatenated string. + /// is . + [Pure] + public static string? ConcatIf(this string? value, Func conditionFactory, string? appendValue) + { + if (conditionFactory is null) + { + throw new ArgumentNullException(nameof(conditionFactory)); + } + + return conditionFactory() ? value + appendValue : value; + } + + /// + /// Appends a string to the current string if the specified condition evaluates to . + /// + /// The current string. + /// The condition to evaluate. + /// The function that returns the string to append if the condition is true. + /// The concatenated string. + [Pure] + public static string? ConcatIf(this string? value, bool condition, Func valueFactory) + { + if (valueFactory is null) + { + throw new ArgumentNullException(nameof(valueFactory)); + } + + return condition ? value + valueFactory() : value; + } + + /// + /// Appends a string to the current string if the specified condition evaluates to . + /// + /// The current string. + /// The function that returns the condition to evaluate. + /// The function that returns the string to append if the condition is true. + /// The concatenated string. + /// is . + [Pure] + public static string? ConcatIf(this string? value, Func conditionFactory, Func valueFactory) + { + if (conditionFactory is null) + { + throw new ArgumentNullException(nameof(conditionFactory)); + } + + if (valueFactory is null) + { + throw new ArgumentNullException(nameof(valueFactory)); + } + + return conditionFactory() ? value + valueFactory() : value; + } + /// /// Counts the occurrences of a character within the current character span. /// From 23dee3d2b8b1190f054681442491f43f923a76bb Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Fri, 14 Apr 2023 14:17:33 +0100 Subject: [PATCH 059/102] feat: add value-passthru overloads for ConcatIf --- X10D.Tests/src/Text/StringTests.cs | 23 ++++- X10D/src/Text/StringExtensions.cs | 136 ++++++++++++++++++++++++++++- 2 files changed, 154 insertions(+), 5 deletions(-) diff --git a/X10D.Tests/src/Text/StringTests.cs b/X10D.Tests/src/Text/StringTests.cs index d462186..6c94343 100644 --- a/X10D.Tests/src/Text/StringTests.cs +++ b/X10D.Tests/src/Text/StringTests.cs @@ -112,8 +112,10 @@ public class StringTests { Assert.That("Hello".ConcatIf(true, " World"), Is.EqualTo("Hello World")); Assert.That("Hello".ConcatIf(true, () => " World"), Is.EqualTo("Hello World")); + Assert.That("Hello".ConcatIf(true, _ => " World"), Is.EqualTo("Hello World")); Assert.That("Hello".ConcatIf(() => true, " World"), Is.EqualTo("Hello World")); Assert.That("Hello".ConcatIf(() => true, () => " World"), Is.EqualTo("Hello World")); + Assert.That("Hello".ConcatIf(() => true, _ => " World"), Is.EqualTo("Hello World")); }); } @@ -124,23 +126,36 @@ public class StringTests { Assert.That("Hello".ConcatIf(false, " World"), Is.EqualTo("Hello")); Assert.That("Hello".ConcatIf(false, () => " World"), Is.EqualTo("Hello")); + Assert.That("Hello".ConcatIf(false, _ => " World"), Is.EqualTo("Hello")); Assert.That("Hello".ConcatIf(() => false, " World"), Is.EqualTo("Hello")); Assert.That("Hello".ConcatIf(() => false, () => " World"), Is.EqualTo("Hello")); + Assert.That("Hello".ConcatIf(() => false, _ => " World"), Is.EqualTo("Hello")); + Assert.That("Hello".ConcatIf(_ => false, " World"), Is.EqualTo("Hello")); + Assert.That("Hello".ConcatIf(_ => false, () => " World"), Is.EqualTo("Hello")); + Assert.That("Hello".ConcatIf(_ => false, _ => " World"), Is.EqualTo("Hello")); }); } [Test] public void ConcatIf_ShouldThrowArgumentNullException_GivenNullConditionFactory() { - Assert.Throws(() => _ = "".ConcatIf(null!, "Hello World")); - Assert.Throws(() => _ = "".ConcatIf(null!, () => "Hello World")); + Assert.Throws(() => _ = "".ConcatIf((Func)null!, "Hello World")); + Assert.Throws(() => _ = "".ConcatIf((Func)null!, () => "Hello World")); + Assert.Throws(() => _ = "".ConcatIf((Func)null!, _ => "Hello World")); + Assert.Throws(() => _ = "".ConcatIf((Func)null!, "Hello World")); + Assert.Throws(() => _ = "".ConcatIf((Func)null!, () => "Hello World")); + Assert.Throws(() => _ = "".ConcatIf((Func)null!, _ => "Hello World")); } [Test] public void ConcatIf_ShouldThrowArgumentNullException_GivenNullValueFactory() { - Assert.Throws(() => _ = "".ConcatIf(true, (Func?)null!)); - Assert.Throws(() => _ = "".ConcatIf(() => true, (Func?)null!)); + Assert.Throws(() => _ = "".ConcatIf(true, (Func)null!)); + Assert.Throws(() => _ = "".ConcatIf(() => true, (Func)null!)); + Assert.Throws(() => _ = "".ConcatIf(_ => true, (Func)null!)); + Assert.Throws(() => _ = "".ConcatIf(true, (Func)null!)); + Assert.Throws(() => _ = "".ConcatIf(() => true, (Func)null!)); + Assert.Throws(() => _ = "".ConcatIf(_ => true, (Func)null!)); } [Test] diff --git a/X10D/src/Text/StringExtensions.cs b/X10D/src/Text/StringExtensions.cs index 4600931..16183f9 100644 --- a/X10D/src/Text/StringExtensions.cs +++ b/X10D/src/Text/StringExtensions.cs @@ -157,6 +157,27 @@ public static class StringExtensions return conditionFactory() ? value + appendValue : value; } + /// + /// Appends a string to the current string if the specified condition evaluates to . + /// + /// The current string. + /// + /// The function that returns the condition to evaluate, with given as an argument. + /// + /// The string to append if the condition is true. + /// The concatenated string. + /// is . + [Pure] + public static string? ConcatIf(this string? value, Func conditionFactory, string? appendValue) + { + if (conditionFactory is null) + { + throw new ArgumentNullException(nameof(conditionFactory)); + } + + return conditionFactory(value) ? value + appendValue : value; + } + /// /// Appends a string to the current string if the specified condition evaluates to . /// @@ -164,6 +185,7 @@ public static class StringExtensions /// The condition to evaluate. /// The function that returns the string to append if the condition is true. /// The concatenated string. + /// is . [Pure] public static string? ConcatIf(this string? value, bool condition, Func valueFactory) { @@ -175,6 +197,28 @@ public static class StringExtensions return condition ? value + valueFactory() : value; } + /// + /// Appends a string to the current string if the specified condition evaluates to . + /// + /// The current string. + /// The condition to evaluate. + /// + /// The function that returns the string to append if the condition is true, with given as an + /// argument. + /// + /// The concatenated string. + /// is . + [Pure] + public static string? ConcatIf(this string? value, bool condition, Func valueFactory) + { + if (valueFactory is null) + { + throw new ArgumentNullException(nameof(valueFactory)); + } + + return condition ? value + valueFactory(value) : value; + } + /// /// Appends a string to the current string if the specified condition evaluates to . /// @@ -182,7 +226,9 @@ public static class StringExtensions /// The function that returns the condition to evaluate. /// The function that returns the string to append if the condition is true. /// The concatenated string. - /// is . + /// + /// or is . + /// [Pure] public static string? ConcatIf(this string? value, Func conditionFactory, Func valueFactory) { @@ -199,6 +245,94 @@ public static class StringExtensions return conditionFactory() ? value + valueFactory() : value; } + /// + /// Appends a string to the current string if the specified condition evaluates to . + /// + /// The current string. + /// The function that returns the condition to evaluate. + /// + /// The function that returns the string to append if the condition is true, with given as an + /// argument. + /// + /// The concatenated string. + /// + /// or is . + /// + [Pure] + public static string? ConcatIf(this string? value, Func conditionFactory, Func valueFactory) + { + if (conditionFactory is null) + { + throw new ArgumentNullException(nameof(conditionFactory)); + } + + if (valueFactory is null) + { + throw new ArgumentNullException(nameof(valueFactory)); + } + + return conditionFactory() ? value + valueFactory(value) : value; + } + + /// + /// Appends a string to the current string if the specified condition evaluates to . + /// + /// The current string. + /// + /// The function that returns the condition to evaluate, with given as an argument. + /// + /// The function that returns the string to append if the condition is true. + /// The concatenated string. + /// + /// or is . + /// + [Pure] + public static string? ConcatIf(this string? value, Func conditionFactory, Func valueFactory) + { + if (conditionFactory is null) + { + throw new ArgumentNullException(nameof(conditionFactory)); + } + + if (valueFactory is null) + { + throw new ArgumentNullException(nameof(valueFactory)); + } + + return conditionFactory(value) ? value + valueFactory() : value; + } + + /// + /// Appends a string to the current string if the specified condition evaluates to . + /// + /// The current string. + /// + /// The function that returns the condition to evaluate, with given as an argument. + /// + /// + /// The function that returns the string to append if the condition is true, with given as an + /// argument. + /// + /// The concatenated string. + /// + /// or is . + /// + [Pure] + public static string? ConcatIf(this string? value, Func conditionFactory, Func valueFactory) + { + if (conditionFactory is null) + { + throw new ArgumentNullException(nameof(conditionFactory)); + } + + if (valueFactory is null) + { + throw new ArgumentNullException(nameof(valueFactory)); + } + + return conditionFactory(value) ? value + valueFactory(value) : value; + } + /// /// Counts the occurrences of a character within the current character span. /// From d8be85835981571e295d2b6c7b208a87815385b9 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Sun, 14 May 2023 16:27:42 +0100 Subject: [PATCH 060/102] refactor: remove IEnumerable.ConcatOne --- CHANGELOG.md | 4 ++++ X10D/src/Linq/EnumerableExtensions.cs | 26 -------------------------- 2 files changed, 4 insertions(+), 26 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 61bb729..eb88270 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - X10D: `DateTime.Age(DateTime)` and `DateTimeOffset.Age(DateTimeOffset)` parameter renamed from `asOf` to `referenceDate`. +### Removed + +- X10D: Removed `IEnumerable.ConcatOne` - this functionality already exists with `Append`. + ## [3.2.0] - 2023-04-03 ### Added diff --git a/X10D/src/Linq/EnumerableExtensions.cs b/X10D/src/Linq/EnumerableExtensions.cs index 05004c9..39d4002 100644 --- a/X10D/src/Linq/EnumerableExtensions.cs +++ b/X10D/src/Linq/EnumerableExtensions.cs @@ -9,32 +9,6 @@ namespace X10D.Linq; /// public static class EnumerableExtensions { - /// - /// Concatenates a single value to the end of a sequence. - /// - /// The source sequence. - /// The value to concatenate to the end of the source sequence. - /// The type of the elements in . - /// - /// An that contains the concatenated elements of the input sequence, and the specified - /// value. - /// - /// is . - public static IEnumerable ConcatOne(this IEnumerable source, TSource value) - { - if (source is null) - { - throw new ArgumentNullException(nameof(source)); - } - - foreach (TSource item in source) - { - yield return item; - } - - yield return value; - } - /// /// Filters a sequence of values by omitting elements that match a specified value. /// From 8d7ca6ea0a8f8999233f1843a3df872e355ba517 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Sun, 14 May 2023 16:31:40 +0100 Subject: [PATCH 061/102] fix(tests): remove outdated tests This should have been part of d8be85835981571e295d2b6c7b208a87815385b9 --- X10D.Tests/src/Linq/EnumerableTests.cs | 31 -------------------------- 1 file changed, 31 deletions(-) diff --git a/X10D.Tests/src/Linq/EnumerableTests.cs b/X10D.Tests/src/Linq/EnumerableTests.cs index c478578..8189443 100644 --- a/X10D.Tests/src/Linq/EnumerableTests.cs +++ b/X10D.Tests/src/Linq/EnumerableTests.cs @@ -6,37 +6,6 @@ namespace X10D.Tests.Linq; [TestFixture] public class EnumerableTests { - [Test] - public void ConcatOne_ShouldReturnConcatenatedSequence_GivenValidSequenceAndValue() - { - IEnumerable source = new[] {"Hello"}; - string[] expected = {"Hello", "World"}; - - string[] actual = source.ConcatOne("World").ToArray(); - - Assert.That(actual, Has.Length.EqualTo(2)); - CollectionAssert.AreEqual(expected, actual); - } - - [Test] - public void ConcatOne_ShouldReturnSingletonSequence_GivenEmptySequenceAndValidValue() - { - IEnumerable source = Enumerable.Empty(); - string[] expected = {"Foobar"}; - - string[] actual = source.ConcatOne("Foobar").ToArray(); - - Assert.That(actual, Has.Length.EqualTo(1)); - CollectionAssert.AreEqual(expected, actual); - } - - [Test] - public void ConcatOne_ShouldThrowArgumentNullException_GivenNullSource() - { - IEnumerable? source = null; - Assert.Throws(() => source!.ConcatOne("Foobar").ToArray()); - } - [Test] public void Except_ShouldFilterElements_GivenMatchingElements() { From 35073d9c85f80f21ea7dc86c496660753f846d35 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Mon, 5 Jun 2023 21:34:54 +0100 Subject: [PATCH 062/102] chore: bump to 3.2.1 --- X10D.DSharpPlus/X10D.DSharpPlus.csproj | 2 +- X10D.Hosting/X10D.Hosting.csproj | 2 +- X10D.Unity/X10D.Unity.csproj | 2 +- X10D/X10D.csproj | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/X10D.DSharpPlus/X10D.DSharpPlus.csproj b/X10D.DSharpPlus/X10D.DSharpPlus.csproj index 79b26aa..4e0144a 100644 --- a/X10D.DSharpPlus/X10D.DSharpPlus.csproj +++ b/X10D.DSharpPlus/X10D.DSharpPlus.csproj @@ -16,7 +16,7 @@ dotnet extension-methods $([System.IO.File]::ReadAllText("$(MSBuildProjectDirectory)/../CHANGELOG.md")) true - 4.0.0 + 3.2.1 enable true true diff --git a/X10D.Hosting/X10D.Hosting.csproj b/X10D.Hosting/X10D.Hosting.csproj index b8e4296..e352556 100644 --- a/X10D.Hosting/X10D.Hosting.csproj +++ b/X10D.Hosting/X10D.Hosting.csproj @@ -16,7 +16,7 @@ dotnet extension-methods $([System.IO.File]::ReadAllText("$(MSBuildProjectDirectory)/../CHANGELOG.md")) true - 4.0.0 + 3.2.1 enable true true diff --git a/X10D.Unity/X10D.Unity.csproj b/X10D.Unity/X10D.Unity.csproj index 90caf27..c628bdf 100644 --- a/X10D.Unity/X10D.Unity.csproj +++ b/X10D.Unity/X10D.Unity.csproj @@ -16,7 +16,7 @@ dotnet extension-methods $([System.IO.File]::ReadAllText("$(MSBuildProjectDirectory)/../CHANGELOG.md")) true - 4.0.0 + 3.2.1 enable true true diff --git a/X10D/X10D.csproj b/X10D/X10D.csproj index e034d06..6f19b46 100644 --- a/X10D/X10D.csproj +++ b/X10D/X10D.csproj @@ -17,7 +17,7 @@ README.md $([System.IO.File]::ReadAllText("$(MSBuildProjectDirectory)/../CHANGELOG.md")) true - 4.0.0 + 3.2.1 enable true true From 455b32407156901600727927e771b9046636cf81 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Mon, 5 Jun 2023 21:38:09 +0100 Subject: [PATCH 063/102] feat: add support for new usernames user discriminators become "0" if the user has a new username, distinct from "0000" for webhooks. --- CHANGELOG.md | 26 +++----------------- X10D.DSharpPlus/src/DiscordUserExtensions.cs | 6 +++++ 2 files changed, 10 insertions(+), 22 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9482e2e..b3203eb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,30 +5,11 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## 4.0.0 - [Unreleased] +## [3.2.1] - 2023-06-05 ### Added -- X10D: Added extension methods for `DateOnly`, for parity with `DateTime` and `DateTimeOffset`. -- X10D: Added math-related extension methods for `BigInteger`. -- X10D: Added `Span.Replace(T, T)`. -- X10D: Added `CountDigits` for integer types. -- X10D: Added `IEnumerable.Except(T)`. -- X10D: Added `Progress.OnProgressChanged([T])`. -- X10D: Added `TextWriter.WriteNoAlloc(int[, ReadOnlySpan[, IFormatProvider]])`. -- X10D: Added `TextWriter.WriteNoAlloc(uint[, ReadOnlySpan[, IFormatProvider]])`. -- X10D: Added `TextWriter.WriteNoAlloc(long[, ReadOnlySpan[, IFormatProvider]])`. -- X10D: Added `TextWriter.WriteNoAlloc(ulong[, ReadOnlySpan[, IFormatProvider]])`. -- X10D: Added `TextWriter.WriteLineNoAlloc(int[, ReadOnlySpan[, IFormatProvider]])`. -- X10D: Added `TextWriter.WriteLineNoAlloc(uint[, ReadOnlySpan[, IFormatProvider]])`. -- X10D: Added `TextWriter.WriteLineNoAlloc(long[, ReadOnlySpan[, IFormatProvider]])`. -- X10D: Added `TextWriter.WriteLineNoAlloc(ulong[, ReadOnlySpan[, IFormatProvider]])`. -- X10D.Unity: Added `RaycastHit.GetComponent` and `RaycastHit.TryGetComponent`. -- X10D.Unity: Added `DebugUtility.DrawFunction`, and `DebugUtility.DrawUnjoinedPolyhedron` on which it relies. - -### Changed - -- X10D: `DateTime.Age(DateTime)` and `DateTimeOffset.Age(DateTimeOffset)` parameter renamed from `asOf` to `referenceDate`. +- X10D.DSharpPlus: Added support for new usernames. See https://discord.com/blog/usernames ## [3.2.0] - 2023-04-03 @@ -592,7 +573,8 @@ please [open an issue](https://github.com/oliverbooth/X10D/issues)! Earlier versions of this package are undocumented and unlisted from package results. -[unreleased]: https://github.com/oliverbooth/X10D/compare/v3.2.0...main +[unreleased]: https://github.com/oliverbooth/X10D/compare/v3.2.1...main +[3.2.1]: https://github.com/oliverbooth/X10D/releases/tag/v3.2.1 [3.2.0]: https://github.com/oliverbooth/X10D/releases/tag/v3.2.0 [3.1.0]: https://github.com/oliverbooth/X10D/releases/tag/v3.1.0 [3.0.0]: https://github.com/oliverbooth/X10D/releases/tag/v3.0.0 diff --git a/X10D.DSharpPlus/src/DiscordUserExtensions.cs b/X10D.DSharpPlus/src/DiscordUserExtensions.cs index 6ab8314..0cc9483 100644 --- a/X10D.DSharpPlus/src/DiscordUserExtensions.cs +++ b/X10D.DSharpPlus/src/DiscordUserExtensions.cs @@ -77,6 +77,12 @@ public static class DiscordUserExtensions } #endif + if (user.Discriminator == "0") + { + // user has a new username. see: https://discord.com/blog/usernames + return user.Username; + } + return $"{user.Username}#{user.Discriminator}"; } From f84fc044ba3335d7defa9c5aa3681880d3e8b180 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Mon, 5 Jun 2023 21:46:51 +0100 Subject: [PATCH 064/102] chore: bump to 3.2.2 --- X10D.DSharpPlus/X10D.DSharpPlus.csproj | 2 +- X10D.Hosting/X10D.Hosting.csproj | 2 +- X10D.Unity/X10D.Unity.csproj | 2 +- X10D/X10D.csproj | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/X10D.DSharpPlus/X10D.DSharpPlus.csproj b/X10D.DSharpPlus/X10D.DSharpPlus.csproj index 0bef06b..9626435 100644 --- a/X10D.DSharpPlus/X10D.DSharpPlus.csproj +++ b/X10D.DSharpPlus/X10D.DSharpPlus.csproj @@ -16,7 +16,7 @@ dotnet extension-methods $([System.IO.File]::ReadAllText("$(MSBuildProjectDirectory)/../CHANGELOG.md")) true - 3.2.0 + 3.2.2 enable true true diff --git a/X10D.Hosting/X10D.Hosting.csproj b/X10D.Hosting/X10D.Hosting.csproj index af34b97..3d986d6 100644 --- a/X10D.Hosting/X10D.Hosting.csproj +++ b/X10D.Hosting/X10D.Hosting.csproj @@ -16,7 +16,7 @@ dotnet extension-methods $([System.IO.File]::ReadAllText("$(MSBuildProjectDirectory)/../CHANGELOG.md")) true - 3.2.0 + 3.2.2 enable true true diff --git a/X10D.Unity/X10D.Unity.csproj b/X10D.Unity/X10D.Unity.csproj index efb745c..b426b02 100644 --- a/X10D.Unity/X10D.Unity.csproj +++ b/X10D.Unity/X10D.Unity.csproj @@ -16,7 +16,7 @@ dotnet extension-methods $([System.IO.File]::ReadAllText("$(MSBuildProjectDirectory)/../CHANGELOG.md")) true - 3.2.0 + 3.2.2 enable true true diff --git a/X10D/X10D.csproj b/X10D/X10D.csproj index 2afcbcb..1c5424b 100644 --- a/X10D/X10D.csproj +++ b/X10D/X10D.csproj @@ -17,7 +17,7 @@ README.md $([System.IO.File]::ReadAllText("$(MSBuildProjectDirectory)/../CHANGELOG.md")) true - 3.2.0 + 3.2.2 enable true true From 103e037dc86d32811489bae4d34fa92ab666172c Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Mon, 5 Jun 2023 21:47:04 +0100 Subject: [PATCH 065/102] docs: update changelog --- CHANGELOG.md | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dc5c548..4716a77 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,17 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## 3.2.0 - [Unreleased] +## [3.2.2] - 2023-06-05 + +### Added + +- X10D.DSharpPlus: Added support for new usernames. See https://discord.com/blog/usernames + +## 3.2.1 - 2023-06-05 + +ERRONEOUS RELEASE. + +## [3.2.0] - 2023-04-03 ### Added @@ -567,7 +577,8 @@ please [open an issue](https://github.com/oliverbooth/X10D/issues)! Earlier versions of this package are undocumented and unlisted from package results. -[unreleased]: https://github.com/oliverbooth/X10D/compare/v3.1.0...develop +[unreleased]: https://github.com/oliverbooth/X10D/compare/v3.2.2...main +[3.2.0]: https://github.com/oliverbooth/X10D/releases/tag/v3.2.0 [3.1.0]: https://github.com/oliverbooth/X10D/releases/tag/v3.1.0 [3.0.0]: https://github.com/oliverbooth/X10D/releases/tag/v3.0.0 [2.6.0]: https://github.com/oliverbooth/X10D/releases/tag/2.6.0 From 678dd914d470d9453fe4c4e954e267e68b6bb0a4 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Mon, 5 Jun 2023 21:47:24 +0100 Subject: [PATCH 066/102] feat: add support for new usernames user discriminators become "0" if the user has a new username, distinct from "0000" for webhooks. --- X10D.DSharpPlus/src/DiscordUserExtensions.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/X10D.DSharpPlus/src/DiscordUserExtensions.cs b/X10D.DSharpPlus/src/DiscordUserExtensions.cs index 6ab8314..0cc9483 100644 --- a/X10D.DSharpPlus/src/DiscordUserExtensions.cs +++ b/X10D.DSharpPlus/src/DiscordUserExtensions.cs @@ -77,6 +77,12 @@ public static class DiscordUserExtensions } #endif + if (user.Discriminator == "0") + { + // user has a new username. see: https://discord.com/blog/usernames + return user.Username; + } + return $"{user.Username}#{user.Discriminator}"; } From 1a2f92c7002713e515aa2e40505f05f752505c67 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Mon, 5 Jun 2023 21:47:42 +0100 Subject: [PATCH 067/102] docs: update version in README --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 85d2dbb..36c6e54 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ X10D (pronounced *extend*), is a .NET package that provides extension methods fo ## Installation ### NuGet installation ```ps -Install-Package X10D -Version 3.2.0 +Install-Package X10D -Version 3.2.2 ``` ### Manual installation From a0b07edc823fc6db00ea7615f6c34eb19ce7e18a Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Wed, 9 Aug 2023 15:17:50 +0100 Subject: [PATCH 068/102] fix: replace Moq with a library that DOESN'T steal your pii Moq has recently introduced a payload named SponsorLink which takes PII (your email address) to send to a third party server for remote verification. This kind of suspicious data harvesting is simply unacceptable, and the developers have now destroyed all credibility and trust with their user base. This change replaces Moq with NSubstitute. For further information, see: https://github.com/moq/moq/issues/1372 --- X10D.Tests/X10D.Tests.csproj | 2 +- .../CollectionTests.ClearAndDisposeAll.cs | 21 ++++++++++--------- ...CollectionTests.ClearAndDisposeAllAsync.cs | 21 ++++++++++--------- .../Collections/EnumerableTests.DisposeAll.cs | 16 +++++++------- .../EnumerableTests.DisposeAllAsync.cs | 16 +++++++------- 5 files changed, 39 insertions(+), 37 deletions(-) diff --git a/X10D.Tests/X10D.Tests.csproj b/X10D.Tests/X10D.Tests.csproj index 00ea605..aa5bbd2 100644 --- a/X10D.Tests/X10D.Tests.csproj +++ b/X10D.Tests/X10D.Tests.csproj @@ -17,7 +17,7 @@ - + diff --git a/X10D.Tests/src/Collections/CollectionTests.ClearAndDisposeAll.cs b/X10D.Tests/src/Collections/CollectionTests.ClearAndDisposeAll.cs index ebce1e4..3330de8 100644 --- a/X10D.Tests/src/Collections/CollectionTests.ClearAndDisposeAll.cs +++ b/X10D.Tests/src/Collections/CollectionTests.ClearAndDisposeAll.cs @@ -1,5 +1,5 @@ using System.Collections.ObjectModel; -using Moq; +using NSubstitute; using NUnit.Framework; using X10D.Collections; @@ -13,16 +13,17 @@ public partial class CollectionTests [Test] public void ClearAndDisposeAll_ShouldClearAndDisposeAllItems_WhenCalledWithValidList() { - var mock1 = new Mock(); - var mock2 = new Mock(); - var mock3 = new Mock(); - var list = new List {mock1.Object, mock2.Object, mock3.Object}; + var substitute1 = Substitute.For(); + var substitute2 = Substitute.For(); + var substitute3 = Substitute.For(); + var list = new List {substitute1, substitute2, substitute3}; list.ClearAndDisposeAll(); - mock1.Verify(i => i.Dispose(), Times.Once); - mock2.Verify(i => i.Dispose(), Times.Once); - mock3.Verify(i => i.Dispose(), Times.Once); + substitute1.Received(1).Dispose(); + substitute2.Received(1).Dispose(); + substitute3.Received(1).Dispose(); + Assert.That(list, Is.Empty); } @@ -36,8 +37,8 @@ public partial class CollectionTests [Test] public void ClearAndDisposeAll_ShouldThrowInvalidOperationException_WhenCalledWithReadOnlyList() { - var mock = new Mock(); - var list = new ReadOnlyCollection(new List {mock.Object}); + var substitute = Substitute.For(); + var list = new ReadOnlyCollection(new List {substitute}); Assert.Throws(() => list.ClearAndDisposeAll()); } diff --git a/X10D.Tests/src/Collections/CollectionTests.ClearAndDisposeAllAsync.cs b/X10D.Tests/src/Collections/CollectionTests.ClearAndDisposeAllAsync.cs index 560eac7..c8b3c6a 100644 --- a/X10D.Tests/src/Collections/CollectionTests.ClearAndDisposeAllAsync.cs +++ b/X10D.Tests/src/Collections/CollectionTests.ClearAndDisposeAllAsync.cs @@ -1,5 +1,5 @@ using System.Collections.ObjectModel; -using Moq; +using NSubstitute; using NUnit.Framework; using X10D.Collections; @@ -13,16 +13,17 @@ public partial class CollectionTests [Test] public async Task ClearAndDisposeAllAsync_ShouldClearAndDisposeAllItems_WhenCalledWithValidList() { - var mock1 = new Mock(); - var mock2 = new Mock(); - var mock3 = new Mock(); - var list = new List {mock1.Object, mock2.Object, mock3.Object}; + var substitute1 = Substitute.For(); + var substitute2 = Substitute.For(); + var substitute3 = Substitute.For(); + var list = new List {substitute1, substitute2, substitute3}; await list.ClearAndDisposeAllAsync().ConfigureAwait(false); - mock1.Verify(i => i.DisposeAsync(), Times.Once); - mock2.Verify(i => i.DisposeAsync(), Times.Once); - mock3.Verify(i => i.DisposeAsync(), Times.Once); + await substitute1.Received(1).DisposeAsync(); + await substitute2.Received(1).DisposeAsync(); + await substitute3.Received(1).DisposeAsync(); + Assert.That(list, Is.Empty); } @@ -36,8 +37,8 @@ public partial class CollectionTests [Test] public void ClearAndDisposeAllAsync_ShouldThrowInvalidOperationException_WhenCalledWithReadOnlyList() { - var mock = new Mock(); - var list = new ReadOnlyCollection(new List {mock.Object}); + var substitute = Substitute.For(); + var list = new ReadOnlyCollection(new List {substitute}); Assert.ThrowsAsync(list.ClearAndDisposeAllAsync); } diff --git a/X10D.Tests/src/Collections/EnumerableTests.DisposeAll.cs b/X10D.Tests/src/Collections/EnumerableTests.DisposeAll.cs index d5a4b8e..a402ceb 100644 --- a/X10D.Tests/src/Collections/EnumerableTests.DisposeAll.cs +++ b/X10D.Tests/src/Collections/EnumerableTests.DisposeAll.cs @@ -1,4 +1,4 @@ -using Moq; +using NSubstitute; using NUnit.Framework; using X10D.Collections; @@ -12,16 +12,16 @@ public partial class EnumerableTests [Test] public void DisposeAll_ShouldDisposeAllItems_WhenCalledWithValidList() { - var mock1 = new Mock(); - var mock2 = new Mock(); - var mock3 = new Mock(); - var list = new List {mock1.Object, mock2.Object, null!, mock3.Object}; + var substitute1 = Substitute.For(); + var substitute2 = Substitute.For(); + var substitute3 = Substitute.For(); + var list = new List { substitute1, substitute2, null!, substitute3 }; list.DisposeAll(); - mock1.Verify(i => i.Dispose(), Times.Once); - mock2.Verify(i => i.Dispose(), Times.Once); - mock3.Verify(i => i.Dispose(), Times.Once); + substitute1.Received(1).Dispose(); + substitute2.Received(1).Dispose(); + substitute3.Received(1).Dispose(); } [Test] diff --git a/X10D.Tests/src/Collections/EnumerableTests.DisposeAllAsync.cs b/X10D.Tests/src/Collections/EnumerableTests.DisposeAllAsync.cs index 867006e..1510338 100644 --- a/X10D.Tests/src/Collections/EnumerableTests.DisposeAllAsync.cs +++ b/X10D.Tests/src/Collections/EnumerableTests.DisposeAllAsync.cs @@ -1,4 +1,4 @@ -using Moq; +using NSubstitute; using NUnit.Framework; using X10D.Collections; @@ -12,16 +12,16 @@ public partial class EnumerableTests [Test] public async Task DisposeAllAsync_ShouldDisposeAllItems_WhenCalledWithValidList() { - var mock1 = new Mock(); - var mock2 = new Mock(); - var mock3 = new Mock(); - var list = new List {mock1.Object, mock2.Object, null!, mock3.Object}; + var substitute1 = Substitute.For(); + var substitute2 = Substitute.For(); + var substitute3 = Substitute.For(); + var list = new List { substitute1, substitute2, null!, substitute3 }; await list.DisposeAllAsync().ConfigureAwait(false); - mock1.Verify(i => i.DisposeAsync(), Times.Once); - mock2.Verify(i => i.DisposeAsync(), Times.Once); - mock3.Verify(i => i.DisposeAsync(), Times.Once); + await substitute1.Received(1).DisposeAsync(); + await substitute2.Received(1).DisposeAsync(); + await substitute3.Received(1).DisposeAsync(); } [Test] From 9b995524dd6fa7b5c4b9497a9b08acfd723a9edf Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Mon, 21 Aug 2023 17:21:58 +0100 Subject: [PATCH 069/102] feat: add service/impl register for AddHostedSingleton --- CHANGELOG.md | 1 + .../ServiceCollectionExtensions.cs | 30 +++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 77c9538..27f75f7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - X10D: Added `TextWriter.WriteLineNoAlloc(long[, ReadOnlySpan[, IFormatProvider]])`. - X10D: Added `TextWriter.WriteLineNoAlloc(ulong[, ReadOnlySpan[, IFormatProvider]])`. - X10D: Added `string.ConcatIf`. +- X10D.Hosting: Added support for service/implementation registration with `AddHostedSingleton`. - X10D.Unity: Added `RaycastHit.GetComponent` and `RaycastHit.TryGetComponent`. - X10D.Unity: Added `DebugUtility.DrawFunction`, and `DebugUtility.DrawUnjoinedPolyhedron` on which it relies. diff --git a/X10D.Hosting/src/DependencyInjection/ServiceCollectionExtensions.cs b/X10D.Hosting/src/DependencyInjection/ServiceCollectionExtensions.cs index 9a0bafe..8df216c 100644 --- a/X10D.Hosting/src/DependencyInjection/ServiceCollectionExtensions.cs +++ b/X10D.Hosting/src/DependencyInjection/ServiceCollectionExtensions.cs @@ -21,6 +21,21 @@ public static class ServiceCollectionExtensions return services.AddSingleton(provider => provider.GetRequiredService()); } + /// + /// Adds an registration for the given type, while simultaneously adding it as a singleton. + /// + /// The to add the service to. + /// The type of the service to add. + /// The type of the implementation to use. + /// A reference to this instance after the operation has completed. + public static IServiceCollection AddHostedSingleton(this IServiceCollection services) + where TService : class, IHostedService + where TImplementation : class, TService + { + services.AddSingleton(); + return services.AddSingleton(provider => provider.GetRequiredService()); + } + /// /// Adds an registration for the given type, while simultaneously adding it as a singleton. /// @@ -32,4 +47,19 @@ public static class ServiceCollectionExtensions services.AddSingleton(type); return services.AddSingleton(provider => (IHostedService)provider.GetRequiredService(type)); } + + /// + /// Adds an registration for the given type, while simultaneously adding it as a singleton. + /// + /// The to add the service to. + /// The type of the service to register. + /// The type of the implementation to use. + /// A reference to this instance after the operation has completed. + public static IServiceCollection AddHostedSingleton(this IServiceCollection services, + Type serviceType, + Type implementationType) + { + services.AddSingleton(serviceType, implementationType); + return services.AddSingleton(provider => (IHostedService)provider.GetRequiredService(serviceType)); + } } From a715384e98fccb457650ebb844756d8d278363a3 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Mon, 21 Aug 2023 17:23:27 +0100 Subject: [PATCH 070/102] chore: bump to 3.3.0 --- X10D.DSharpPlus/X10D.DSharpPlus.csproj | 2 +- X10D.Hosting/X10D.Hosting.csproj | 2 +- X10D.Unity/X10D.Unity.csproj | 2 +- X10D/X10D.csproj | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/X10D.DSharpPlus/X10D.DSharpPlus.csproj b/X10D.DSharpPlus/X10D.DSharpPlus.csproj index 9626435..585e787 100644 --- a/X10D.DSharpPlus/X10D.DSharpPlus.csproj +++ b/X10D.DSharpPlus/X10D.DSharpPlus.csproj @@ -16,7 +16,7 @@ dotnet extension-methods $([System.IO.File]::ReadAllText("$(MSBuildProjectDirectory)/../CHANGELOG.md")) true - 3.2.2 + 3.3.0 enable true true diff --git a/X10D.Hosting/X10D.Hosting.csproj b/X10D.Hosting/X10D.Hosting.csproj index 3d986d6..074388a 100644 --- a/X10D.Hosting/X10D.Hosting.csproj +++ b/X10D.Hosting/X10D.Hosting.csproj @@ -16,7 +16,7 @@ dotnet extension-methods $([System.IO.File]::ReadAllText("$(MSBuildProjectDirectory)/../CHANGELOG.md")) true - 3.2.2 + 3.3.0 enable true true diff --git a/X10D.Unity/X10D.Unity.csproj b/X10D.Unity/X10D.Unity.csproj index 41af9ef..17c8d55 100644 --- a/X10D.Unity/X10D.Unity.csproj +++ b/X10D.Unity/X10D.Unity.csproj @@ -16,7 +16,7 @@ dotnet extension-methods $([System.IO.File]::ReadAllText("$(MSBuildProjectDirectory)/../CHANGELOG.md")) true - 3.2.2 + 3.3.0 enable true true diff --git a/X10D/X10D.csproj b/X10D/X10D.csproj index 0f853d8..d74d84a 100644 --- a/X10D/X10D.csproj +++ b/X10D/X10D.csproj @@ -17,7 +17,7 @@ README.md $([System.IO.File]::ReadAllText("$(MSBuildProjectDirectory)/../CHANGELOG.md")) true - 3.2.2 + 3.3.0 enable true true From 22532e8cef56125f4afaccd2600fded148bb876b Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Mon, 21 Aug 2023 17:25:41 +0100 Subject: [PATCH 071/102] feat: add service/impl register for AddHostedSingleton --- CHANGELOG.md | 10 ++++++- .../ServiceCollectionExtensions.cs | 30 +++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4716a77..a86ae26 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [3.3.0] - 2023-08-21 + +### Added + +- X10D.Hosting: Added support for service/implementation registration with `AddHostedSingleton`. + ## [3.2.2] - 2023-06-05 ### Added @@ -577,7 +583,9 @@ please [open an issue](https://github.com/oliverbooth/X10D/issues)! Earlier versions of this package are undocumented and unlisted from package results. -[unreleased]: https://github.com/oliverbooth/X10D/compare/v3.2.2...main +[unreleased]: https://github.com/oliverbooth/X10D/compare/v3.3.0...main +[3.3.0]: https://github.com/oliverbooth/X10D/releases/tag/v3.3.0 +[3.2.2]: https://github.com/oliverbooth/X10D/releases/tag/v3.2.2 [3.2.0]: https://github.com/oliverbooth/X10D/releases/tag/v3.2.0 [3.1.0]: https://github.com/oliverbooth/X10D/releases/tag/v3.1.0 [3.0.0]: https://github.com/oliverbooth/X10D/releases/tag/v3.0.0 diff --git a/X10D.Hosting/src/DependencyInjection/ServiceCollectionExtensions.cs b/X10D.Hosting/src/DependencyInjection/ServiceCollectionExtensions.cs index 9a0bafe..8df216c 100644 --- a/X10D.Hosting/src/DependencyInjection/ServiceCollectionExtensions.cs +++ b/X10D.Hosting/src/DependencyInjection/ServiceCollectionExtensions.cs @@ -21,6 +21,21 @@ public static class ServiceCollectionExtensions return services.AddSingleton(provider => provider.GetRequiredService()); } + /// + /// Adds an registration for the given type, while simultaneously adding it as a singleton. + /// + /// The to add the service to. + /// The type of the service to add. + /// The type of the implementation to use. + /// A reference to this instance after the operation has completed. + public static IServiceCollection AddHostedSingleton(this IServiceCollection services) + where TService : class, IHostedService + where TImplementation : class, TService + { + services.AddSingleton(); + return services.AddSingleton(provider => provider.GetRequiredService()); + } + /// /// Adds an registration for the given type, while simultaneously adding it as a singleton. /// @@ -32,4 +47,19 @@ public static class ServiceCollectionExtensions services.AddSingleton(type); return services.AddSingleton(provider => (IHostedService)provider.GetRequiredService(type)); } + + /// + /// Adds an registration for the given type, while simultaneously adding it as a singleton. + /// + /// The to add the service to. + /// The type of the service to register. + /// The type of the implementation to use. + /// A reference to this instance after the operation has completed. + public static IServiceCollection AddHostedSingleton(this IServiceCollection services, + Type serviceType, + Type implementationType) + { + services.AddSingleton(serviceType, implementationType); + return services.AddSingleton(provider => (IHostedService)provider.GetRequiredService(serviceType)); + } } From 0afe45f4d654916909aca6c07ccf0a19fcba11bc Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Mon, 21 Aug 2023 17:39:28 +0100 Subject: [PATCH 072/102] chore: bump to 3.3.1 --- X10D.DSharpPlus/X10D.DSharpPlus.csproj | 2 +- X10D.Hosting/X10D.Hosting.csproj | 2 +- X10D.Unity/X10D.Unity.csproj | 2 +- X10D/X10D.csproj | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/X10D.DSharpPlus/X10D.DSharpPlus.csproj b/X10D.DSharpPlus/X10D.DSharpPlus.csproj index 585e787..dfcf6f0 100644 --- a/X10D.DSharpPlus/X10D.DSharpPlus.csproj +++ b/X10D.DSharpPlus/X10D.DSharpPlus.csproj @@ -16,7 +16,7 @@ dotnet extension-methods $([System.IO.File]::ReadAllText("$(MSBuildProjectDirectory)/../CHANGELOG.md")) true - 3.3.0 + 3.3.1 enable true true diff --git a/X10D.Hosting/X10D.Hosting.csproj b/X10D.Hosting/X10D.Hosting.csproj index 074388a..13a36d9 100644 --- a/X10D.Hosting/X10D.Hosting.csproj +++ b/X10D.Hosting/X10D.Hosting.csproj @@ -16,7 +16,7 @@ dotnet extension-methods $([System.IO.File]::ReadAllText("$(MSBuildProjectDirectory)/../CHANGELOG.md")) true - 3.3.0 + 3.3.1 enable true true diff --git a/X10D.Unity/X10D.Unity.csproj b/X10D.Unity/X10D.Unity.csproj index 17c8d55..e68de2b 100644 --- a/X10D.Unity/X10D.Unity.csproj +++ b/X10D.Unity/X10D.Unity.csproj @@ -16,7 +16,7 @@ dotnet extension-methods $([System.IO.File]::ReadAllText("$(MSBuildProjectDirectory)/../CHANGELOG.md")) true - 3.3.0 + 3.3.1 enable true true diff --git a/X10D/X10D.csproj b/X10D/X10D.csproj index d74d84a..c9ddcf1 100644 --- a/X10D/X10D.csproj +++ b/X10D/X10D.csproj @@ -17,7 +17,7 @@ README.md $([System.IO.File]::ReadAllText("$(MSBuildProjectDirectory)/../CHANGELOG.md")) true - 3.3.0 + 3.3.1 enable true true From 42cb9acb4846b35747be25ace7f36d74fb5b9c94 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Mon, 21 Aug 2023 17:39:35 +0100 Subject: [PATCH 073/102] fix: fix AddHostedSingleton not accepting interface as service type --- CHANGELOG.md | 9 +++- .../ServiceCollectionExtensions.cs | 7 +-- .../src/Hosting/ServiceCollectionTests.cs | 53 ++++++++++++++++++- 3 files changed, 64 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a86ae26..034117e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [3.3.1] - 2023-08-21 + +### Fixed + +- X10D.Hosting: Fixed `AddHostedSingleton` not accepting an interface as the service type. + ## [3.3.0] - 2023-08-21 ### Added @@ -583,7 +589,8 @@ please [open an issue](https://github.com/oliverbooth/X10D/issues)! Earlier versions of this package are undocumented and unlisted from package results. -[unreleased]: https://github.com/oliverbooth/X10D/compare/v3.3.0...main +[unreleased]: https://github.com/oliverbooth/X10D/compare/v3.3.1...main +[3.3.1]: https://github.com/oliverbooth/X10D/releases/tag/v3.3.1 [3.3.0]: https://github.com/oliverbooth/X10D/releases/tag/v3.3.0 [3.2.2]: https://github.com/oliverbooth/X10D/releases/tag/v3.2.2 [3.2.0]: https://github.com/oliverbooth/X10D/releases/tag/v3.2.0 diff --git a/X10D.Hosting/src/DependencyInjection/ServiceCollectionExtensions.cs b/X10D.Hosting/src/DependencyInjection/ServiceCollectionExtensions.cs index 8df216c..ea0d3a4 100644 --- a/X10D.Hosting/src/DependencyInjection/ServiceCollectionExtensions.cs +++ b/X10D.Hosting/src/DependencyInjection/ServiceCollectionExtensions.cs @@ -29,11 +29,12 @@ public static class ServiceCollectionExtensions /// The type of the implementation to use. /// A reference to this instance after the operation has completed. public static IServiceCollection AddHostedSingleton(this IServiceCollection services) - where TService : class, IHostedService - where TImplementation : class, TService + where TService : class + where TImplementation : class, TService, IHostedService { services.AddSingleton(); - return services.AddSingleton(provider => provider.GetRequiredService()); + return services.AddSingleton(provider => + (TImplementation)provider.GetRequiredService()); } /// diff --git a/X10D.Tests/src/Hosting/ServiceCollectionTests.cs b/X10D.Tests/src/Hosting/ServiceCollectionTests.cs index 0ce3fd2..63a3db6 100644 --- a/X10D.Tests/src/Hosting/ServiceCollectionTests.cs +++ b/X10D.Tests/src/Hosting/ServiceCollectionTests.cs @@ -29,6 +29,27 @@ public class ServiceCollectionTests }); } + [Test] + public void AddHostedSingleton_ShouldRegisterServiceAsSingletonAndAsHostedService_GivenServiceAndImplTypes() + { + var services = new ServiceCollection(); + + services.AddHostedSingleton(); + + var serviceProvider = services.BuildServiceProvider(); + var service = serviceProvider.GetService(); + var hostedService = serviceProvider.GetService(); + + Assert.Multiple(() => + { + Assert.That(service, Is.Not.Null); + Assert.That(hostedService, Is.Not.Null); + Assert.IsAssignableFrom(service); + Assert.IsAssignableFrom(hostedService); + Assert.That(hostedService, Is.SameAs(service)); + }); + } + [Test] public void AddHostedSingleton_ShouldRegisterServiceTypeAsSingletonAndAsHostedService() { @@ -50,8 +71,38 @@ public class ServiceCollectionTests }); } - private sealed class TestService : IHostedService + [Test] + public void AddHostedSingleton_ShouldRegisterServiceTypeAsSingletonAndAsHostedService_GivenServiceAndImplTypes() { + var services = new ServiceCollection(); + + services.AddHostedSingleton(typeof(ITestService), typeof(TestService)); + + var serviceProvider = services.BuildServiceProvider(); + var service = serviceProvider.GetService(); + var hostedService = serviceProvider.GetService(); + + Assert.Multiple(() => + { + Assert.That(service, Is.Not.Null); + Assert.That(hostedService, Is.Not.Null); + Assert.IsAssignableFrom(service); + Assert.IsAssignableFrom(hostedService); + Assert.That(hostedService, Is.SameAs(service)); + }); + } + + private interface ITestService + { + void Foo(); + } + + private sealed class TestService : ITestService, IHostedService + { + public void Foo() + { + } + public Task StartAsync(CancellationToken cancellationToken) { return Task.CompletedTask; From a9cde347bdb462b3760c42e856261f704667606d Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Mon, 21 Aug 2023 17:42:59 +0100 Subject: [PATCH 074/102] [ci skip] docs: bump to 3.3.1 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 36c6e54..183602b 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ X10D (pronounced *extend*), is a .NET package that provides extension methods fo ## Installation ### NuGet installation ```ps -Install-Package X10D -Version 3.2.2 +Install-Package X10D -Version 3.3.1 ``` ### Manual installation From e8a331ff9693432b1f2804d6099bd29f09d36cf6 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Tue, 22 Aug 2023 17:11:20 +0100 Subject: [PATCH 075/102] chore: use shared Build.props for all projects --- Directory.Build.props | 67 ++++++++++++++++++++++++++ X10D.DSharpPlus/X10D.DSharpPlus.csproj | 58 ---------------------- X10D.Hosting/X10D.Hosting.csproj | 58 ---------------------- X10D.Tests/X10D.Tests.csproj | 5 +- X10D.Unity/X10D.Unity.csproj | 58 ---------------------- X10D.sln | 1 + X10D/X10D.csproj | 63 ------------------------ 7 files changed, 70 insertions(+), 240 deletions(-) create mode 100644 Directory.Build.props diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 0000000..be302ef --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,67 @@ + + + 11.0 + true + true + true + true + true + pdbonly + true + 4.0.0 + Oliver Booth + enable + en + https://github.com/oliverbooth/X10D + git + Extension methods on crack. + LICENSE.md + branding_Icon.png + + dotnet extension-methods + README.md + $([System.IO.File]::ReadAllText("$(SolutionDir)/CHANGELOG.md")) + true + + + + true + + + + $(VersionPrefix)-$(VersionSuffix) + $(VersionPrefix).0 + $(VersionPrefix).0 + + + + $(VersionPrefix)-$(VersionSuffix).$(BuildNumber) + $(VersionPrefix).$(BuildNumber) + $(VersionPrefix).$(BuildNumber) + + + + $(VersionPrefix) + $(VersionPrefix).0 + $(VersionPrefix).0 + + + + + True + + + + True + + + + True + + + + True + + + + \ No newline at end of file diff --git a/X10D.DSharpPlus/X10D.DSharpPlus.csproj b/X10D.DSharpPlus/X10D.DSharpPlus.csproj index 79b26aa..9128252 100644 --- a/X10D.DSharpPlus/X10D.DSharpPlus.csproj +++ b/X10D.DSharpPlus/X10D.DSharpPlus.csproj @@ -2,69 +2,11 @@ net7.0;net6.0;netstandard2.1 - 11.0 - true - true - Oliver Booth - en - https://github.com/oliverbooth/X10D - git - Extension methods on crack. - LICENSE.md - branding_Icon.png - - dotnet extension-methods - $([System.IO.File]::ReadAllText("$(MSBuildProjectDirectory)/../CHANGELOG.md")) - true - 4.0.0 - enable - true - true true - true - pdbonly - true - - - - true - - - - $(VersionPrefix)-$(VersionSuffix) - $(VersionPrefix).0 - $(VersionPrefix).0 - - - - $(VersionPrefix)-$(VersionSuffix).$(BuildNumber) - $(VersionPrefix).$(BuildNumber) - $(VersionPrefix).$(BuildNumber) - - - - $(VersionPrefix) - $(VersionPrefix).0 - $(VersionPrefix).0 - - - True - - - - True - - - - True - - - - diff --git a/X10D.Hosting/X10D.Hosting.csproj b/X10D.Hosting/X10D.Hosting.csproj index b8e4296..a534fa0 100644 --- a/X10D.Hosting/X10D.Hosting.csproj +++ b/X10D.Hosting/X10D.Hosting.csproj @@ -2,68 +2,10 @@ net7.0;net6.0;netstandard2.1 - 11.0 - true - true - Oliver Booth - en - https://github.com/oliverbooth/X10D - git - Extension methods on crack. - LICENSE.md - branding_Icon.png - - dotnet extension-methods - $([System.IO.File]::ReadAllText("$(MSBuildProjectDirectory)/../CHANGELOG.md")) - true - 4.0.0 - enable - true - true - true - pdbonly - true - - - - true - - - - $(VersionPrefix)-$(VersionSuffix) - $(VersionPrefix).0 - $(VersionPrefix).0 - - - - $(VersionPrefix)-$(VersionSuffix).$(BuildNumber) - $(VersionPrefix).$(BuildNumber) - $(VersionPrefix).$(BuildNumber) - - - - $(VersionPrefix) - $(VersionPrefix).0 - $(VersionPrefix).0 - - - True - - - - True - - - - True - - - - diff --git a/X10D.Tests/X10D.Tests.csproj b/X10D.Tests/X10D.Tests.csproj index aa5bbd2..567e11c 100644 --- a/X10D.Tests/X10D.Tests.csproj +++ b/X10D.Tests/X10D.Tests.csproj @@ -2,12 +2,11 @@ net7.0;net6.0;netcoreapp3.1 - 11.0 false - enable - true json,cobertura true + false + $(NoWarn);1591 diff --git a/X10D.Unity/X10D.Unity.csproj b/X10D.Unity/X10D.Unity.csproj index 90caf27..b1584ea 100644 --- a/X10D.Unity/X10D.Unity.csproj +++ b/X10D.Unity/X10D.Unity.csproj @@ -2,49 +2,6 @@ netstandard2.1 - 11.0 - true - true - Oliver Booth - en - https://github.com/oliverbooth/X10D - git - Extension methods on crack. - LICENSE.md - branding_Icon.png - - dotnet extension-methods - $([System.IO.File]::ReadAllText("$(MSBuildProjectDirectory)/../CHANGELOG.md")) - true - 4.0.0 - enable - true - true - true - pdbonly - true - - - - true - - - - $(VersionPrefix)-$(VersionSuffix) - $(VersionPrefix).0 - $(VersionPrefix).0 - - - - $(VersionPrefix)-$(VersionSuffix).$(BuildNumber) - $(VersionPrefix).$(BuildNumber) - $(VersionPrefix).$(BuildNumber) - - - - $(VersionPrefix) - $(VersionPrefix).0 - $(VersionPrefix).0 @@ -55,21 +12,6 @@ - - - True - - - - True - - - - True - - - - ResXFileCodeGenerator diff --git a/X10D.sln b/X10D.sln index dd11b7d..b1b36a2 100644 --- a/X10D.sln +++ b/X10D.sln @@ -16,6 +16,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution LICENSE.md = LICENSE.md README.md = README.md branding_Icon.png = branding_Icon.png + Directory.Build.props = Directory.Build.props EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SourceValidator", "tools\SourceValidator\SourceValidator.csproj", "{84750149-9068-4780-AFDE-CDA1AC57007D}" diff --git a/X10D/X10D.csproj b/X10D/X10D.csproj index e034d06..7994902 100644 --- a/X10D/X10D.csproj +++ b/X10D/X10D.csproj @@ -2,71 +2,8 @@ net7.0;net6.0;netstandard2.1 - 11.0 - true - true - Oliver Booth - en - https://github.com/oliverbooth/X10D - git - Extension methods on crack. - LICENSE.md - branding_Icon.png - - dotnet extension-methods - README.md - $([System.IO.File]::ReadAllText("$(MSBuildProjectDirectory)/../CHANGELOG.md")) - true - 4.0.0 - enable - true - true - true - pdbonly - true - - true - - - - $(VersionPrefix)-$(VersionSuffix) - $(VersionPrefix).0 - $(VersionPrefix).0 - - - - $(VersionPrefix)-$(VersionSuffix).$(BuildNumber) - $(VersionPrefix).$(BuildNumber) - $(VersionPrefix).$(BuildNumber) - - - - $(VersionPrefix) - $(VersionPrefix).0 - $(VersionPrefix).0 - - - - - True - - - - True - - - - True - - - - True - - - - True From 24a7de7e8c116d8d12e0fd7301c99b1103bb0cec Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Tue, 22 Aug 2023 17:32:47 +0100 Subject: [PATCH 076/102] refactor: define test fixtures as internal --- X10D.Tests/X10D.Tests.csproj | 1 - X10D.Tests/src/Assembly.cs | 2 +- .../src/Collections/ArrayTests.AsReadOnly.cs | 4 ++-- X10D.Tests/src/Collections/ArrayTests.Clear.cs | 2 +- X10D.Tests/src/Collections/ArrayTests.cs | 2 +- X10D.Tests/src/Collections/BoolListTests.cs | 2 +- X10D.Tests/src/Collections/ByteTests.cs | 2 +- .../CollectionTests.ClearAndDisposeAll.cs | 2 +- .../CollectionTests.ClearAndDisposeAllAsync.cs | 2 +- X10D.Tests/src/Collections/CollectionTests.cs | 2 +- X10D.Tests/src/Collections/DictionaryTests.cs | 2 +- .../Collections/EnumerableTests.DisposeAll.cs | 2 +- .../EnumerableTests.DisposeAllAsync.cs | 2 +- X10D.Tests/src/Collections/EnumerableTests.cs | 2 +- X10D.Tests/src/Collections/Int16Tests.cs | 2 +- X10D.Tests/src/Collections/Int32Tests.cs | 2 +- X10D.Tests/src/Collections/Int64Tests.cs | 7 ++++--- X10D.Tests/src/Collections/ListTests.cs | 8 +++----- X10D.Tests/src/Collections/SpanTest.cs | 2 +- X10D.Tests/src/Core/CoreTests.cs | 2 +- X10D.Tests/src/Core/EnumTests.cs | 2 +- X10D.Tests/src/Core/IntrinsicTests.cs | 2 +- X10D.Tests/src/Core/NullableTests.cs | 2 +- X10D.Tests/src/Core/RandomTests.cs | 2 +- X10D.Tests/src/Core/SpanTest.cs | 2 +- X10D.Tests/src/Drawing/CircleFTests.cs | 2 +- X10D.Tests/src/Drawing/CircleTests.cs | 2 +- X10D.Tests/src/Drawing/ColorTests.cs | 2 +- X10D.Tests/src/Drawing/CuboidTests.cs | 2 +- X10D.Tests/src/Drawing/EllipseFTests.cs | 2 +- X10D.Tests/src/Drawing/EllipseTests.cs | 2 +- X10D.Tests/src/Drawing/Line3DTests.cs | 2 +- X10D.Tests/src/Drawing/LineFTests.cs | 2 +- X10D.Tests/src/Drawing/LineTests.cs | 2 +- X10D.Tests/src/Drawing/PointFTests.cs | 2 +- X10D.Tests/src/Drawing/PointTests.cs | 2 +- X10D.Tests/src/Drawing/PolygonFTests.cs | 2 +- X10D.Tests/src/Drawing/PolygonTests.cs | 2 +- X10D.Tests/src/Drawing/PolyhedronTests.cs | 2 +- X10D.Tests/src/Drawing/RandomTests.cs | 2 +- X10D.Tests/src/Drawing/SizeTests.cs | 2 +- X10D.Tests/src/Drawing/SphereTests.cs | 2 +- .../src/Hosting/ServiceCollectionTests.cs | 2 +- X10D.Tests/src/IO/BooleanTests.cs | 2 +- X10D.Tests/src/IO/ByteTests.cs | 2 +- X10D.Tests/src/IO/DirectoryInfoTests.cs | 2 +- X10D.Tests/src/IO/DoubleTests.cs | 2 +- X10D.Tests/src/IO/FileInfoTests.cs | 2 +- X10D.Tests/src/IO/Int16Tests.cs | 2 +- X10D.Tests/src/IO/Int32Tests.cs | 2 +- X10D.Tests/src/IO/Int64Tests.cs | 2 +- X10D.Tests/src/IO/ListOfByteTests.cs | 2 +- X10D.Tests/src/IO/SByteTests.cs | 3 +-- X10D.Tests/src/IO/SingleTests.cs | 2 +- X10D.Tests/src/IO/StreamTests.ReadDecimal.cs | 2 +- X10D.Tests/src/IO/StreamTests.ReadDouble.cs | 2 +- X10D.Tests/src/IO/StreamTests.ReadInt16.cs | 2 +- X10D.Tests/src/IO/StreamTests.ReadInt32.cs | 2 +- X10D.Tests/src/IO/StreamTests.ReadInt64.cs | 2 +- X10D.Tests/src/IO/StreamTests.ReadSingle.cs | 2 +- X10D.Tests/src/IO/StreamTests.ReadUInt16.cs | 17 ++++++----------- X10D.Tests/src/IO/StreamTests.ReadUInt32.cs | 17 ++++++----------- X10D.Tests/src/IO/StreamTests.ReadUInt64.cs | 17 ++++++----------- X10D.Tests/src/IO/StreamTests.WriteDecimal.cs | 2 +- X10D.Tests/src/IO/StreamTests.WriteDouble.cs | 2 +- X10D.Tests/src/IO/StreamTests.WriteInt16.cs | 2 +- X10D.Tests/src/IO/StreamTests.WriteInt32.cs | 2 +- X10D.Tests/src/IO/StreamTests.WriteInt64.cs | 2 +- X10D.Tests/src/IO/StreamTests.WriteSingle.cs | 2 +- X10D.Tests/src/IO/StreamTests.WriteUInt16.cs | 17 ++++++----------- X10D.Tests/src/IO/StreamTests.WriteUInt32.cs | 17 ++++++----------- X10D.Tests/src/IO/StreamTests.WriteUInt64.cs | 17 ++++++----------- X10D.Tests/src/IO/StreamTests.cs | 2 +- X10D.Tests/src/IO/TextReaderTests.cs | 2 +- X10D.Tests/src/IO/TextWriterTests.Double.cs | 2 +- X10D.Tests/src/IO/TextWriterTests.Int32.cs | 2 +- X10D.Tests/src/IO/TextWriterTests.Int64.cs | 2 +- X10D.Tests/src/IO/TextWriterTests.Single.cs | 2 +- X10D.Tests/src/IO/TextWriterTests.UInt32.cs | 2 +- X10D.Tests/src/IO/TextWriterTests.UInt64.cs | 2 +- X10D.Tests/src/IO/TextWriterTests.cs | 4 +++- X10D.Tests/src/IO/UInt16Tests.cs | 3 +-- X10D.Tests/src/IO/UInt32Tests.cs | 3 +-- X10D.Tests/src/IO/UInt64Tests.cs | 3 +-- X10D.Tests/src/Linq/ByteTests.cs | 2 +- X10D.Tests/src/Linq/DecimalTests.cs | 2 +- X10D.Tests/src/Linq/DoubleTests.cs | 2 +- X10D.Tests/src/Linq/EnumerableTests.cs | 2 +- X10D.Tests/src/Linq/Int16Tests.cs | 2 +- X10D.Tests/src/Linq/Int32Tests.cs | 2 +- X10D.Tests/src/Linq/Int64Tests.cs | 2 +- X10D.Tests/src/Linq/ReadOnlySpanTests.cs | 2 +- X10D.Tests/src/Linq/SByteTests.cs | 3 +-- X10D.Tests/src/Linq/SingleTests.cs | 2 +- X10D.Tests/src/Linq/SpanTests.cs | 2 +- X10D.Tests/src/Linq/UInt16Tests.cs | 3 +-- X10D.Tests/src/Linq/UInt32Tests.cs | 3 +-- X10D.Tests/src/Linq/UInt64Tests.cs | 3 +-- X10D.Tests/src/Math/BigIntegerTests.Wrap.cs | 2 +- X10D.Tests/src/Math/BigIntegerTests.cs | 2 +- X10D.Tests/src/Math/ByteTests.Wrap.cs | 2 +- X10D.Tests/src/Math/ByteTests.cs | 2 +- X10D.Tests/src/Math/ComparableTests.cs | 2 +- X10D.Tests/src/Math/DecimalTests.Wrap.cs | 2 +- X10D.Tests/src/Math/DecimalTests.cs | 2 +- X10D.Tests/src/Math/DoubleTests.Wrap.cs | 2 +- X10D.Tests/src/Math/DoubleTests.cs | 2 +- X10D.Tests/src/Math/Int16Tests.Wrap.cs | 2 +- X10D.Tests/src/Math/Int16Tests.cs | 2 +- X10D.Tests/src/Math/Int32Tests.Wrap.cs | 2 +- X10D.Tests/src/Math/Int32Tests.cs | 2 +- X10D.Tests/src/Math/Int64Tests.Wrap.cs | 2 +- X10D.Tests/src/Math/Int64Tests.cs | 2 +- X10D.Tests/src/Math/IsPrimeTests.cs | 2 +- X10D.Tests/src/Math/MathUtilityTests.cs | 2 +- X10D.Tests/src/Math/SByteTests.Wrap.cs | 2 +- X10D.Tests/src/Math/SByteTests.cs | 3 +-- X10D.Tests/src/Math/SingleTests.Wrap.cs | 2 +- X10D.Tests/src/Math/SingleTests.cs | 2 +- X10D.Tests/src/Math/UInt16Tests.Wrap.cs | 2 +- X10D.Tests/src/Math/UInt16Tests.cs | 3 +-- X10D.Tests/src/Math/UInt32Tests.Wrap.cs | 2 +- X10D.Tests/src/Math/UInt32Tests.cs | 3 +-- X10D.Tests/src/Math/UInt64Tests.Wrap.cs | 2 +- X10D.Tests/src/Math/UInt64Tests.cs | 3 +-- X10D.Tests/src/Net/EndPointTests.cs | 2 +- X10D.Tests/src/Net/IPAddressTests.cs | 2 +- X10D.Tests/src/Net/Int16Tests.cs | 2 +- X10D.Tests/src/Net/Int32Tests.cs | 2 +- X10D.Tests/src/Net/Int64Tests.cs | 2 +- X10D.Tests/src/Numerics/ByteTests.cs | 2 +- X10D.Tests/src/Numerics/Int16Tests.cs | 2 +- X10D.Tests/src/Numerics/Int32Tests.cs | 2 +- X10D.Tests/src/Numerics/Int64Tests.cs | 2 +- X10D.Tests/src/Numerics/QuaternionTests.cs | 2 +- X10D.Tests/src/Numerics/RandomTests.cs | 2 +- X10D.Tests/src/Numerics/SByteTests.cs | 3 +-- X10D.Tests/src/Numerics/UInt16Tests.cs | 3 +-- X10D.Tests/src/Numerics/UInt32Tests.cs | 3 +-- X10D.Tests/src/Numerics/UInt64Tests.cs | 3 +-- X10D.Tests/src/Numerics/Vector2Tests.cs | 2 +- X10D.Tests/src/Numerics/Vector3Tests.cs | 2 +- X10D.Tests/src/Numerics/Vector4Tests.cs | 2 +- X10D.Tests/src/Reactive/ProgressTests.cs | 2 +- X10D.Tests/src/Reflection/MemberInfoTests.cs | 2 +- X10D.Tests/src/Reflection/TypeTests.cs | 2 +- X10D.Tests/src/Text/CharSpanTests.cs | 2 +- X10D.Tests/src/Text/CharTests.cs | 2 +- X10D.Tests/src/Text/CoreTests.cs | 2 +- X10D.Tests/src/Text/EnumerableTests.cs | 2 +- X10D.Tests/src/Text/RuneTests.cs | 2 +- X10D.Tests/src/Text/StringBuilderReaderTests.cs | 2 +- X10D.Tests/src/Text/StringTests.cs | 2 +- X10D.Tests/src/Time/ByteTests.cs | 2 +- X10D.Tests/src/Time/CharSpanTests.cs | 2 +- X10D.Tests/src/Time/DateOnlyTests.cs | 2 +- X10D.Tests/src/Time/DateTimeOffsetTests.cs | 2 +- X10D.Tests/src/Time/DateTimeTests.cs | 2 +- X10D.Tests/src/Time/DecimalTests.cs | 2 +- X10D.Tests/src/Time/DoubleTests.cs | 2 +- X10D.Tests/src/Time/HalfTests.cs | 2 +- X10D.Tests/src/Time/Int16Tests.cs | 2 +- X10D.Tests/src/Time/Int32Tests.cs | 2 +- X10D.Tests/src/Time/Int64Tests.cs | 2 +- X10D.Tests/src/Time/SByteTests.cs | 3 +-- X10D.Tests/src/Time/SingleTests.cs | 2 +- X10D.Tests/src/Time/StringTests.cs | 2 +- X10D.Tests/src/Time/TimeSpanParserTests.cs | 2 +- X10D.Tests/src/Time/TimeSpanTests.cs | 2 +- X10D.Tests/src/Time/UInt16Tests.cs | 3 +-- X10D.Tests/src/Time/UInt32Tests.cs | 3 +-- X10D.Tests/src/Time/UInt64Tests.cs | 3 +-- 172 files changed, 209 insertions(+), 259 deletions(-) diff --git a/X10D.Tests/X10D.Tests.csproj b/X10D.Tests/X10D.Tests.csproj index 567e11c..4af78b2 100644 --- a/X10D.Tests/X10D.Tests.csproj +++ b/X10D.Tests/X10D.Tests.csproj @@ -6,7 +6,6 @@ json,cobertura true false - $(NoWarn);1591 diff --git a/X10D.Tests/src/Assembly.cs b/X10D.Tests/src/Assembly.cs index f547610..4e11466 100644 --- a/X10D.Tests/src/Assembly.cs +++ b/X10D.Tests/src/Assembly.cs @@ -1 +1 @@ -[assembly: CLSCompliant(true)] +[assembly: CLSCompliant(false)] diff --git a/X10D.Tests/src/Collections/ArrayTests.AsReadOnly.cs b/X10D.Tests/src/Collections/ArrayTests.AsReadOnly.cs index d576b26..e1d010d 100644 --- a/X10D.Tests/src/Collections/ArrayTests.AsReadOnly.cs +++ b/X10D.Tests/src/Collections/ArrayTests.AsReadOnly.cs @@ -3,10 +3,10 @@ using X10D.Collections; namespace X10D.Tests.Collections; -public partial class ArrayTests +internal static partial class ArrayTests { [TestFixture] - public class AsReadOnlyTests + internal class AsReadOnlyTests { [Test] public void AsReadOnly_ShouldReturnReadOnlyCollection_WhenArrayIsNotNull() diff --git a/X10D.Tests/src/Collections/ArrayTests.Clear.cs b/X10D.Tests/src/Collections/ArrayTests.Clear.cs index 4679b83..5608952 100644 --- a/X10D.Tests/src/Collections/ArrayTests.Clear.cs +++ b/X10D.Tests/src/Collections/ArrayTests.Clear.cs @@ -3,7 +3,7 @@ using X10D.Collections; namespace X10D.Tests.Collections; -public partial class ArrayTests +internal static partial class ArrayTests { [TestFixture] public class ClearTests diff --git a/X10D.Tests/src/Collections/ArrayTests.cs b/X10D.Tests/src/Collections/ArrayTests.cs index 90e5cd2..53c46f5 100644 --- a/X10D.Tests/src/Collections/ArrayTests.cs +++ b/X10D.Tests/src/Collections/ArrayTests.cs @@ -3,6 +3,6 @@ namespace X10D.Tests.Collections; [TestFixture] -public partial class ArrayTests +internal static partial class ArrayTests { } diff --git a/X10D.Tests/src/Collections/BoolListTests.cs b/X10D.Tests/src/Collections/BoolListTests.cs index a2ad121..c90bc16 100644 --- a/X10D.Tests/src/Collections/BoolListTests.cs +++ b/X10D.Tests/src/Collections/BoolListTests.cs @@ -4,7 +4,7 @@ using X10D.Collections; namespace X10D.Tests.Collections; [TestFixture] -public class BoolListTests +internal class BoolListTests { [Test] public void PackByte_Should_Pack_Correctly() diff --git a/X10D.Tests/src/Collections/ByteTests.cs b/X10D.Tests/src/Collections/ByteTests.cs index 088fa00..4f35f86 100644 --- a/X10D.Tests/src/Collections/ByteTests.cs +++ b/X10D.Tests/src/Collections/ByteTests.cs @@ -5,7 +5,7 @@ using X10D.Collections; namespace X10D.Tests.Collections; [TestFixture] -public class ByteTests +internal class ByteTests { [Test] public void Unpack_ShouldUnpackToArrayCorrectly() diff --git a/X10D.Tests/src/Collections/CollectionTests.ClearAndDisposeAll.cs b/X10D.Tests/src/Collections/CollectionTests.ClearAndDisposeAll.cs index 3330de8..24c542f 100644 --- a/X10D.Tests/src/Collections/CollectionTests.ClearAndDisposeAll.cs +++ b/X10D.Tests/src/Collections/CollectionTests.ClearAndDisposeAll.cs @@ -5,7 +5,7 @@ using X10D.Collections; namespace X10D.Tests.Collections; -public partial class CollectionTests +internal partial class CollectionTests { [TestFixture] public class ClearAndDisposeAllTests diff --git a/X10D.Tests/src/Collections/CollectionTests.ClearAndDisposeAllAsync.cs b/X10D.Tests/src/Collections/CollectionTests.ClearAndDisposeAllAsync.cs index c8b3c6a..e176fa0 100644 --- a/X10D.Tests/src/Collections/CollectionTests.ClearAndDisposeAllAsync.cs +++ b/X10D.Tests/src/Collections/CollectionTests.ClearAndDisposeAllAsync.cs @@ -5,7 +5,7 @@ using X10D.Collections; namespace X10D.Tests.Collections; -public partial class CollectionTests +internal partial class CollectionTests { [TestFixture] public class ClearAndDisposeAllAsyncTests diff --git a/X10D.Tests/src/Collections/CollectionTests.cs b/X10D.Tests/src/Collections/CollectionTests.cs index ba825f6..8452830 100644 --- a/X10D.Tests/src/Collections/CollectionTests.cs +++ b/X10D.Tests/src/Collections/CollectionTests.cs @@ -3,6 +3,6 @@ namespace X10D.Tests.Collections; [TestFixture] -public partial class CollectionTests +internal partial class CollectionTests { } diff --git a/X10D.Tests/src/Collections/DictionaryTests.cs b/X10D.Tests/src/Collections/DictionaryTests.cs index 1882dad..c420375 100644 --- a/X10D.Tests/src/Collections/DictionaryTests.cs +++ b/X10D.Tests/src/Collections/DictionaryTests.cs @@ -4,7 +4,7 @@ using X10D.Collections; namespace X10D.Tests.Collections; [TestFixture] -public class DictionaryTests +internal class DictionaryTests { [Test] public void AddOrUpdate_ShouldAddNewKey_IfNotExists_GivenConcreteDictionary() diff --git a/X10D.Tests/src/Collections/EnumerableTests.DisposeAll.cs b/X10D.Tests/src/Collections/EnumerableTests.DisposeAll.cs index a402ceb..6f8519b 100644 --- a/X10D.Tests/src/Collections/EnumerableTests.DisposeAll.cs +++ b/X10D.Tests/src/Collections/EnumerableTests.DisposeAll.cs @@ -4,7 +4,7 @@ using X10D.Collections; namespace X10D.Tests.Collections; -public partial class EnumerableTests +internal partial class EnumerableTests { [TestFixture] public class DisposeAllTests diff --git a/X10D.Tests/src/Collections/EnumerableTests.DisposeAllAsync.cs b/X10D.Tests/src/Collections/EnumerableTests.DisposeAllAsync.cs index 1510338..9cd238f 100644 --- a/X10D.Tests/src/Collections/EnumerableTests.DisposeAllAsync.cs +++ b/X10D.Tests/src/Collections/EnumerableTests.DisposeAllAsync.cs @@ -4,7 +4,7 @@ using X10D.Collections; namespace X10D.Tests.Collections; -public partial class EnumerableTests +internal partial class EnumerableTests { [TestFixture] public class DisposeAllAsyncTests diff --git a/X10D.Tests/src/Collections/EnumerableTests.cs b/X10D.Tests/src/Collections/EnumerableTests.cs index 0fbc23e..df6442c 100644 --- a/X10D.Tests/src/Collections/EnumerableTests.cs +++ b/X10D.Tests/src/Collections/EnumerableTests.cs @@ -5,7 +5,7 @@ using X10D.Core; namespace X10D.Tests.Collections; [TestFixture] -public partial class EnumerableTests +internal partial class EnumerableTests { [Test] public void CountWhereNot_ShouldReturnCorrectCount_GivenSequence() diff --git a/X10D.Tests/src/Collections/Int16Tests.cs b/X10D.Tests/src/Collections/Int16Tests.cs index 63c2cef..9e44f49 100644 --- a/X10D.Tests/src/Collections/Int16Tests.cs +++ b/X10D.Tests/src/Collections/Int16Tests.cs @@ -5,7 +5,7 @@ using X10D.Collections; namespace X10D.Tests.Collections; [TestFixture] -public class Int16Tests +internal class Int16Tests { [Test] public void Unpack_ShouldUnpackToArrayCorrectly() diff --git a/X10D.Tests/src/Collections/Int32Tests.cs b/X10D.Tests/src/Collections/Int32Tests.cs index 9aee1e8..219ecd3 100644 --- a/X10D.Tests/src/Collections/Int32Tests.cs +++ b/X10D.Tests/src/Collections/Int32Tests.cs @@ -5,7 +5,7 @@ using X10D.Collections; namespace X10D.Tests.Collections; [TestFixture] -public class Int32Tests +internal class Int32Tests { [Test] public void Unpack_ShouldUnpackToArrayCorrectly() diff --git a/X10D.Tests/src/Collections/Int64Tests.cs b/X10D.Tests/src/Collections/Int64Tests.cs index 02b89df..1cfee79 100644 --- a/X10D.Tests/src/Collections/Int64Tests.cs +++ b/X10D.Tests/src/Collections/Int64Tests.cs @@ -1,11 +1,12 @@ using System.Diagnostics; +using System.Globalization; using NUnit.Framework; using X10D.Collections; namespace X10D.Tests.Collections; [TestFixture] -public class Int64Tests +internal class Int64Tests { [Test] public void UnpackBits_ShouldUnpackToArrayCorrectly() @@ -29,7 +30,7 @@ public class Int64Tests for (var index = 8; index < 64; index++) { - Assert.That(bits[index], Is.False, index.ToString()); + Assert.That(bits[index], Is.False, index.ToString(CultureInfo.InvariantCulture)); } }); } @@ -53,7 +54,7 @@ public class Int64Tests for (var index = 8; index < 64; index++) { - Assert.That(bits[index], Is.False, index.ToString()); + Assert.That(bits[index], Is.False, index.ToString(CultureInfo.InvariantCulture)); } }); } diff --git a/X10D.Tests/src/Collections/ListTests.cs b/X10D.Tests/src/Collections/ListTests.cs index 095444f..bd62f8c 100644 --- a/X10D.Tests/src/Collections/ListTests.cs +++ b/X10D.Tests/src/Collections/ListTests.cs @@ -4,10 +4,9 @@ using X10D.Collections; namespace X10D.Tests.Collections; [TestFixture] -public class ListTests +internal class ListTests { - [CLSCompliant(false)] - [Test] + [Test] [TestCase(1)] [TestCase(1, 2, 3)] [TestCase(1, 2, 3, 4, 5)] @@ -26,8 +25,7 @@ public class ListTests CollectionAssert.AreEqual(all42, list); } - [CLSCompliant(false)] - [Test] + [Test] [TestCase(1)] [TestCase(1, 2, 3)] [TestCase(1, 2, 3, 4, 5)] diff --git a/X10D.Tests/src/Collections/SpanTest.cs b/X10D.Tests/src/Collections/SpanTest.cs index 0c59d1c..04f263a 100644 --- a/X10D.Tests/src/Collections/SpanTest.cs +++ b/X10D.Tests/src/Collections/SpanTest.cs @@ -4,7 +4,7 @@ using X10D.Collections; namespace X10D.Tests.Collections; [TestFixture] -public class SpanTest +internal class SpanTest { [Test] public void Count_ShouldReturn0_GivenEmptySpan() diff --git a/X10D.Tests/src/Core/CoreTests.cs b/X10D.Tests/src/Core/CoreTests.cs index 41f1436..fea360d 100644 --- a/X10D.Tests/src/Core/CoreTests.cs +++ b/X10D.Tests/src/Core/CoreTests.cs @@ -4,7 +4,7 @@ using X10D.Core; namespace X10D.Tests.Core; [TestFixture] -public class CoreTests +internal class CoreTests { [Test] [TestCase(1)] diff --git a/X10D.Tests/src/Core/EnumTests.cs b/X10D.Tests/src/Core/EnumTests.cs index 4469874..c335b9a 100644 --- a/X10D.Tests/src/Core/EnumTests.cs +++ b/X10D.Tests/src/Core/EnumTests.cs @@ -4,7 +4,7 @@ using X10D.Core; namespace X10D.Tests.Core; [TestFixture] -public class EnumTests +internal class EnumTests { // Microsoft wrongfully decided to have Sunday be 0, Monday be 1, etc. // I personally hate this, Sunday is not the first day of the week. diff --git a/X10D.Tests/src/Core/IntrinsicTests.cs b/X10D.Tests/src/Core/IntrinsicTests.cs index ecda634..da5fd8e 100644 --- a/X10D.Tests/src/Core/IntrinsicTests.cs +++ b/X10D.Tests/src/Core/IntrinsicTests.cs @@ -7,7 +7,7 @@ using X10D.Core; namespace X10D.Tests.Core; [TestFixture] -public class IntrinsicTests +internal class IntrinsicTests { [Test] public void CorrectBoolean_ShouldReturnExpectedVector64Result_GivenInputVector() diff --git a/X10D.Tests/src/Core/NullableTests.cs b/X10D.Tests/src/Core/NullableTests.cs index 4626e9c..db4c8ef 100644 --- a/X10D.Tests/src/Core/NullableTests.cs +++ b/X10D.Tests/src/Core/NullableTests.cs @@ -4,7 +4,7 @@ using X10D.Core; namespace X10D.Tests.Core; [TestFixture] -public class NullableTests +internal class NullableTests { [Test] public void TryGetValue_ShouldBeTrue_GivenValue() diff --git a/X10D.Tests/src/Core/RandomTests.cs b/X10D.Tests/src/Core/RandomTests.cs index 1e7b7bd..5e1022d 100644 --- a/X10D.Tests/src/Core/RandomTests.cs +++ b/X10D.Tests/src/Core/RandomTests.cs @@ -5,7 +5,7 @@ using X10D.Core; namespace X10D.Tests.Core; [TestFixture] -public class RandomTests +internal class RandomTests { [Test] public void NextBoolean_ShouldBeFalse_GivenSeed1234() diff --git a/X10D.Tests/src/Core/SpanTest.cs b/X10D.Tests/src/Core/SpanTest.cs index 6ef4f74..85fb460 100644 --- a/X10D.Tests/src/Core/SpanTest.cs +++ b/X10D.Tests/src/Core/SpanTest.cs @@ -8,7 +8,7 @@ using X10D.Core; namespace X10D.Tests.Core; [TestFixture] -public class SpanTest +internal class SpanTest { [Test] public void Contains_ShouldReturnFalse_GivenReadOnlySpanWithNoMatchingElements_UsingByteEnum() diff --git a/X10D.Tests/src/Drawing/CircleFTests.cs b/X10D.Tests/src/Drawing/CircleFTests.cs index fad7e5c..06a4de8 100644 --- a/X10D.Tests/src/Drawing/CircleFTests.cs +++ b/X10D.Tests/src/Drawing/CircleFTests.cs @@ -5,7 +5,7 @@ using X10D.Drawing; namespace X10D.Tests.Drawing; [TestFixture] -public class CircleFTests +internal class CircleFTests { [Test] public void Area_ShouldBePiRadiusRadius_GivenUnitCircle() diff --git a/X10D.Tests/src/Drawing/CircleTests.cs b/X10D.Tests/src/Drawing/CircleTests.cs index 8ab4d18..e03fb0c 100644 --- a/X10D.Tests/src/Drawing/CircleTests.cs +++ b/X10D.Tests/src/Drawing/CircleTests.cs @@ -4,7 +4,7 @@ using X10D.Drawing; namespace X10D.Tests.Drawing; [TestFixture] -public class CircleTests +internal class CircleTests { [Test] public void Area_ShouldBePiRadiusRadius_GivenUnitCircle() diff --git a/X10D.Tests/src/Drawing/ColorTests.cs b/X10D.Tests/src/Drawing/ColorTests.cs index ad29fb3..7868484 100644 --- a/X10D.Tests/src/Drawing/ColorTests.cs +++ b/X10D.Tests/src/Drawing/ColorTests.cs @@ -5,7 +5,7 @@ using X10D.Drawing; namespace X10D.Tests.Drawing; [TestFixture] -public class ColorTests +internal class ColorTests { private static readonly Color Black = Color.FromArgb(0, 0, 0); private static readonly Color White = Color.FromArgb(255, 255, 255); diff --git a/X10D.Tests/src/Drawing/CuboidTests.cs b/X10D.Tests/src/Drawing/CuboidTests.cs index f2eafdc..37d006f 100644 --- a/X10D.Tests/src/Drawing/CuboidTests.cs +++ b/X10D.Tests/src/Drawing/CuboidTests.cs @@ -5,7 +5,7 @@ using X10D.Drawing; namespace X10D.Tests.Drawing; [TestFixture] -public class CuboidTests +internal class CuboidTests { [Test] public void Corners_ShouldBeCorrect_GivenCubeOfSize1() diff --git a/X10D.Tests/src/Drawing/EllipseFTests.cs b/X10D.Tests/src/Drawing/EllipseFTests.cs index 7ca40aa..aecdcdc 100644 --- a/X10D.Tests/src/Drawing/EllipseFTests.cs +++ b/X10D.Tests/src/Drawing/EllipseFTests.cs @@ -6,7 +6,7 @@ using X10D.Drawing; namespace X10D.Tests.Drawing; [TestFixture] -public class EllipseFTests +internal class EllipseFTests { [Test] public void Area_ShouldBePiRadiusRadius_GivenUnitEllipse() diff --git a/X10D.Tests/src/Drawing/EllipseTests.cs b/X10D.Tests/src/Drawing/EllipseTests.cs index 529f1c6..6f938cd 100644 --- a/X10D.Tests/src/Drawing/EllipseTests.cs +++ b/X10D.Tests/src/Drawing/EllipseTests.cs @@ -5,7 +5,7 @@ using X10D.Drawing; namespace X10D.Tests.Drawing; [TestFixture] -public class EllipseTests +internal class EllipseTests { [Test] public void Area_ShouldBePiRadiusRadius_GivenUnitEllipse() diff --git a/X10D.Tests/src/Drawing/Line3DTests.cs b/X10D.Tests/src/Drawing/Line3DTests.cs index f7db299..1182a5b 100644 --- a/X10D.Tests/src/Drawing/Line3DTests.cs +++ b/X10D.Tests/src/Drawing/Line3DTests.cs @@ -6,7 +6,7 @@ using X10D.Drawing; namespace X10D.Tests.Drawing; [TestFixture] -public class Line3DTests +internal class Line3DTests { [Test] public void CompareTo_ShouldBeNegativeOne_GivenEmptyAndOne() diff --git a/X10D.Tests/src/Drawing/LineFTests.cs b/X10D.Tests/src/Drawing/LineFTests.cs index 2c53cd4..412fff2 100644 --- a/X10D.Tests/src/Drawing/LineFTests.cs +++ b/X10D.Tests/src/Drawing/LineFTests.cs @@ -5,7 +5,7 @@ using X10D.Drawing; namespace X10D.Tests.Drawing; [TestFixture] -public class LineFTests +internal class LineFTests { [Test] public void CompareTo_ShouldBeNegativeOne_GivenEmptyAndOne() diff --git a/X10D.Tests/src/Drawing/LineTests.cs b/X10D.Tests/src/Drawing/LineTests.cs index dfca225..24a985d 100644 --- a/X10D.Tests/src/Drawing/LineTests.cs +++ b/X10D.Tests/src/Drawing/LineTests.cs @@ -4,7 +4,7 @@ using X10D.Drawing; namespace X10D.Tests.Drawing; [TestFixture] -public class LineTests +internal class LineTests { [Test] public void CompareTo_ShouldBeNegativeOne_GivenEmptyAndOne() diff --git a/X10D.Tests/src/Drawing/PointFTests.cs b/X10D.Tests/src/Drawing/PointFTests.cs index 9bcd0c9..aace160 100644 --- a/X10D.Tests/src/Drawing/PointFTests.cs +++ b/X10D.Tests/src/Drawing/PointFTests.cs @@ -8,7 +8,7 @@ using X10D.Drawing; namespace X10D.Tests.Drawing; [TestFixture] -public class PointFTests +internal class PointFTests { [Test] public void IsOnLine_ShouldReturnTrue_GivenPointOnLine() diff --git a/X10D.Tests/src/Drawing/PointTests.cs b/X10D.Tests/src/Drawing/PointTests.cs index 818a3f5..ae07657 100644 --- a/X10D.Tests/src/Drawing/PointTests.cs +++ b/X10D.Tests/src/Drawing/PointTests.cs @@ -5,7 +5,7 @@ using X10D.Drawing; namespace X10D.Tests.Drawing; [TestFixture] -public class PointTests +internal class PointTests { [Test] public void IsOnLine_ShouldReturnTrue_GivenPointOnLine() diff --git a/X10D.Tests/src/Drawing/PolygonFTests.cs b/X10D.Tests/src/Drawing/PolygonFTests.cs index 9b7e626..f6a09de 100644 --- a/X10D.Tests/src/Drawing/PolygonFTests.cs +++ b/X10D.Tests/src/Drawing/PolygonFTests.cs @@ -6,7 +6,7 @@ using X10D.Drawing; namespace X10D.Tests.Drawing; [TestFixture] -public class PolygonFTests +internal class PolygonFTests { [Test] public void AddVertices_ShouldAddVertices() diff --git a/X10D.Tests/src/Drawing/PolygonTests.cs b/X10D.Tests/src/Drawing/PolygonTests.cs index 40e9da4..4d73cd8 100644 --- a/X10D.Tests/src/Drawing/PolygonTests.cs +++ b/X10D.Tests/src/Drawing/PolygonTests.cs @@ -5,7 +5,7 @@ using X10D.Drawing; namespace X10D.Tests.Drawing; [TestFixture] -public class PolygonTests +internal class PolygonTests { [Test] public void AddVertices_ShouldAddVertices() diff --git a/X10D.Tests/src/Drawing/PolyhedronTests.cs b/X10D.Tests/src/Drawing/PolyhedronTests.cs index 608e7e1..8e85423 100644 --- a/X10D.Tests/src/Drawing/PolyhedronTests.cs +++ b/X10D.Tests/src/Drawing/PolyhedronTests.cs @@ -5,7 +5,7 @@ using X10D.Drawing; namespace X10D.Tests.Drawing; [TestFixture] -public class PolyhedronTests +internal class PolyhedronTests { [Test] public void AddVertices_ShouldAddVertices() diff --git a/X10D.Tests/src/Drawing/RandomTests.cs b/X10D.Tests/src/Drawing/RandomTests.cs index cad12e4..349ca33 100644 --- a/X10D.Tests/src/Drawing/RandomTests.cs +++ b/X10D.Tests/src/Drawing/RandomTests.cs @@ -5,7 +5,7 @@ using X10D.Drawing; namespace X10D.Tests.Drawing; [TestFixture] -public class RandomTests +internal class RandomTests { [Test] public void NextColorArgb_ShouldReturn331515e5_GivenSeed1234() diff --git a/X10D.Tests/src/Drawing/SizeTests.cs b/X10D.Tests/src/Drawing/SizeTests.cs index e72bbbb..47a2a42 100644 --- a/X10D.Tests/src/Drawing/SizeTests.cs +++ b/X10D.Tests/src/Drawing/SizeTests.cs @@ -5,7 +5,7 @@ using X10D.Drawing; namespace X10D.Tests.Drawing; [TestFixture] -public class SizeTests +internal class SizeTests { [Test] public void ToPoint_ShouldReturnPoint_WithEquivalentMembers() diff --git a/X10D.Tests/src/Drawing/SphereTests.cs b/X10D.Tests/src/Drawing/SphereTests.cs index 2a61a8b..dcbf8ce 100644 --- a/X10D.Tests/src/Drawing/SphereTests.cs +++ b/X10D.Tests/src/Drawing/SphereTests.cs @@ -4,7 +4,7 @@ using X10D.Drawing; namespace X10D.Tests.Drawing; [TestFixture] -public class SphereTests +internal class SphereTests { [Test] public void Circumference_ShouldBe2PiRadius_GivenUnitCircle() diff --git a/X10D.Tests/src/Hosting/ServiceCollectionTests.cs b/X10D.Tests/src/Hosting/ServiceCollectionTests.cs index 63a3db6..0691914 100644 --- a/X10D.Tests/src/Hosting/ServiceCollectionTests.cs +++ b/X10D.Tests/src/Hosting/ServiceCollectionTests.cs @@ -6,7 +6,7 @@ using X10D.Hosting.DependencyInjection; namespace X10D.Tests.Hosting; [TestFixture] -public class ServiceCollectionTests +internal class ServiceCollectionTests { [Test] public void AddHostedSingleton_ShouldRegisterServiceAsSingletonAndAsHostedService() diff --git a/X10D.Tests/src/IO/BooleanTests.cs b/X10D.Tests/src/IO/BooleanTests.cs index 86ebdd9..2994e03 100644 --- a/X10D.Tests/src/IO/BooleanTests.cs +++ b/X10D.Tests/src/IO/BooleanTests.cs @@ -4,7 +4,7 @@ using X10D.IO; namespace X10D.Tests.IO; [TestFixture] -public class BooleanTests +internal class BooleanTests { [Test] public void GetBytes_ReturnsArrayContaining1() diff --git a/X10D.Tests/src/IO/ByteTests.cs b/X10D.Tests/src/IO/ByteTests.cs index 4c13411..433cc09 100644 --- a/X10D.Tests/src/IO/ByteTests.cs +++ b/X10D.Tests/src/IO/ByteTests.cs @@ -4,7 +4,7 @@ using X10D.IO; namespace X10D.Tests.IO; [TestFixture] -public class ByteTests +internal class ByteTests { [Test] public void GetBytes_ReturnsArrayContainingItself() diff --git a/X10D.Tests/src/IO/DirectoryInfoTests.cs b/X10D.Tests/src/IO/DirectoryInfoTests.cs index 62df128..925902a 100644 --- a/X10D.Tests/src/IO/DirectoryInfoTests.cs +++ b/X10D.Tests/src/IO/DirectoryInfoTests.cs @@ -4,7 +4,7 @@ using X10D.IO; namespace X10D.Tests.IO; [TestFixture] -public class DirectoryInfoTests +internal class DirectoryInfoTests { [Test] public void Clear_ShouldClear_GivenValidDirectory() diff --git a/X10D.Tests/src/IO/DoubleTests.cs b/X10D.Tests/src/IO/DoubleTests.cs index c327e9f..f58e26c 100644 --- a/X10D.Tests/src/IO/DoubleTests.cs +++ b/X10D.Tests/src/IO/DoubleTests.cs @@ -4,7 +4,7 @@ using X10D.IO; namespace X10D.Tests.IO; [TestFixture] -public class DoubleTests +internal class DoubleTests { [Test] public void GetBytes_ReturnsCorrectValue() diff --git a/X10D.Tests/src/IO/FileInfoTests.cs b/X10D.Tests/src/IO/FileInfoTests.cs index b182b94..319e864 100644 --- a/X10D.Tests/src/IO/FileInfoTests.cs +++ b/X10D.Tests/src/IO/FileInfoTests.cs @@ -5,7 +5,7 @@ using X10D.IO; namespace X10D.Tests.IO; [TestFixture] -public class FileInfoTests +internal class FileInfoTests { [Test] public void GetHashSha1ShouldBeCorrect() diff --git a/X10D.Tests/src/IO/Int16Tests.cs b/X10D.Tests/src/IO/Int16Tests.cs index ae4dcbe..11d6bb1 100644 --- a/X10D.Tests/src/IO/Int16Tests.cs +++ b/X10D.Tests/src/IO/Int16Tests.cs @@ -4,7 +4,7 @@ using X10D.IO; namespace X10D.Tests.IO; [TestFixture] -public class Int16Tests +internal class Int16Tests { [Test] public void GetBytes_ReturnsCorrectValue() diff --git a/X10D.Tests/src/IO/Int32Tests.cs b/X10D.Tests/src/IO/Int32Tests.cs index d69b2be..c123980 100644 --- a/X10D.Tests/src/IO/Int32Tests.cs +++ b/X10D.Tests/src/IO/Int32Tests.cs @@ -4,7 +4,7 @@ using X10D.IO; namespace X10D.Tests.IO; [TestFixture] -public class Int32Tests +internal class Int32Tests { [Test] public void GetBytes_ReturnsCorrectValue() diff --git a/X10D.Tests/src/IO/Int64Tests.cs b/X10D.Tests/src/IO/Int64Tests.cs index ccd3673..6183d13 100644 --- a/X10D.Tests/src/IO/Int64Tests.cs +++ b/X10D.Tests/src/IO/Int64Tests.cs @@ -4,7 +4,7 @@ using X10D.IO; namespace X10D.Tests.IO; [TestFixture] -public class Int64Tests +internal class Int64Tests { [Test] public void GetBytes_ReturnsCorrectValue() diff --git a/X10D.Tests/src/IO/ListOfByteTests.cs b/X10D.Tests/src/IO/ListOfByteTests.cs index 17bd66d..998344d 100644 --- a/X10D.Tests/src/IO/ListOfByteTests.cs +++ b/X10D.Tests/src/IO/ListOfByteTests.cs @@ -5,7 +5,7 @@ using X10D.IO; namespace X10D.Tests.IO; [TestFixture] -public class ListOfByteTests +internal class ListOfByteTests { [Test] public void AsString_ShouldReturnBytes_GivenBytes() diff --git a/X10D.Tests/src/IO/SByteTests.cs b/X10D.Tests/src/IO/SByteTests.cs index 23143ad..c9486e2 100644 --- a/X10D.Tests/src/IO/SByteTests.cs +++ b/X10D.Tests/src/IO/SByteTests.cs @@ -4,8 +4,7 @@ using X10D.IO; namespace X10D.Tests.IO; [TestFixture] -[CLSCompliant(false)] -public class SByteTests +internal class SByteTests { [Test] public void GetBytes_ReturnsArrayContainingItself() diff --git a/X10D.Tests/src/IO/SingleTests.cs b/X10D.Tests/src/IO/SingleTests.cs index b0b1bf3..5f753c4 100644 --- a/X10D.Tests/src/IO/SingleTests.cs +++ b/X10D.Tests/src/IO/SingleTests.cs @@ -4,7 +4,7 @@ using X10D.IO; namespace X10D.Tests.IO; [TestFixture] -public class SingleTests +internal class SingleTests { [Test] public void GetBytes_ReturnsCorrectValue() diff --git a/X10D.Tests/src/IO/StreamTests.ReadDecimal.cs b/X10D.Tests/src/IO/StreamTests.ReadDecimal.cs index 3209443..7f61b76 100644 --- a/X10D.Tests/src/IO/StreamTests.ReadDecimal.cs +++ b/X10D.Tests/src/IO/StreamTests.ReadDecimal.cs @@ -3,7 +3,7 @@ using X10D.IO; namespace X10D.Tests.IO; -public partial class StreamTests +internal partial class StreamTests { [Test] public void ReadDecimal_ShouldThrowArgumentException_GivenNonReadableStream() diff --git a/X10D.Tests/src/IO/StreamTests.ReadDouble.cs b/X10D.Tests/src/IO/StreamTests.ReadDouble.cs index 6084984..b400ac1 100644 --- a/X10D.Tests/src/IO/StreamTests.ReadDouble.cs +++ b/X10D.Tests/src/IO/StreamTests.ReadDouble.cs @@ -3,7 +3,7 @@ using X10D.IO; namespace X10D.Tests.IO; -public partial class StreamTests +internal partial class StreamTests { [Test] public void ReadDouble_ShouldThrowArgumentException_GivenNonReadableStream() diff --git a/X10D.Tests/src/IO/StreamTests.ReadInt16.cs b/X10D.Tests/src/IO/StreamTests.ReadInt16.cs index bdb045c..950f368 100644 --- a/X10D.Tests/src/IO/StreamTests.ReadInt16.cs +++ b/X10D.Tests/src/IO/StreamTests.ReadInt16.cs @@ -3,7 +3,7 @@ using X10D.IO; namespace X10D.Tests.IO; -public partial class StreamTests +internal partial class StreamTests { [Test] public void ReadInt16_ShouldThrowArgumentException_GivenNonReadableStream() diff --git a/X10D.Tests/src/IO/StreamTests.ReadInt32.cs b/X10D.Tests/src/IO/StreamTests.ReadInt32.cs index 64f4c75..8b45594 100644 --- a/X10D.Tests/src/IO/StreamTests.ReadInt32.cs +++ b/X10D.Tests/src/IO/StreamTests.ReadInt32.cs @@ -3,7 +3,7 @@ using X10D.IO; namespace X10D.Tests.IO; -public partial class StreamTests +internal partial class StreamTests { [Test] public void ReadInt32_ShouldThrowArgumentException_GivenNonReadableStream() diff --git a/X10D.Tests/src/IO/StreamTests.ReadInt64.cs b/X10D.Tests/src/IO/StreamTests.ReadInt64.cs index d9f938e..d094a56 100644 --- a/X10D.Tests/src/IO/StreamTests.ReadInt64.cs +++ b/X10D.Tests/src/IO/StreamTests.ReadInt64.cs @@ -3,7 +3,7 @@ using X10D.IO; namespace X10D.Tests.IO; -public partial class StreamTests +internal partial class StreamTests { [Test] public void ReadInt64_ShouldThrowArgumentException_GivenNonReadableStream() diff --git a/X10D.Tests/src/IO/StreamTests.ReadSingle.cs b/X10D.Tests/src/IO/StreamTests.ReadSingle.cs index 2dc2292..7d5a396 100644 --- a/X10D.Tests/src/IO/StreamTests.ReadSingle.cs +++ b/X10D.Tests/src/IO/StreamTests.ReadSingle.cs @@ -3,7 +3,7 @@ using X10D.IO; namespace X10D.Tests.IO; -public partial class StreamTests +internal partial class StreamTests { [Test] public void ReadSingle_ShouldThrowArgumentException_GivenNonReadableStream() diff --git a/X10D.Tests/src/IO/StreamTests.ReadUInt16.cs b/X10D.Tests/src/IO/StreamTests.ReadUInt16.cs index 23508dc..cd8d726 100644 --- a/X10D.Tests/src/IO/StreamTests.ReadUInt16.cs +++ b/X10D.Tests/src/IO/StreamTests.ReadUInt16.cs @@ -3,11 +3,10 @@ using X10D.IO; namespace X10D.Tests.IO; -public partial class StreamTests +internal partial class StreamTests { [Test] - [CLSCompliant(false)] - public void ReadUInt16_ShouldThrowArgumentException_GivenNonReadableStream() + public void ReadUInt16_ShouldThrowArgumentException_GivenNonReadableStream() { Stream stream = new DummyStream(); Assert.Throws(() => stream.ReadUInt16()); @@ -16,8 +15,7 @@ public partial class StreamTests } [Test] - [CLSCompliant(false)] - public void ReadUInt16_ShouldThrowArgumentNullException_GivenNullStream() + public void ReadUInt16_ShouldThrowArgumentNullException_GivenNullStream() { Stream stream = null!; Assert.Throws(() => stream.ReadUInt16()); @@ -26,8 +24,7 @@ public partial class StreamTests } [Test] - [CLSCompliant(false)] - public void ReadUInt16_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() + public void ReadUInt16_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() { // we don't need to enclose this stream in a using declaration, since disposing a // null stream is meaningless. NullStream.Dispose actually does nothing, anyway. @@ -39,8 +36,7 @@ public partial class StreamTests } [Test] - [CLSCompliant(false)] - public void ReadUInt16_ShouldReadBigEndian_GivenBigEndian() + public void ReadUInt16_ShouldReadBigEndian_GivenBigEndian() { using var stream = new MemoryStream(); ReadOnlySpan bytes = stackalloc byte[] {0x01, 0xA4}; @@ -55,8 +51,7 @@ public partial class StreamTests } [Test] - [CLSCompliant(false)] - public void ReadUInt16_ShouldReadLittleEndian_GivenLittleEndian() + public void ReadUInt16_ShouldReadLittleEndian_GivenLittleEndian() { using var stream = new MemoryStream(); ReadOnlySpan bytes = stackalloc byte[] {0xA4, 0x01}; diff --git a/X10D.Tests/src/IO/StreamTests.ReadUInt32.cs b/X10D.Tests/src/IO/StreamTests.ReadUInt32.cs index 8bd57a3..cc5c67d 100644 --- a/X10D.Tests/src/IO/StreamTests.ReadUInt32.cs +++ b/X10D.Tests/src/IO/StreamTests.ReadUInt32.cs @@ -3,11 +3,10 @@ using X10D.IO; namespace X10D.Tests.IO; -public partial class StreamTests +internal partial class StreamTests { [Test] - [CLSCompliant(false)] - public void ReadUInt32_ShouldThrowArgumentException_GivenNonReadableStream() + public void ReadUInt32_ShouldThrowArgumentException_GivenNonReadableStream() { Stream stream = new DummyStream(); Assert.Throws(() => stream.ReadUInt32()); @@ -16,8 +15,7 @@ public partial class StreamTests } [Test] - [CLSCompliant(false)] - public void ReadUInt32_ShouldThrowArgumentNullException_GivenNullStream() + public void ReadUInt32_ShouldThrowArgumentNullException_GivenNullStream() { Stream stream = null!; Assert.Throws(() => stream.ReadUInt32()); @@ -26,8 +24,7 @@ public partial class StreamTests } [Test] - [CLSCompliant(false)] - public void ReadUInt32_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() + public void ReadUInt32_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() { // we don't need to enclose this stream in a using declaration, since disposing a // null stream is meaningless. NullStream.Dispose actually does nothing, anyway. @@ -39,8 +36,7 @@ public partial class StreamTests } [Test] - [CLSCompliant(false)] - public void ReadUInt32_ShouldReadBigEndian_GivenBigEndian() + public void ReadUInt32_ShouldReadBigEndian_GivenBigEndian() { using var stream = new MemoryStream(); ReadOnlySpan bytes = stackalloc byte[] {0x00, 0x00, 0x01, 0xA4}; @@ -55,8 +51,7 @@ public partial class StreamTests } [Test] - [CLSCompliant(false)] - public void ReadUInt32_ShouldReadLittleEndian_GivenLittleEndian() + public void ReadUInt32_ShouldReadLittleEndian_GivenLittleEndian() { using var stream = new MemoryStream(); ReadOnlySpan bytes = stackalloc byte[] {0xA4, 0x01, 0x00, 0x00}; diff --git a/X10D.Tests/src/IO/StreamTests.ReadUInt64.cs b/X10D.Tests/src/IO/StreamTests.ReadUInt64.cs index f315b47..0d916a7 100644 --- a/X10D.Tests/src/IO/StreamTests.ReadUInt64.cs +++ b/X10D.Tests/src/IO/StreamTests.ReadUInt64.cs @@ -3,11 +3,10 @@ using X10D.IO; namespace X10D.Tests.IO; -public partial class StreamTests +internal partial class StreamTests { [Test] - [CLSCompliant(false)] - public void ReadUInt64_ShouldThrowArgumentException_GivenNonReadableStream() + public void ReadUInt64_ShouldThrowArgumentException_GivenNonReadableStream() { Stream stream = new DummyStream(); Assert.Throws(() => stream.ReadUInt64()); @@ -16,8 +15,7 @@ public partial class StreamTests } [Test] - [CLSCompliant(false)] - public void ReadUInt64_ShouldThrowArgumentNullException_GivenNullStream() + public void ReadUInt64_ShouldThrowArgumentNullException_GivenNullStream() { Stream stream = null!; Assert.Throws(() => stream.ReadUInt64()); @@ -26,8 +24,7 @@ public partial class StreamTests } [Test] - [CLSCompliant(false)] - public void ReadUInt64_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() + public void ReadUInt64_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() { // we don't need to enclose this stream in a using declaration, since disposing a // null stream is meaningless. NullStream.Dispose actually does nothing, anyway. @@ -39,8 +36,7 @@ public partial class StreamTests } [Test] - [CLSCompliant(false)] - public void ReadUInt64_ShouldReadBigEndian_GivenBigEndian() + public void ReadUInt64_ShouldReadBigEndian_GivenBigEndian() { using var stream = new MemoryStream(); ReadOnlySpan bytes = stackalloc byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xA4}; @@ -55,8 +51,7 @@ public partial class StreamTests } [Test] - [CLSCompliant(false)] - public void ReadUInt64_ShouldWriteLittleEndian_GivenLittleEndian() + public void ReadUInt64_ShouldWriteLittleEndian_GivenLittleEndian() { using var stream = new MemoryStream(); ReadOnlySpan bytes = stackalloc byte[] {0xA4, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; diff --git a/X10D.Tests/src/IO/StreamTests.WriteDecimal.cs b/X10D.Tests/src/IO/StreamTests.WriteDecimal.cs index e34a816..3aaa113 100644 --- a/X10D.Tests/src/IO/StreamTests.WriteDecimal.cs +++ b/X10D.Tests/src/IO/StreamTests.WriteDecimal.cs @@ -4,7 +4,7 @@ using X10D.IO; namespace X10D.Tests.IO; -public partial class StreamTests +internal partial class StreamTests { [Test] public void WriteDecimal_ShouldThrowArgumentException_GivenNonWriteableStream() diff --git a/X10D.Tests/src/IO/StreamTests.WriteDouble.cs b/X10D.Tests/src/IO/StreamTests.WriteDouble.cs index b1b43e1..e933858 100644 --- a/X10D.Tests/src/IO/StreamTests.WriteDouble.cs +++ b/X10D.Tests/src/IO/StreamTests.WriteDouble.cs @@ -3,7 +3,7 @@ using X10D.IO; namespace X10D.Tests.IO; -public partial class StreamTests +internal partial class StreamTests { [Test] public void WriteDouble_ShouldThrowArgumentException_GivenNonWriteableStream() diff --git a/X10D.Tests/src/IO/StreamTests.WriteInt16.cs b/X10D.Tests/src/IO/StreamTests.WriteInt16.cs index ce0bc8d..cc17549 100644 --- a/X10D.Tests/src/IO/StreamTests.WriteInt16.cs +++ b/X10D.Tests/src/IO/StreamTests.WriteInt16.cs @@ -3,7 +3,7 @@ using X10D.IO; namespace X10D.Tests.IO; -public partial class StreamTests +internal partial class StreamTests { [Test] public void WriteInt16_ShouldThrowArgumentException_GivenNonWriteableStream() diff --git a/X10D.Tests/src/IO/StreamTests.WriteInt32.cs b/X10D.Tests/src/IO/StreamTests.WriteInt32.cs index bb8c982..95f748e 100644 --- a/X10D.Tests/src/IO/StreamTests.WriteInt32.cs +++ b/X10D.Tests/src/IO/StreamTests.WriteInt32.cs @@ -3,7 +3,7 @@ using X10D.IO; namespace X10D.Tests.IO; -public partial class StreamTests +internal partial class StreamTests { [Test] public void WriteInt32_ShouldThrowArgumentException_GivenNonWriteableStream() diff --git a/X10D.Tests/src/IO/StreamTests.WriteInt64.cs b/X10D.Tests/src/IO/StreamTests.WriteInt64.cs index e0fda01..adb8ce2 100644 --- a/X10D.Tests/src/IO/StreamTests.WriteInt64.cs +++ b/X10D.Tests/src/IO/StreamTests.WriteInt64.cs @@ -3,7 +3,7 @@ using X10D.IO; namespace X10D.Tests.IO; -public partial class StreamTests +internal partial class StreamTests { [Test] public void WriteInt64_ShouldThrowArgumentException_GivenNonWriteableStream() diff --git a/X10D.Tests/src/IO/StreamTests.WriteSingle.cs b/X10D.Tests/src/IO/StreamTests.WriteSingle.cs index 69d491b..4a7376e 100644 --- a/X10D.Tests/src/IO/StreamTests.WriteSingle.cs +++ b/X10D.Tests/src/IO/StreamTests.WriteSingle.cs @@ -3,7 +3,7 @@ using X10D.IO; namespace X10D.Tests.IO; -public partial class StreamTests +internal partial class StreamTests { [Test] public void WriteSingle_ShouldThrowArgumentException_GivenNonWriteableStream() diff --git a/X10D.Tests/src/IO/StreamTests.WriteUInt16.cs b/X10D.Tests/src/IO/StreamTests.WriteUInt16.cs index 9747ca8..89a620f 100644 --- a/X10D.Tests/src/IO/StreamTests.WriteUInt16.cs +++ b/X10D.Tests/src/IO/StreamTests.WriteUInt16.cs @@ -3,11 +3,10 @@ using X10D.IO; namespace X10D.Tests.IO; -public partial class StreamTests +internal partial class StreamTests { [Test] - [CLSCompliant(false)] - public void WriteUInt16_ShouldThrowArgumentException_GivenNonWriteableStream() + public void WriteUInt16_ShouldThrowArgumentException_GivenNonWriteableStream() { Stream stream = new DummyStream(); Assert.Throws(() => stream.Write((ushort)420, Endianness.LittleEndian)); @@ -15,8 +14,7 @@ public partial class StreamTests } [Test] - [CLSCompliant(false)] - public void WriteUInt16_ShouldThrowArgumentNullException_GivenNullStream() + public void WriteUInt16_ShouldThrowArgumentNullException_GivenNullStream() { Stream stream = null!; Assert.Throws(() => stream.Write((ushort)420, Endianness.LittleEndian)); @@ -24,8 +22,7 @@ public partial class StreamTests } [Test] - [CLSCompliant(false)] - public void WriteUInt16_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() + public void WriteUInt16_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() { // we don't need to enclose this stream in a using declaration, since disposing a // null stream is meaningless. NullStream.Dispose actually does nothing, anyway. @@ -38,8 +35,7 @@ public partial class StreamTests } [Test] - [CLSCompliant(false)] - public void WriteUInt16_ShouldWriteBigEndian_GivenBigEndian() + public void WriteUInt16_ShouldWriteBigEndian_GivenBigEndian() { using var stream = new MemoryStream(); stream.Write((ushort)420, Endianness.BigEndian); @@ -55,8 +51,7 @@ public partial class StreamTests } [Test] - [CLSCompliant(false)] - public void WriteUInt16_ShouldWriteLittleEndian_GivenLittleEndian() + public void WriteUInt16_ShouldWriteLittleEndian_GivenLittleEndian() { using var stream = new MemoryStream(); stream.Write((ushort)420, Endianness.LittleEndian); diff --git a/X10D.Tests/src/IO/StreamTests.WriteUInt32.cs b/X10D.Tests/src/IO/StreamTests.WriteUInt32.cs index 41d77a9..a9c3bb9 100644 --- a/X10D.Tests/src/IO/StreamTests.WriteUInt32.cs +++ b/X10D.Tests/src/IO/StreamTests.WriteUInt32.cs @@ -3,11 +3,10 @@ using X10D.IO; namespace X10D.Tests.IO; -public partial class StreamTests +internal partial class StreamTests { [Test] - [CLSCompliant(false)] - public void WriteUInt32_ShouldThrowArgumentException_GivenNonWriteableStream() + public void WriteUInt32_ShouldThrowArgumentException_GivenNonWriteableStream() { Stream stream = new DummyStream(); Assert.Throws(() => stream.Write(420U, Endianness.LittleEndian)); @@ -15,8 +14,7 @@ public partial class StreamTests } [Test] - [CLSCompliant(false)] - public void WriteUInt32_ShouldThrowArgumentNullException_GivenNullStream() + public void WriteUInt32_ShouldThrowArgumentNullException_GivenNullStream() { Stream stream = null!; Assert.Throws(() => stream.Write(420U, Endianness.LittleEndian)); @@ -24,8 +22,7 @@ public partial class StreamTests } [Test] - [CLSCompliant(false)] - public void WriteUInt32_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() + public void WriteUInt32_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() { // we don't need to enclose this stream in a using declaration, since disposing a // null stream is meaningless. NullStream.Dispose actually does nothing, anyway. @@ -38,8 +35,7 @@ public partial class StreamTests } [Test] - [CLSCompliant(false)] - public void WriteUInt32_ShouldWriteBigEndian_GivenBigEndian() + public void WriteUInt32_ShouldWriteBigEndian_GivenBigEndian() { using var stream = new MemoryStream(); stream.Write(420U, Endianness.BigEndian); @@ -55,8 +51,7 @@ public partial class StreamTests } [Test] - [CLSCompliant(false)] - public void WriteUInt32_ShouldWriteLittleEndian_GivenLittleEndian() + public void WriteUInt32_ShouldWriteLittleEndian_GivenLittleEndian() { using var stream = new MemoryStream(); stream.Write(420U, Endianness.LittleEndian); diff --git a/X10D.Tests/src/IO/StreamTests.WriteUInt64.cs b/X10D.Tests/src/IO/StreamTests.WriteUInt64.cs index 51a44f5..dad8cc4 100644 --- a/X10D.Tests/src/IO/StreamTests.WriteUInt64.cs +++ b/X10D.Tests/src/IO/StreamTests.WriteUInt64.cs @@ -3,11 +3,10 @@ using X10D.IO; namespace X10D.Tests.IO; -public partial class StreamTests +internal partial class StreamTests { [Test] - [CLSCompliant(false)] - public void WriteUInt64_ShouldThrowArgumentException_GivenNonWriteableStream() + public void WriteUInt64_ShouldThrowArgumentException_GivenNonWriteableStream() { Stream stream = new DummyStream(); Assert.Throws(() => stream.Write(420UL, Endianness.LittleEndian)); @@ -15,8 +14,7 @@ public partial class StreamTests } [Test] - [CLSCompliant(false)] - public void WriteUInt64_ShouldThrowArgumentNullException_GivenNullStream() + public void WriteUInt64_ShouldThrowArgumentNullException_GivenNullStream() { Stream stream = null!; Assert.Throws(() => stream.Write(420UL, Endianness.LittleEndian)); @@ -24,8 +22,7 @@ public partial class StreamTests } [Test] - [CLSCompliant(false)] - public void WriteUInt64_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() + public void WriteUInt64_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() { // we don't need to enclose this stream in a using declaration, since disposing a // null stream is meaningless. NullStream.Dispose actually does nothing, anyway. @@ -38,8 +35,7 @@ public partial class StreamTests } [Test] - [CLSCompliant(false)] - public void WriteUInt64_ShouldWriteBigEndian_GivenBigEndian() + public void WriteUInt64_ShouldWriteBigEndian_GivenBigEndian() { using var stream = new MemoryStream(); stream.Write(420UL, Endianness.BigEndian); @@ -55,8 +51,7 @@ public partial class StreamTests } [Test] - [CLSCompliant(false)] - public void WriteUInt64_ShouldWriteLittleEndian_GivenLittleEndian() + public void WriteUInt64_ShouldWriteLittleEndian_GivenLittleEndian() { using var stream = new MemoryStream(); stream.Write(420UL, Endianness.LittleEndian); diff --git a/X10D.Tests/src/IO/StreamTests.cs b/X10D.Tests/src/IO/StreamTests.cs index 01e4684..e240990 100644 --- a/X10D.Tests/src/IO/StreamTests.cs +++ b/X10D.Tests/src/IO/StreamTests.cs @@ -7,7 +7,7 @@ using X10D.IO; namespace X10D.Tests.IO; [TestFixture] -public partial class StreamTests +internal partial class StreamTests { [Test] public void GetHashSha1ShouldBeCorrect() diff --git a/X10D.Tests/src/IO/TextReaderTests.cs b/X10D.Tests/src/IO/TextReaderTests.cs index a2bafbc..a6ff77e 100644 --- a/X10D.Tests/src/IO/TextReaderTests.cs +++ b/X10D.Tests/src/IO/TextReaderTests.cs @@ -5,7 +5,7 @@ using X10D.IO; namespace X10D.Tests.IO; [TestFixture] -public class TextReaderTests +internal class TextReaderTests { [Test] public void EnumerateLines_ShouldYield10Lines_Given10LineString() diff --git a/X10D.Tests/src/IO/TextWriterTests.Double.cs b/X10D.Tests/src/IO/TextWriterTests.Double.cs index 6f6ed7f..0eb9361 100644 --- a/X10D.Tests/src/IO/TextWriterTests.Double.cs +++ b/X10D.Tests/src/IO/TextWriterTests.Double.cs @@ -5,7 +5,7 @@ using X10D.IO; namespace X10D.Tests.IO; -public partial class TextWriterTests +internal partial class TextWriterTests { [Test] public void WriteNoAlloc_ShouldThrowArgumentNullException_GivenDouble_AndNullWriter() diff --git a/X10D.Tests/src/IO/TextWriterTests.Int32.cs b/X10D.Tests/src/IO/TextWriterTests.Int32.cs index 31bed11..46d13b6 100644 --- a/X10D.Tests/src/IO/TextWriterTests.Int32.cs +++ b/X10D.Tests/src/IO/TextWriterTests.Int32.cs @@ -5,7 +5,7 @@ using X10D.IO; namespace X10D.Tests.IO; -public partial class TextWriterTests +internal partial class TextWriterTests { [Test] public void WriteNoAlloc_ShouldThrowArgumentNullException_GivenInt32_AndNullWriter() diff --git a/X10D.Tests/src/IO/TextWriterTests.Int64.cs b/X10D.Tests/src/IO/TextWriterTests.Int64.cs index affd830..f9b10b4 100644 --- a/X10D.Tests/src/IO/TextWriterTests.Int64.cs +++ b/X10D.Tests/src/IO/TextWriterTests.Int64.cs @@ -5,7 +5,7 @@ using X10D.IO; namespace X10D.Tests.IO; -public partial class TextWriterTests +internal partial class TextWriterTests { [Test] public void WriteNoAlloc_ShouldThrowArgumentNullException_GivenInt64_AndNullWriter() diff --git a/X10D.Tests/src/IO/TextWriterTests.Single.cs b/X10D.Tests/src/IO/TextWriterTests.Single.cs index 3ccba4f..35629b3 100644 --- a/X10D.Tests/src/IO/TextWriterTests.Single.cs +++ b/X10D.Tests/src/IO/TextWriterTests.Single.cs @@ -5,7 +5,7 @@ using X10D.IO; namespace X10D.Tests.IO; -public partial class TextWriterTests +internal partial class TextWriterTests { [Test] public void WriteNoAlloc_ShouldThrowArgumentNullException_GivenSingle_AndNullWriter() diff --git a/X10D.Tests/src/IO/TextWriterTests.UInt32.cs b/X10D.Tests/src/IO/TextWriterTests.UInt32.cs index 8aab080..5b35c99 100644 --- a/X10D.Tests/src/IO/TextWriterTests.UInt32.cs +++ b/X10D.Tests/src/IO/TextWriterTests.UInt32.cs @@ -5,7 +5,7 @@ using X10D.IO; namespace X10D.Tests.IO; -public partial class TextWriterTests +internal partial class TextWriterTests { [Test] public void WriteNoAlloc_ShouldThrowArgumentNullException_GivenUInt32_AndNullWriter() diff --git a/X10D.Tests/src/IO/TextWriterTests.UInt64.cs b/X10D.Tests/src/IO/TextWriterTests.UInt64.cs index 57f5425..a7b4551 100644 --- a/X10D.Tests/src/IO/TextWriterTests.UInt64.cs +++ b/X10D.Tests/src/IO/TextWriterTests.UInt64.cs @@ -5,7 +5,7 @@ using X10D.IO; namespace X10D.Tests.IO; -public partial class TextWriterTests +internal partial class TextWriterTests { [Test] public void WriteNoAlloc_ShouldThrowArgumentNullException_GivenUInt64_AndNullWriter() diff --git a/X10D.Tests/src/IO/TextWriterTests.cs b/X10D.Tests/src/IO/TextWriterTests.cs index 750b352..6c0945b 100644 --- a/X10D.Tests/src/IO/TextWriterTests.cs +++ b/X10D.Tests/src/IO/TextWriterTests.cs @@ -1,11 +1,13 @@ using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Text; using NUnit.Framework; namespace X10D.Tests.IO; [TestFixture] -public partial class TextWriterTests +[SuppressMessage("Design", "CA1001:Types that own disposable fields should be disposable")] +internal partial class TextWriterTests { private MemoryStream _stream = null!; private StreamWriter _writer = null!; diff --git a/X10D.Tests/src/IO/UInt16Tests.cs b/X10D.Tests/src/IO/UInt16Tests.cs index 4e0e4bc..6085358 100644 --- a/X10D.Tests/src/IO/UInt16Tests.cs +++ b/X10D.Tests/src/IO/UInt16Tests.cs @@ -4,8 +4,7 @@ using X10D.IO; namespace X10D.Tests.IO; [TestFixture] -[CLSCompliant(false)] -public class UInt16Tests +internal class UInt16Tests { [Test] public void GetBytes_ReturnsCorrectValue() diff --git a/X10D.Tests/src/IO/UInt32Tests.cs b/X10D.Tests/src/IO/UInt32Tests.cs index 910aa50..a04ea4b 100644 --- a/X10D.Tests/src/IO/UInt32Tests.cs +++ b/X10D.Tests/src/IO/UInt32Tests.cs @@ -4,8 +4,7 @@ using X10D.IO; namespace X10D.Tests.IO; [TestFixture] -[CLSCompliant(false)] -public class UInt32Tests +internal class UInt32Tests { [Test] public void GetBytes_ReturnsCorrectValue() diff --git a/X10D.Tests/src/IO/UInt64Tests.cs b/X10D.Tests/src/IO/UInt64Tests.cs index 374444f..af5727d 100644 --- a/X10D.Tests/src/IO/UInt64Tests.cs +++ b/X10D.Tests/src/IO/UInt64Tests.cs @@ -4,8 +4,7 @@ using X10D.IO; namespace X10D.Tests.IO; [TestFixture] -[CLSCompliant(false)] -public class UInt64Tests +internal class UInt64Tests { [Test] public void GetBytes_ReturnsCorrectValue() diff --git a/X10D.Tests/src/Linq/ByteTests.cs b/X10D.Tests/src/Linq/ByteTests.cs index ccaf696..0ece8b6 100644 --- a/X10D.Tests/src/Linq/ByteTests.cs +++ b/X10D.Tests/src/Linq/ByteTests.cs @@ -4,7 +4,7 @@ using X10D.Linq; namespace X10D.Tests.Linq; [TestFixture] -public class ByteTests +internal class ByteTests { [Test] public void ProductShouldBeCorrect() diff --git a/X10D.Tests/src/Linq/DecimalTests.cs b/X10D.Tests/src/Linq/DecimalTests.cs index 93a73b5..db0e66b 100644 --- a/X10D.Tests/src/Linq/DecimalTests.cs +++ b/X10D.Tests/src/Linq/DecimalTests.cs @@ -4,7 +4,7 @@ using X10D.Linq; namespace X10D.Tests.Linq; [TestFixture] -public class DecimalTests +internal class DecimalTests { [Test] public void ProductShouldBeCorrect() diff --git a/X10D.Tests/src/Linq/DoubleTests.cs b/X10D.Tests/src/Linq/DoubleTests.cs index b5234c2..01399ea 100644 --- a/X10D.Tests/src/Linq/DoubleTests.cs +++ b/X10D.Tests/src/Linq/DoubleTests.cs @@ -4,7 +4,7 @@ using X10D.Linq; namespace X10D.Tests.Linq; [TestFixture] -public class DoubleTests +internal class DoubleTests { [Test] public void ProductShouldBeCorrect() diff --git a/X10D.Tests/src/Linq/EnumerableTests.cs b/X10D.Tests/src/Linq/EnumerableTests.cs index 8189443..253690a 100644 --- a/X10D.Tests/src/Linq/EnumerableTests.cs +++ b/X10D.Tests/src/Linq/EnumerableTests.cs @@ -4,7 +4,7 @@ using X10D.Linq; namespace X10D.Tests.Linq; [TestFixture] -public class EnumerableTests +internal class EnumerableTests { [Test] public void Except_ShouldFilterElements_GivenMatchingElements() diff --git a/X10D.Tests/src/Linq/Int16Tests.cs b/X10D.Tests/src/Linq/Int16Tests.cs index 2a8459d..76a6a48 100644 --- a/X10D.Tests/src/Linq/Int16Tests.cs +++ b/X10D.Tests/src/Linq/Int16Tests.cs @@ -4,7 +4,7 @@ using X10D.Linq; namespace X10D.Tests.Linq; [TestFixture] -public class Int16Tests +internal class Int16Tests { [Test] public void ProductShouldBeCorrect() diff --git a/X10D.Tests/src/Linq/Int32Tests.cs b/X10D.Tests/src/Linq/Int32Tests.cs index 93b6f5a..5f8422a 100644 --- a/X10D.Tests/src/Linq/Int32Tests.cs +++ b/X10D.Tests/src/Linq/Int32Tests.cs @@ -4,7 +4,7 @@ using X10D.Linq; namespace X10D.Tests.Linq; [TestFixture] -public class Int32Tests +internal class Int32Tests { [Test] public void ProductShouldBeCorrect() diff --git a/X10D.Tests/src/Linq/Int64Tests.cs b/X10D.Tests/src/Linq/Int64Tests.cs index 61f1932..aad0738 100644 --- a/X10D.Tests/src/Linq/Int64Tests.cs +++ b/X10D.Tests/src/Linq/Int64Tests.cs @@ -4,7 +4,7 @@ using X10D.Linq; namespace X10D.Tests.Linq; [TestFixture] -public class Int64Tests +internal class Int64Tests { [Test] public void ProductShouldBeCorrect() diff --git a/X10D.Tests/src/Linq/ReadOnlySpanTests.cs b/X10D.Tests/src/Linq/ReadOnlySpanTests.cs index 05787b9..da74e71 100644 --- a/X10D.Tests/src/Linq/ReadOnlySpanTests.cs +++ b/X10D.Tests/src/Linq/ReadOnlySpanTests.cs @@ -4,7 +4,7 @@ using X10D.Linq; namespace X10D.Tests.Linq; [TestFixture] -public class ReadOnlySpanTests +internal class ReadOnlySpanTests { [Test] public void AllShouldReturnTrueForEmptySpan() diff --git a/X10D.Tests/src/Linq/SByteTests.cs b/X10D.Tests/src/Linq/SByteTests.cs index 5d5e0b8..a859279 100644 --- a/X10D.Tests/src/Linq/SByteTests.cs +++ b/X10D.Tests/src/Linq/SByteTests.cs @@ -4,8 +4,7 @@ using X10D.Linq; namespace X10D.Tests.Linq; [TestFixture] -[CLSCompliant(false)] -public class SByteTests +internal class SByteTests { [Test] public void ProductShouldBeCorrect() diff --git a/X10D.Tests/src/Linq/SingleTests.cs b/X10D.Tests/src/Linq/SingleTests.cs index 3a1a866..0bac265 100644 --- a/X10D.Tests/src/Linq/SingleTests.cs +++ b/X10D.Tests/src/Linq/SingleTests.cs @@ -4,7 +4,7 @@ using X10D.Linq; namespace X10D.Tests.Linq; [TestFixture] -public class SingleTests +internal class SingleTests { [Test] public void ProductShouldBeCorrect() diff --git a/X10D.Tests/src/Linq/SpanTests.cs b/X10D.Tests/src/Linq/SpanTests.cs index 624a399..05d60f5 100644 --- a/X10D.Tests/src/Linq/SpanTests.cs +++ b/X10D.Tests/src/Linq/SpanTests.cs @@ -4,7 +4,7 @@ using X10D.Linq; namespace X10D.Tests.Linq; [TestFixture] -public class SpanTests +internal class SpanTests { [Test] public void AllShouldReturnTrueForEmptySpan() diff --git a/X10D.Tests/src/Linq/UInt16Tests.cs b/X10D.Tests/src/Linq/UInt16Tests.cs index 2742fc0..8abfc97 100644 --- a/X10D.Tests/src/Linq/UInt16Tests.cs +++ b/X10D.Tests/src/Linq/UInt16Tests.cs @@ -4,8 +4,7 @@ using X10D.Linq; namespace X10D.Tests.Linq; [TestFixture] -[CLSCompliant(false)] -public class UInt16Tests +internal class UInt16Tests { [Test] public void ProductShouldBeCorrect() diff --git a/X10D.Tests/src/Linq/UInt32Tests.cs b/X10D.Tests/src/Linq/UInt32Tests.cs index 2435f17..20d1217 100644 --- a/X10D.Tests/src/Linq/UInt32Tests.cs +++ b/X10D.Tests/src/Linq/UInt32Tests.cs @@ -4,8 +4,7 @@ using X10D.Linq; namespace X10D.Tests.Linq; [TestFixture] -[CLSCompliant(false)] -public class UInt32Tests +internal class UInt32Tests { [Test] public void ProductShouldBeCorrect() diff --git a/X10D.Tests/src/Linq/UInt64Tests.cs b/X10D.Tests/src/Linq/UInt64Tests.cs index bbaa2fc..64710d3 100644 --- a/X10D.Tests/src/Linq/UInt64Tests.cs +++ b/X10D.Tests/src/Linq/UInt64Tests.cs @@ -4,8 +4,7 @@ using X10D.Linq; namespace X10D.Tests.Linq; [TestFixture] -[CLSCompliant(false)] -public class UInt64Tests +internal class UInt64Tests { [Test] public void ProductShouldBeCorrect() diff --git a/X10D.Tests/src/Math/BigIntegerTests.Wrap.cs b/X10D.Tests/src/Math/BigIntegerTests.Wrap.cs index d3fff35..ecff3df 100644 --- a/X10D.Tests/src/Math/BigIntegerTests.Wrap.cs +++ b/X10D.Tests/src/Math/BigIntegerTests.Wrap.cs @@ -4,7 +4,7 @@ using X10D.Math; namespace X10D.Tests.Math; -public partial class BigIntegerTests +internal partial class BigIntegerTests { [TestFixture] public class WrapTests diff --git a/X10D.Tests/src/Math/BigIntegerTests.cs b/X10D.Tests/src/Math/BigIntegerTests.cs index 2151798..80c0cec 100644 --- a/X10D.Tests/src/Math/BigIntegerTests.cs +++ b/X10D.Tests/src/Math/BigIntegerTests.cs @@ -5,7 +5,7 @@ using X10D.Math; namespace X10D.Tests.Math; [TestFixture] -public partial class BigIntegerTests +internal partial class BigIntegerTests { [Test] public void CountDigits_ShouldReturn1_Given0() diff --git a/X10D.Tests/src/Math/ByteTests.Wrap.cs b/X10D.Tests/src/Math/ByteTests.Wrap.cs index d7303e8..91c214f 100644 --- a/X10D.Tests/src/Math/ByteTests.Wrap.cs +++ b/X10D.Tests/src/Math/ByteTests.Wrap.cs @@ -3,7 +3,7 @@ using X10D.Math; namespace X10D.Tests.Math; -public partial class ByteTests +internal partial class ByteTests { [TestFixture] public class WrapTests diff --git a/X10D.Tests/src/Math/ByteTests.cs b/X10D.Tests/src/Math/ByteTests.cs index 3419f3e..0d80790 100644 --- a/X10D.Tests/src/Math/ByteTests.cs +++ b/X10D.Tests/src/Math/ByteTests.cs @@ -4,7 +4,7 @@ using X10D.Math; namespace X10D.Tests.Math; [TestFixture] -public partial class ByteTests +internal partial class ByteTests { [Test] public void CountDigits_ShouldReturn1_Given0() diff --git a/X10D.Tests/src/Math/ComparableTests.cs b/X10D.Tests/src/Math/ComparableTests.cs index 80ee06a..cb90266 100644 --- a/X10D.Tests/src/Math/ComparableTests.cs +++ b/X10D.Tests/src/Math/ComparableTests.cs @@ -4,7 +4,7 @@ using X10D.Math; namespace X10D.Tests.Math; [TestFixture] -public class ComparableTests +internal class ComparableTests { private class ComparableTestClass : IComparable { diff --git a/X10D.Tests/src/Math/DecimalTests.Wrap.cs b/X10D.Tests/src/Math/DecimalTests.Wrap.cs index 8b92e8c..1408043 100644 --- a/X10D.Tests/src/Math/DecimalTests.Wrap.cs +++ b/X10D.Tests/src/Math/DecimalTests.Wrap.cs @@ -3,7 +3,7 @@ using X10D.Math; namespace X10D.Tests.Math; -public partial class DecimalTests +internal partial class DecimalTests { [TestFixture] public class WrapTests diff --git a/X10D.Tests/src/Math/DecimalTests.cs b/X10D.Tests/src/Math/DecimalTests.cs index b93f415..8c4b31e 100644 --- a/X10D.Tests/src/Math/DecimalTests.cs +++ b/X10D.Tests/src/Math/DecimalTests.cs @@ -5,7 +5,7 @@ using X10D.Math; namespace X10D.Tests.Math; [TestFixture] -public partial class DecimalTests +internal partial class DecimalTests { [Test] public void ComplexSqrt_ShouldBeCorrect_GivenReal() diff --git a/X10D.Tests/src/Math/DoubleTests.Wrap.cs b/X10D.Tests/src/Math/DoubleTests.Wrap.cs index b6c15f8..fdc5ada 100644 --- a/X10D.Tests/src/Math/DoubleTests.Wrap.cs +++ b/X10D.Tests/src/Math/DoubleTests.Wrap.cs @@ -3,7 +3,7 @@ using X10D.Math; namespace X10D.Tests.Math; -public partial class DoubleTests +internal partial class DoubleTests { [TestFixture] public class WrapTests diff --git a/X10D.Tests/src/Math/DoubleTests.cs b/X10D.Tests/src/Math/DoubleTests.cs index 07a7bff..3929b24 100644 --- a/X10D.Tests/src/Math/DoubleTests.cs +++ b/X10D.Tests/src/Math/DoubleTests.cs @@ -5,7 +5,7 @@ using X10D.Math; namespace X10D.Tests.Math; [TestFixture] -public partial class DoubleTests +internal partial class DoubleTests { [Test] public void DegreesToRadians_ShouldBeCorrect() diff --git a/X10D.Tests/src/Math/Int16Tests.Wrap.cs b/X10D.Tests/src/Math/Int16Tests.Wrap.cs index bdd290a..b5f20d7 100644 --- a/X10D.Tests/src/Math/Int16Tests.Wrap.cs +++ b/X10D.Tests/src/Math/Int16Tests.Wrap.cs @@ -3,7 +3,7 @@ using X10D.Math; namespace X10D.Tests.Math; -public partial class Int16Tests +internal partial class Int16Tests { [TestFixture] public class WrapTests diff --git a/X10D.Tests/src/Math/Int16Tests.cs b/X10D.Tests/src/Math/Int16Tests.cs index 3823264..5612e4b 100644 --- a/X10D.Tests/src/Math/Int16Tests.cs +++ b/X10D.Tests/src/Math/Int16Tests.cs @@ -4,7 +4,7 @@ using X10D.Math; namespace X10D.Tests.Math; [TestFixture] -public partial class Int16Tests +internal partial class Int16Tests { [Test] public void CountDigits_ShouldReturn1_Given0() diff --git a/X10D.Tests/src/Math/Int32Tests.Wrap.cs b/X10D.Tests/src/Math/Int32Tests.Wrap.cs index 306ac09..754ae48 100644 --- a/X10D.Tests/src/Math/Int32Tests.Wrap.cs +++ b/X10D.Tests/src/Math/Int32Tests.Wrap.cs @@ -3,7 +3,7 @@ using X10D.Math; namespace X10D.Tests.Math; -public partial class Int32Tests +internal partial class Int32Tests { [TestFixture] public class WrapTests diff --git a/X10D.Tests/src/Math/Int32Tests.cs b/X10D.Tests/src/Math/Int32Tests.cs index 7711d3d..0bfbf25 100644 --- a/X10D.Tests/src/Math/Int32Tests.cs +++ b/X10D.Tests/src/Math/Int32Tests.cs @@ -4,7 +4,7 @@ using X10D.Math; namespace X10D.Tests.Math; [TestFixture] -public partial class Int32Tests +internal partial class Int32Tests { [Test] public void CountDigits_ShouldReturn1_Given0() diff --git a/X10D.Tests/src/Math/Int64Tests.Wrap.cs b/X10D.Tests/src/Math/Int64Tests.Wrap.cs index c8985d3..6434295 100644 --- a/X10D.Tests/src/Math/Int64Tests.Wrap.cs +++ b/X10D.Tests/src/Math/Int64Tests.Wrap.cs @@ -3,7 +3,7 @@ using X10D.Math; namespace X10D.Tests.Math; -public partial class Int64Tests +internal partial class Int64Tests { [TestFixture] public class WrapTests diff --git a/X10D.Tests/src/Math/Int64Tests.cs b/X10D.Tests/src/Math/Int64Tests.cs index 557e0b0..bd5f524 100644 --- a/X10D.Tests/src/Math/Int64Tests.cs +++ b/X10D.Tests/src/Math/Int64Tests.cs @@ -4,7 +4,7 @@ using X10D.Math; namespace X10D.Tests.Math; [TestFixture] -public partial class Int64Tests +internal partial class Int64Tests { [Test] public void CountDigits_ShouldReturn1_Given0() diff --git a/X10D.Tests/src/Math/IsPrimeTests.cs b/X10D.Tests/src/Math/IsPrimeTests.cs index 3af4499..4d50e68 100644 --- a/X10D.Tests/src/Math/IsPrimeTests.cs +++ b/X10D.Tests/src/Math/IsPrimeTests.cs @@ -7,7 +7,7 @@ using X10D.Math; namespace X10D.Tests.Math; [TestFixture] -public class IsPrimeTests +internal class IsPrimeTests { private IReadOnlyList _primeNumbers = ArraySegment.Empty; diff --git a/X10D.Tests/src/Math/MathUtilityTests.cs b/X10D.Tests/src/Math/MathUtilityTests.cs index 0989e44..01028a2 100644 --- a/X10D.Tests/src/Math/MathUtilityTests.cs +++ b/X10D.Tests/src/Math/MathUtilityTests.cs @@ -7,7 +7,7 @@ using X10D.Math; namespace X10D.Tests.Math; [TestFixture] -public class MathUtilityTests +internal class MathUtilityTests { [Test] public void Bias_ReturnsCorrectResult_WhenBiasIsLessThanPointFive() diff --git a/X10D.Tests/src/Math/SByteTests.Wrap.cs b/X10D.Tests/src/Math/SByteTests.Wrap.cs index eaecb3c..dd7b9b9 100644 --- a/X10D.Tests/src/Math/SByteTests.Wrap.cs +++ b/X10D.Tests/src/Math/SByteTests.Wrap.cs @@ -3,7 +3,7 @@ using X10D.Math; namespace X10D.Tests.Math; -public partial class SByteTests +internal partial class SByteTests { [TestFixture] public class WrapTests diff --git a/X10D.Tests/src/Math/SByteTests.cs b/X10D.Tests/src/Math/SByteTests.cs index 454e35f..9550cfb 100644 --- a/X10D.Tests/src/Math/SByteTests.cs +++ b/X10D.Tests/src/Math/SByteTests.cs @@ -4,8 +4,7 @@ using X10D.Math; namespace X10D.Tests.Math; [TestFixture] -[CLSCompliant(false)] -public partial class SByteTests +internal partial class SByteTests { [Test] public void CountDigits_ShouldReturn1_Given0() diff --git a/X10D.Tests/src/Math/SingleTests.Wrap.cs b/X10D.Tests/src/Math/SingleTests.Wrap.cs index 9430e9a..596a40a 100644 --- a/X10D.Tests/src/Math/SingleTests.Wrap.cs +++ b/X10D.Tests/src/Math/SingleTests.Wrap.cs @@ -3,7 +3,7 @@ using X10D.Math; namespace X10D.Tests.Math; -public partial class SingleTests +internal partial class SingleTests { [TestFixture] public class WrapTests diff --git a/X10D.Tests/src/Math/SingleTests.cs b/X10D.Tests/src/Math/SingleTests.cs index f13ec65..5e50fe7 100644 --- a/X10D.Tests/src/Math/SingleTests.cs +++ b/X10D.Tests/src/Math/SingleTests.cs @@ -5,7 +5,7 @@ using X10D.Math; namespace X10D.Tests.Math; [TestFixture] -public partial class SingleTests +internal partial class SingleTests { [Test] public void DegreesToRadians_ShouldBeCorrect() diff --git a/X10D.Tests/src/Math/UInt16Tests.Wrap.cs b/X10D.Tests/src/Math/UInt16Tests.Wrap.cs index 6f21662..e5be525 100644 --- a/X10D.Tests/src/Math/UInt16Tests.Wrap.cs +++ b/X10D.Tests/src/Math/UInt16Tests.Wrap.cs @@ -3,7 +3,7 @@ using X10D.Math; namespace X10D.Tests.Math; -public partial class UInt16Tests +internal partial class UInt16Tests { [TestFixture] public class WrapTests diff --git a/X10D.Tests/src/Math/UInt16Tests.cs b/X10D.Tests/src/Math/UInt16Tests.cs index f123de7..c6f38ad 100644 --- a/X10D.Tests/src/Math/UInt16Tests.cs +++ b/X10D.Tests/src/Math/UInt16Tests.cs @@ -4,8 +4,7 @@ using X10D.Math; namespace X10D.Tests.Math; [TestFixture] -[CLSCompliant(false)] -public partial class UInt16Tests +internal partial class UInt16Tests { [Test] public void CountDigits_ShouldReturn1_Given0() diff --git a/X10D.Tests/src/Math/UInt32Tests.Wrap.cs b/X10D.Tests/src/Math/UInt32Tests.Wrap.cs index a46ee45..572f71c 100644 --- a/X10D.Tests/src/Math/UInt32Tests.Wrap.cs +++ b/X10D.Tests/src/Math/UInt32Tests.Wrap.cs @@ -3,7 +3,7 @@ using X10D.Math; namespace X10D.Tests.Math; -public partial class UInt32Tests +internal partial class UInt32Tests { [TestFixture] public class WrapTests diff --git a/X10D.Tests/src/Math/UInt32Tests.cs b/X10D.Tests/src/Math/UInt32Tests.cs index a6c2911..5c161ff 100644 --- a/X10D.Tests/src/Math/UInt32Tests.cs +++ b/X10D.Tests/src/Math/UInt32Tests.cs @@ -4,8 +4,7 @@ using X10D.Math; namespace X10D.Tests.Math; [TestFixture] -[CLSCompliant(false)] -public partial class UInt32Tests +internal partial class UInt32Tests { [Test] public void CountDigits_ShouldReturn1_Given0() diff --git a/X10D.Tests/src/Math/UInt64Tests.Wrap.cs b/X10D.Tests/src/Math/UInt64Tests.Wrap.cs index a99e8ad..7307589 100644 --- a/X10D.Tests/src/Math/UInt64Tests.Wrap.cs +++ b/X10D.Tests/src/Math/UInt64Tests.Wrap.cs @@ -3,7 +3,7 @@ using X10D.Math; namespace X10D.Tests.Math; -public partial class UInt64Tests +internal partial class UInt64Tests { [TestFixture] public class WrapTests diff --git a/X10D.Tests/src/Math/UInt64Tests.cs b/X10D.Tests/src/Math/UInt64Tests.cs index 6d05b4d..909548f 100644 --- a/X10D.Tests/src/Math/UInt64Tests.cs +++ b/X10D.Tests/src/Math/UInt64Tests.cs @@ -4,8 +4,7 @@ using X10D.Math; namespace X10D.Tests.Math; [TestFixture] -[CLSCompliant(false)] -public partial class UInt64Tests +internal partial class UInt64Tests { [Test] public void CountDigits_ShouldReturn1_Given0() diff --git a/X10D.Tests/src/Net/EndPointTests.cs b/X10D.Tests/src/Net/EndPointTests.cs index eb69138..7dca5cf 100644 --- a/X10D.Tests/src/Net/EndPointTests.cs +++ b/X10D.Tests/src/Net/EndPointTests.cs @@ -5,7 +5,7 @@ using X10D.Net; namespace X10D.Tests.Net; [TestFixture] -public class EndPointTests +internal class EndPointTests { [Test] public void GetHost_ShouldBeLocalhost_GivenLocalhostDnsEndPoint() diff --git a/X10D.Tests/src/Net/IPAddressTests.cs b/X10D.Tests/src/Net/IPAddressTests.cs index de0f8eb..ab48f24 100644 --- a/X10D.Tests/src/Net/IPAddressTests.cs +++ b/X10D.Tests/src/Net/IPAddressTests.cs @@ -5,7 +5,7 @@ using X10D.Net; namespace X10D.Tests.Net; [TestFixture] -public class IPAddressTests +internal class IPAddressTests { private IPAddress _ipv4Address = null!; private IPAddress _ipv6Address = null!; diff --git a/X10D.Tests/src/Net/Int16Tests.cs b/X10D.Tests/src/Net/Int16Tests.cs index 4a850c7..310a183 100644 --- a/X10D.Tests/src/Net/Int16Tests.cs +++ b/X10D.Tests/src/Net/Int16Tests.cs @@ -4,7 +4,7 @@ using X10D.Net; namespace X10D.Tests.Net; [TestFixture] -public class Int16Tests +internal class Int16Tests { [Test] public void HostToNetworkOrder_ReturnsCorrectValue() diff --git a/X10D.Tests/src/Net/Int32Tests.cs b/X10D.Tests/src/Net/Int32Tests.cs index 7e876ec..50b8899 100644 --- a/X10D.Tests/src/Net/Int32Tests.cs +++ b/X10D.Tests/src/Net/Int32Tests.cs @@ -4,7 +4,7 @@ using X10D.Net; namespace X10D.Tests.Net; [TestFixture] -public class Int32Tests +internal class Int32Tests { [Test] public void HostToNetworkOrder_ReturnsCorrectValue() diff --git a/X10D.Tests/src/Net/Int64Tests.cs b/X10D.Tests/src/Net/Int64Tests.cs index 2e1bc76..a2150e1 100644 --- a/X10D.Tests/src/Net/Int64Tests.cs +++ b/X10D.Tests/src/Net/Int64Tests.cs @@ -4,7 +4,7 @@ using X10D.Net; namespace X10D.Tests.Net; [TestFixture] -public class Int64Tests +internal class Int64Tests { [Test] public void HostToNetworkOrder_ReturnsCorrectValue() diff --git a/X10D.Tests/src/Numerics/ByteTests.cs b/X10D.Tests/src/Numerics/ByteTests.cs index 6257ea3..4a191b7 100644 --- a/X10D.Tests/src/Numerics/ByteTests.cs +++ b/X10D.Tests/src/Numerics/ByteTests.cs @@ -4,7 +4,7 @@ using X10D.Numerics; namespace X10D.Tests.Numerics; [TestFixture] -public class ByteTests +internal class ByteTests { [Test] public void PopCount_ShouldBe0_Given0() diff --git a/X10D.Tests/src/Numerics/Int16Tests.cs b/X10D.Tests/src/Numerics/Int16Tests.cs index 3058845..73a0025 100644 --- a/X10D.Tests/src/Numerics/Int16Tests.cs +++ b/X10D.Tests/src/Numerics/Int16Tests.cs @@ -4,7 +4,7 @@ using X10D.Numerics; namespace X10D.Tests.Numerics; [TestFixture] -public class Int16Tests +internal class Int16Tests { [Test] public void PopCount_ShouldBe0_Given0() diff --git a/X10D.Tests/src/Numerics/Int32Tests.cs b/X10D.Tests/src/Numerics/Int32Tests.cs index db0d7a3..36b3c1d 100644 --- a/X10D.Tests/src/Numerics/Int32Tests.cs +++ b/X10D.Tests/src/Numerics/Int32Tests.cs @@ -4,7 +4,7 @@ using X10D.Numerics; namespace X10D.Tests.Numerics; [TestFixture] -public class Int32Tests +internal class Int32Tests { [Test] public void PopCount_ShouldBe0_Given0() diff --git a/X10D.Tests/src/Numerics/Int64Tests.cs b/X10D.Tests/src/Numerics/Int64Tests.cs index e6253ca..c4c7c7b 100644 --- a/X10D.Tests/src/Numerics/Int64Tests.cs +++ b/X10D.Tests/src/Numerics/Int64Tests.cs @@ -4,7 +4,7 @@ using X10D.Numerics; namespace X10D.Tests.Numerics; [TestFixture] -public class Int64Tests +internal class Int64Tests { [Test] public void PopCount_ShouldBe0_Given0() diff --git a/X10D.Tests/src/Numerics/QuaternionTests.cs b/X10D.Tests/src/Numerics/QuaternionTests.cs index 3d81754..ce33ad2 100644 --- a/X10D.Tests/src/Numerics/QuaternionTests.cs +++ b/X10D.Tests/src/Numerics/QuaternionTests.cs @@ -5,7 +5,7 @@ using X10D.Numerics; namespace X10D.Tests.Numerics; [TestFixture] -public class QuaternionTests +internal class QuaternionTests { [Test] public void ToAxisAngle_ShouldGiveAngle180VectorZero_GivenQuaternion() diff --git a/X10D.Tests/src/Numerics/RandomTests.cs b/X10D.Tests/src/Numerics/RandomTests.cs index 5f70b31..38b1716 100644 --- a/X10D.Tests/src/Numerics/RandomTests.cs +++ b/X10D.Tests/src/Numerics/RandomTests.cs @@ -4,7 +4,7 @@ using X10D.Numerics; namespace X10D.Tests.Numerics; [TestFixture] -public class RandomTests +internal class RandomTests { [Test] public void NextUnitVector2_ShouldReturnVector_WithMagnitude1() diff --git a/X10D.Tests/src/Numerics/SByteTests.cs b/X10D.Tests/src/Numerics/SByteTests.cs index a161831..72132bc 100644 --- a/X10D.Tests/src/Numerics/SByteTests.cs +++ b/X10D.Tests/src/Numerics/SByteTests.cs @@ -4,8 +4,7 @@ using X10D.Numerics; namespace X10D.Tests.Numerics; [TestFixture] -[CLSCompliant(false)] -public class SByteTests +internal class SByteTests { [Test] public void PopCount_ShouldBe0_Given0() diff --git a/X10D.Tests/src/Numerics/UInt16Tests.cs b/X10D.Tests/src/Numerics/UInt16Tests.cs index 89553d7..585f479 100644 --- a/X10D.Tests/src/Numerics/UInt16Tests.cs +++ b/X10D.Tests/src/Numerics/UInt16Tests.cs @@ -4,8 +4,7 @@ using X10D.Numerics; namespace X10D.Tests.Numerics; [TestFixture] -[CLSCompliant(false)] -public class UInt16Tests +internal class UInt16Tests { [Test] public void PopCount_ShouldBe0_Given0() diff --git a/X10D.Tests/src/Numerics/UInt32Tests.cs b/X10D.Tests/src/Numerics/UInt32Tests.cs index eb15df5..da77d5b 100644 --- a/X10D.Tests/src/Numerics/UInt32Tests.cs +++ b/X10D.Tests/src/Numerics/UInt32Tests.cs @@ -4,8 +4,7 @@ using X10D.Numerics; namespace X10D.Tests.Numerics; [TestFixture] -[CLSCompliant(false)] -public class UInt32Tests +internal class UInt32Tests { [Test] public void PopCount_ShouldBe0_Given0() diff --git a/X10D.Tests/src/Numerics/UInt64Tests.cs b/X10D.Tests/src/Numerics/UInt64Tests.cs index 7663aa3..d01bd39 100644 --- a/X10D.Tests/src/Numerics/UInt64Tests.cs +++ b/X10D.Tests/src/Numerics/UInt64Tests.cs @@ -4,8 +4,7 @@ using X10D.Numerics; namespace X10D.Tests.Numerics; [TestFixture] -[CLSCompliant(false)] -public class UInt64Tests +internal class UInt64Tests { [Test] public void PopCount_ShouldBe0_Given0() diff --git a/X10D.Tests/src/Numerics/Vector2Tests.cs b/X10D.Tests/src/Numerics/Vector2Tests.cs index cef7bc7..e18688e 100644 --- a/X10D.Tests/src/Numerics/Vector2Tests.cs +++ b/X10D.Tests/src/Numerics/Vector2Tests.cs @@ -9,7 +9,7 @@ using X10D.Numerics; namespace X10D.Tests.Numerics; [TestFixture] -public class Vector2Tests +internal class Vector2Tests { [Test] public void Deconstruct_ShouldReturnCorrectValues() diff --git a/X10D.Tests/src/Numerics/Vector3Tests.cs b/X10D.Tests/src/Numerics/Vector3Tests.cs index 402f94b..23c1795 100644 --- a/X10D.Tests/src/Numerics/Vector3Tests.cs +++ b/X10D.Tests/src/Numerics/Vector3Tests.cs @@ -5,7 +5,7 @@ using X10D.Numerics; namespace X10D.Tests.Numerics; [TestFixture] -public class Vector3Tests +internal class Vector3Tests { [Test] public void Deconstruct_ShouldReturnCorrectValues() diff --git a/X10D.Tests/src/Numerics/Vector4Tests.cs b/X10D.Tests/src/Numerics/Vector4Tests.cs index 3c1ba1f..108fb47 100644 --- a/X10D.Tests/src/Numerics/Vector4Tests.cs +++ b/X10D.Tests/src/Numerics/Vector4Tests.cs @@ -5,7 +5,7 @@ using X10D.Numerics; namespace X10D.Tests.Numerics; [TestFixture] -public class Vector4Tests +internal class Vector4Tests { [Test] public void Deconstruct_ShouldReturnCorrectValues() diff --git a/X10D.Tests/src/Reactive/ProgressTests.cs b/X10D.Tests/src/Reactive/ProgressTests.cs index fce2683..e18ed39 100644 --- a/X10D.Tests/src/Reactive/ProgressTests.cs +++ b/X10D.Tests/src/Reactive/ProgressTests.cs @@ -4,7 +4,7 @@ using X10D.Reactive; namespace X10D.Tests.Reactive; [TestFixture] -public class ProgressTests +internal class ProgressTests { [Test] public void OnProgressChanged_ShouldCallCompletionDelegate_GivenCompletionValue() diff --git a/X10D.Tests/src/Reflection/MemberInfoTests.cs b/X10D.Tests/src/Reflection/MemberInfoTests.cs index edc2ebf..bbb0952 100644 --- a/X10D.Tests/src/Reflection/MemberInfoTests.cs +++ b/X10D.Tests/src/Reflection/MemberInfoTests.cs @@ -5,7 +5,7 @@ using X10D.Reflection; namespace X10D.Tests.Reflection; [TestFixture] -public class MemberInfoTests +internal class MemberInfoTests { [Test] public void HasCustomAttribute_ShouldBeTrue_GivenCLSCompliantAttributeOnUnsignedTypes() diff --git a/X10D.Tests/src/Reflection/TypeTests.cs b/X10D.Tests/src/Reflection/TypeTests.cs index 0dc24a1..f474b97 100644 --- a/X10D.Tests/src/Reflection/TypeTests.cs +++ b/X10D.Tests/src/Reflection/TypeTests.cs @@ -4,7 +4,7 @@ using X10D.Reflection; namespace X10D.Tests.Reflection; [TestFixture] -public class TypeTests +internal class TypeTests { [Test] public void Inherits_ShouldBeTrue_GivenStringInheritsObject() diff --git a/X10D.Tests/src/Text/CharSpanTests.cs b/X10D.Tests/src/Text/CharSpanTests.cs index 27d9dc5..683f7c0 100644 --- a/X10D.Tests/src/Text/CharSpanTests.cs +++ b/X10D.Tests/src/Text/CharSpanTests.cs @@ -4,7 +4,7 @@ using X10D.Text; namespace X10D.Tests.Text; [TestFixture] -public class CharSpanTests +internal class CharSpanTests { [Test] public void CountSubstring_ShouldHonor_StringComparison() diff --git a/X10D.Tests/src/Text/CharTests.cs b/X10D.Tests/src/Text/CharTests.cs index 602acba..cf17cdf 100644 --- a/X10D.Tests/src/Text/CharTests.cs +++ b/X10D.Tests/src/Text/CharTests.cs @@ -4,7 +4,7 @@ using X10D.Text; namespace X10D.Tests.Text; [TestFixture] -public class CharTests +internal class CharTests { [Test] public void IsEmoji_ShouldReturnTrue_GivenBasicEmoji() diff --git a/X10D.Tests/src/Text/CoreTests.cs b/X10D.Tests/src/Text/CoreTests.cs index 4ed8903..bbd114c 100644 --- a/X10D.Tests/src/Text/CoreTests.cs +++ b/X10D.Tests/src/Text/CoreTests.cs @@ -4,7 +4,7 @@ using X10D.Text; namespace X10D.Tests.Text; [TestFixture] -public class CoreTests +internal class CoreTests { #if NET5_0_OR_GREATER [Test] diff --git a/X10D.Tests/src/Text/EnumerableTests.cs b/X10D.Tests/src/Text/EnumerableTests.cs index a7b7c86..8e6ecd1 100644 --- a/X10D.Tests/src/Text/EnumerableTests.cs +++ b/X10D.Tests/src/Text/EnumerableTests.cs @@ -4,7 +4,7 @@ using X10D.Text; namespace X10D.Tests.Text; [TestFixture] -public class EnumerableTests +internal class EnumerableTests { [Test] public void Grep_ShouldFilterCorrectly_GivenPattern() diff --git a/X10D.Tests/src/Text/RuneTests.cs b/X10D.Tests/src/Text/RuneTests.cs index d5a6946..49c13e4 100644 --- a/X10D.Tests/src/Text/RuneTests.cs +++ b/X10D.Tests/src/Text/RuneTests.cs @@ -6,7 +6,7 @@ using X10D.Text; namespace X10D.Tests.Text; [TestFixture] -public class RuneTests +internal class RuneTests { [Test] public void IsEmoji_ShouldReturnTrue_GivenBasicEmoji() diff --git a/X10D.Tests/src/Text/StringBuilderReaderTests.cs b/X10D.Tests/src/Text/StringBuilderReaderTests.cs index b6557ad..07e8849 100644 --- a/X10D.Tests/src/Text/StringBuilderReaderTests.cs +++ b/X10D.Tests/src/Text/StringBuilderReaderTests.cs @@ -5,7 +5,7 @@ using X10D.Text; namespace X10D.Tests.Text; [TestFixture] -public class StringBuilderReaderTests +internal class StringBuilderReaderTests { [Test] public void Peek_ShouldReturnNextChar_GivenBuilder() diff --git a/X10D.Tests/src/Text/StringTests.cs b/X10D.Tests/src/Text/StringTests.cs index 6c94343..336cafb 100644 --- a/X10D.Tests/src/Text/StringTests.cs +++ b/X10D.Tests/src/Text/StringTests.cs @@ -8,7 +8,7 @@ using X10D.Text; namespace X10D.Tests.Text; [TestFixture] -public class StringTests +internal class StringTests { [Test] public void AsNullIfEmpty_ShouldBeCorrect() diff --git a/X10D.Tests/src/Time/ByteTests.cs b/X10D.Tests/src/Time/ByteTests.cs index c046241..7c3a3ed 100644 --- a/X10D.Tests/src/Time/ByteTests.cs +++ b/X10D.Tests/src/Time/ByteTests.cs @@ -4,7 +4,7 @@ using X10D.Time; namespace X10D.Tests.Time; [TestFixture] -public class ByteTests +internal class ByteTests { [Test] public void FromUnixTimeMilliseconds_ShouldBeEpoch_GivenZero() diff --git a/X10D.Tests/src/Time/CharSpanTests.cs b/X10D.Tests/src/Time/CharSpanTests.cs index ec35528..f420cf0 100644 --- a/X10D.Tests/src/Time/CharSpanTests.cs +++ b/X10D.Tests/src/Time/CharSpanTests.cs @@ -4,7 +4,7 @@ using X10D.Time; namespace X10D.Tests.Time; [TestFixture] -public class CharSpanTests +internal class CharSpanTests { [Test] public void ToTimeSpan_ShouldReturnCorrectTimeSpan_GivenSpanOfCharacters() diff --git a/X10D.Tests/src/Time/DateOnlyTests.cs b/X10D.Tests/src/Time/DateOnlyTests.cs index 5135446..bae376b 100644 --- a/X10D.Tests/src/Time/DateOnlyTests.cs +++ b/X10D.Tests/src/Time/DateOnlyTests.cs @@ -5,7 +5,7 @@ using X10D.Time; namespace X10D.Tests.Time; [TestFixture] -public class DateOnlyTests +internal class DateOnlyTests { [Test] public void Age_ShouldBe17_Given31December1991Birthday_And30December2017Date() diff --git a/X10D.Tests/src/Time/DateTimeOffsetTests.cs b/X10D.Tests/src/Time/DateTimeOffsetTests.cs index 77c8fff..095f988 100644 --- a/X10D.Tests/src/Time/DateTimeOffsetTests.cs +++ b/X10D.Tests/src/Time/DateTimeOffsetTests.cs @@ -4,7 +4,7 @@ using X10D.Time; namespace X10D.Tests.Time; [TestFixture] -public class DateTimeOffsetTests +internal class DateTimeOffsetTests { [Test] public void Age_ShouldBe17_Given31December1991Birthday_And30December2017Date() diff --git a/X10D.Tests/src/Time/DateTimeTests.cs b/X10D.Tests/src/Time/DateTimeTests.cs index ed834b3..7dd437c 100644 --- a/X10D.Tests/src/Time/DateTimeTests.cs +++ b/X10D.Tests/src/Time/DateTimeTests.cs @@ -4,7 +4,7 @@ using X10D.Time; namespace X10D.Tests.Time; [TestFixture] -public class DateTimeTests +internal class DateTimeTests { [Test] public void Age_ShouldBe17_Given31December1991Birthday_And30December2017Date() diff --git a/X10D.Tests/src/Time/DecimalTests.cs b/X10D.Tests/src/Time/DecimalTests.cs index 6ca948c..f1a2b02 100644 --- a/X10D.Tests/src/Time/DecimalTests.cs +++ b/X10D.Tests/src/Time/DecimalTests.cs @@ -4,7 +4,7 @@ using X10D.Time; namespace X10D.Tests.Time; [TestFixture] -public class DecimalTests +internal class DecimalTests { [Test] public void TicksMillisecondsSecondsMinutesDaysHoursWeeks_ShouldBeZero_GivenZero() diff --git a/X10D.Tests/src/Time/DoubleTests.cs b/X10D.Tests/src/Time/DoubleTests.cs index 32164c9..093e466 100644 --- a/X10D.Tests/src/Time/DoubleTests.cs +++ b/X10D.Tests/src/Time/DoubleTests.cs @@ -5,7 +5,7 @@ using X10D.Time; namespace X10D.Tests.Time; [TestFixture] -public class DoubleTests +internal class DoubleTests { private Half _negativeOne; private Half _one; diff --git a/X10D.Tests/src/Time/HalfTests.cs b/X10D.Tests/src/Time/HalfTests.cs index 7e8acc7..b2f7faf 100644 --- a/X10D.Tests/src/Time/HalfTests.cs +++ b/X10D.Tests/src/Time/HalfTests.cs @@ -4,7 +4,7 @@ using X10D.Time; namespace X10D.Tests.Time; [TestFixture] -public class HalfTests +internal class HalfTests { [Test] public void TicksMillisecondsSecondsMinutesDaysHoursWeeks_ShouldBeZero_GivenZero() diff --git a/X10D.Tests/src/Time/Int16Tests.cs b/X10D.Tests/src/Time/Int16Tests.cs index 58ed0e9..f6c40ed 100644 --- a/X10D.Tests/src/Time/Int16Tests.cs +++ b/X10D.Tests/src/Time/Int16Tests.cs @@ -4,7 +4,7 @@ using X10D.Time; namespace X10D.Tests.Time; [TestFixture] -public class Int16Tests +internal class Int16Tests { [Test] public void FromUnixTimeMilliseconds_ShouldBeEpoch_GivenZero() diff --git a/X10D.Tests/src/Time/Int32Tests.cs b/X10D.Tests/src/Time/Int32Tests.cs index 6cbad58..f0c258b 100644 --- a/X10D.Tests/src/Time/Int32Tests.cs +++ b/X10D.Tests/src/Time/Int32Tests.cs @@ -4,7 +4,7 @@ using X10D.Time; namespace X10D.Tests.Time; [TestFixture] -public class Int32Tests +internal class Int32Tests { [Test] public void FromUnixTimeMilliseconds_ShouldBeEpoch_GivenZero() diff --git a/X10D.Tests/src/Time/Int64Tests.cs b/X10D.Tests/src/Time/Int64Tests.cs index 9b83e67..bf317e8 100644 --- a/X10D.Tests/src/Time/Int64Tests.cs +++ b/X10D.Tests/src/Time/Int64Tests.cs @@ -4,7 +4,7 @@ using X10D.Time; namespace X10D.Tests.Time; [TestFixture] -public class Int64Tests +internal class Int64Tests { [Test] public void FromUnixTimeMilliseconds_ShouldBeEpoch_GivenZero() diff --git a/X10D.Tests/src/Time/SByteTests.cs b/X10D.Tests/src/Time/SByteTests.cs index 278469b..7a7de18 100644 --- a/X10D.Tests/src/Time/SByteTests.cs +++ b/X10D.Tests/src/Time/SByteTests.cs @@ -4,8 +4,7 @@ using X10D.Time; namespace X10D.Tests.Time; [TestFixture] -[CLSCompliant(false)] -public class SByteTests +internal class SByteTests { [Test] public void FromUnixTimeMilliseconds_ShouldBeEpoch_GivenZero() diff --git a/X10D.Tests/src/Time/SingleTests.cs b/X10D.Tests/src/Time/SingleTests.cs index cc2f39b..52fbe24 100644 --- a/X10D.Tests/src/Time/SingleTests.cs +++ b/X10D.Tests/src/Time/SingleTests.cs @@ -4,7 +4,7 @@ using X10D.Time; namespace X10D.Tests.Time; [TestFixture] -public class SingleTests +internal class SingleTests { [Test] public void TicksMillisecondsSecondsMinutesDaysHoursWeeks_ShouldBeZero_GivenZero() diff --git a/X10D.Tests/src/Time/StringTests.cs b/X10D.Tests/src/Time/StringTests.cs index 8cad134..c74658e 100644 --- a/X10D.Tests/src/Time/StringTests.cs +++ b/X10D.Tests/src/Time/StringTests.cs @@ -4,7 +4,7 @@ using X10D.Time; namespace X10D.Tests.Time; [TestFixture] -public class StringTests +internal class StringTests { [Test] public void ToTimeSpan_ShouldReturnCorrectTimeSpan_GivenString() diff --git a/X10D.Tests/src/Time/TimeSpanParserTests.cs b/X10D.Tests/src/Time/TimeSpanParserTests.cs index aa065ce..a5a3aef 100644 --- a/X10D.Tests/src/Time/TimeSpanParserTests.cs +++ b/X10D.Tests/src/Time/TimeSpanParserTests.cs @@ -4,7 +4,7 @@ using X10D.Time; namespace X10D.Tests.Time; [TestFixture] -public class TimeSpanParserTests +internal class TimeSpanParserTests { [Test] public void TryParse_ShouldReturnTrue_GivenWellFormedTimeSpan() diff --git a/X10D.Tests/src/Time/TimeSpanTests.cs b/X10D.Tests/src/Time/TimeSpanTests.cs index 20456d5..ca68da3 100644 --- a/X10D.Tests/src/Time/TimeSpanTests.cs +++ b/X10D.Tests/src/Time/TimeSpanTests.cs @@ -4,7 +4,7 @@ using X10D.Time; namespace X10D.Tests.Time; [TestFixture] -public class TimeSpanTests +internal class TimeSpanTests { private TimeSpan _timeSpan; diff --git a/X10D.Tests/src/Time/UInt16Tests.cs b/X10D.Tests/src/Time/UInt16Tests.cs index 64d327e..d93f58a 100644 --- a/X10D.Tests/src/Time/UInt16Tests.cs +++ b/X10D.Tests/src/Time/UInt16Tests.cs @@ -4,8 +4,7 @@ using X10D.Time; namespace X10D.Tests.Time; [TestFixture] -[CLSCompliant(false)] -public class UInt16Tests +internal class UInt16Tests { [Test] public void FromUnixTimeMilliseconds_ShouldBeEpoch_GivenZero() diff --git a/X10D.Tests/src/Time/UInt32Tests.cs b/X10D.Tests/src/Time/UInt32Tests.cs index 0063fe2..605110f 100644 --- a/X10D.Tests/src/Time/UInt32Tests.cs +++ b/X10D.Tests/src/Time/UInt32Tests.cs @@ -4,8 +4,7 @@ using X10D.Time; namespace X10D.Tests.Time; [TestFixture] -[CLSCompliant(false)] -public class UInt32Tests +internal class UInt32Tests { [Test] public void FromUnixTimeMilliseconds_ShouldBeEpoch_GivenZero() diff --git a/X10D.Tests/src/Time/UInt64Tests.cs b/X10D.Tests/src/Time/UInt64Tests.cs index 48642be..dcd08cd 100644 --- a/X10D.Tests/src/Time/UInt64Tests.cs +++ b/X10D.Tests/src/Time/UInt64Tests.cs @@ -4,8 +4,7 @@ using X10D.Time; namespace X10D.Tests.Time; [TestFixture] -[CLSCompliant(false)] -public class UInt64Tests +internal class UInt64Tests { [Test] public void FromUnixTimeMilliseconds_ShouldBeEpoch_GivenZero() From d17d94a8c1818f0ff18c35a355c2bb4e38c7ea7f Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Tue, 22 Aug 2023 17:39:45 +0100 Subject: [PATCH 077/102] chore: suppress NU1701 (#77) --- X10D.Unity/X10D.Unity.csproj | 1 + 1 file changed, 1 insertion(+) diff --git a/X10D.Unity/X10D.Unity.csproj b/X10D.Unity/X10D.Unity.csproj index b1584ea..e1ac766 100644 --- a/X10D.Unity/X10D.Unity.csproj +++ b/X10D.Unity/X10D.Unity.csproj @@ -2,6 +2,7 @@ netstandard2.1 + $(NoWarn);NU1701 From 4593a21065472b7a25720205cbc81db37563dfec Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Tue, 22 Aug 2023 17:43:16 +0100 Subject: [PATCH 078/102] fix(tools): clear Package property groups --- tools/Benchmarks/Benchmarks.csproj | 6 ++++++ tools/SourceGenerator/SourceGenerator.csproj | 6 ++++++ tools/SourceValidator/SourceValidator.csproj | 6 ++++++ tools/UpmPackageGenerator/UpmPackageGenerator.csproj | 6 ++++++ tools/X10D.MetaServices/X10D.MetaServices.csproj | 6 ++++++ 5 files changed, 30 insertions(+) diff --git a/tools/Benchmarks/Benchmarks.csproj b/tools/Benchmarks/Benchmarks.csproj index e5b1c6e..5cc5fa9 100644 --- a/tools/Benchmarks/Benchmarks.csproj +++ b/tools/Benchmarks/Benchmarks.csproj @@ -10,6 +10,12 @@ true true true + + + + + + diff --git a/tools/SourceGenerator/SourceGenerator.csproj b/tools/SourceGenerator/SourceGenerator.csproj index 266d229..2284922 100644 --- a/tools/SourceGenerator/SourceGenerator.csproj +++ b/tools/SourceGenerator/SourceGenerator.csproj @@ -7,6 +7,12 @@ enable true true + + + + + + diff --git a/tools/SourceValidator/SourceValidator.csproj b/tools/SourceValidator/SourceValidator.csproj index 1d72f7d..5a5e699 100644 --- a/tools/SourceValidator/SourceValidator.csproj +++ b/tools/SourceValidator/SourceValidator.csproj @@ -8,6 +8,12 @@ enable true true + + + + + + diff --git a/tools/UpmPackageGenerator/UpmPackageGenerator.csproj b/tools/UpmPackageGenerator/UpmPackageGenerator.csproj index 277ab31..1424dbd 100644 --- a/tools/UpmPackageGenerator/UpmPackageGenerator.csproj +++ b/tools/UpmPackageGenerator/UpmPackageGenerator.csproj @@ -7,6 +7,12 @@ enable true true + + + + + + diff --git a/tools/X10D.MetaServices/X10D.MetaServices.csproj b/tools/X10D.MetaServices/X10D.MetaServices.csproj index aa845a6..8cec64e 100644 --- a/tools/X10D.MetaServices/X10D.MetaServices.csproj +++ b/tools/X10D.MetaServices/X10D.MetaServices.csproj @@ -5,6 +5,12 @@ 11.0 enable enable + + + + + + From 1b71d94084be3a3766747ac5f01cecdab137be63 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Tue, 22 Aug 2023 17:44:29 +0100 Subject: [PATCH 079/102] chore: remove redundant shared props --- tools/Benchmarks/Benchmarks.csproj | 4 ---- tools/SourceGenerator/SourceGenerator.csproj | 4 ---- tools/SourceValidator/SourceValidator.csproj | 4 ---- tools/UpmPackageGenerator/UpmPackageGenerator.csproj | 3 --- tools/X10D.MetaServices/X10D.MetaServices.csproj | 3 --- 5 files changed, 18 deletions(-) diff --git a/tools/Benchmarks/Benchmarks.csproj b/tools/Benchmarks/Benchmarks.csproj index 5cc5fa9..84941d0 100644 --- a/tools/Benchmarks/Benchmarks.csproj +++ b/tools/Benchmarks/Benchmarks.csproj @@ -4,11 +4,7 @@ Release Exe net7.0;net6.0;netcoreapp3.1 - 11.0 - enable - enable true - true true diff --git a/tools/SourceGenerator/SourceGenerator.csproj b/tools/SourceGenerator/SourceGenerator.csproj index 2284922..1e60846 100644 --- a/tools/SourceGenerator/SourceGenerator.csproj +++ b/tools/SourceGenerator/SourceGenerator.csproj @@ -2,11 +2,7 @@ netstandard2.0 - 11.0 - enable - enable true - true diff --git a/tools/SourceValidator/SourceValidator.csproj b/tools/SourceValidator/SourceValidator.csproj index 5a5e699..d8ec2f0 100644 --- a/tools/SourceValidator/SourceValidator.csproj +++ b/tools/SourceValidator/SourceValidator.csproj @@ -3,11 +3,7 @@ Exe net7.0 - 11.0 - enable - enable true - true diff --git a/tools/UpmPackageGenerator/UpmPackageGenerator.csproj b/tools/UpmPackageGenerator/UpmPackageGenerator.csproj index 1424dbd..1629a36 100644 --- a/tools/UpmPackageGenerator/UpmPackageGenerator.csproj +++ b/tools/UpmPackageGenerator/UpmPackageGenerator.csproj @@ -3,10 +3,7 @@ Exe net7.0 - enable - enable true - true diff --git a/tools/X10D.MetaServices/X10D.MetaServices.csproj b/tools/X10D.MetaServices/X10D.MetaServices.csproj index 8cec64e..0a38293 100644 --- a/tools/X10D.MetaServices/X10D.MetaServices.csproj +++ b/tools/X10D.MetaServices/X10D.MetaServices.csproj @@ -2,9 +2,6 @@ netstandard2.0 - 11.0 - enable - enable From 27e0ec54be62238e4d5be683f4b0d9eb8321ba09 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Tue, 22 Aug 2023 17:46:44 +0100 Subject: [PATCH 080/102] chore: extract shared build props --- X10D.sln | 3 +++ tools/Benchmarks/Benchmarks.csproj | 7 ------- tools/Directory.Build.props | 13 +++++++++++++ tools/SourceGenerator/SourceGenerator.csproj | 7 ------- tools/SourceValidator/SourceValidator.csproj | 7 ------- .../UpmPackageGenerator/UpmPackageGenerator.csproj | 7 ------- tools/X10D.MetaServices/X10D.MetaServices.csproj | 6 ------ 7 files changed, 16 insertions(+), 34 deletions(-) create mode 100644 tools/Directory.Build.props diff --git a/X10D.sln b/X10D.sln index b1b36a2..b114966 100644 --- a/X10D.sln +++ b/X10D.sln @@ -45,6 +45,9 @@ EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UpmPackageGenerator", "tools\UpmPackageGenerator\UpmPackageGenerator.csproj", "{CCBF047D-1B01-45EC-8D89-B00B4AC482CA}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tools", "Tools", "{4B8969E6-27D2-4357-964E-9979FF7CC805}" + ProjectSection(SolutionItems) = preProject + tools\Directory.Build.props = tools\Directory.Build.props + EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Benchmarks", "tools\Benchmarks\Benchmarks.csproj", "{259450A0-9964-403A-91E1-E9111B92C293}" EndProject diff --git a/tools/Benchmarks/Benchmarks.csproj b/tools/Benchmarks/Benchmarks.csproj index 84941d0..fb326bc 100644 --- a/tools/Benchmarks/Benchmarks.csproj +++ b/tools/Benchmarks/Benchmarks.csproj @@ -4,14 +4,7 @@ Release Exe net7.0;net6.0;netcoreapp3.1 - true true - - - - - - diff --git a/tools/Directory.Build.props b/tools/Directory.Build.props new file mode 100644 index 0000000..b933b03 --- /dev/null +++ b/tools/Directory.Build.props @@ -0,0 +1,13 @@ + + + 11.0 + true + true + + + + + + + + \ No newline at end of file diff --git a/tools/SourceGenerator/SourceGenerator.csproj b/tools/SourceGenerator/SourceGenerator.csproj index 1e60846..29d8a3c 100644 --- a/tools/SourceGenerator/SourceGenerator.csproj +++ b/tools/SourceGenerator/SourceGenerator.csproj @@ -2,13 +2,6 @@ netstandard2.0 - true - - - - - - diff --git a/tools/SourceValidator/SourceValidator.csproj b/tools/SourceValidator/SourceValidator.csproj index d8ec2f0..5059923 100644 --- a/tools/SourceValidator/SourceValidator.csproj +++ b/tools/SourceValidator/SourceValidator.csproj @@ -3,13 +3,6 @@ Exe net7.0 - true - - - - - - diff --git a/tools/UpmPackageGenerator/UpmPackageGenerator.csproj b/tools/UpmPackageGenerator/UpmPackageGenerator.csproj index 1629a36..82cad6d 100644 --- a/tools/UpmPackageGenerator/UpmPackageGenerator.csproj +++ b/tools/UpmPackageGenerator/UpmPackageGenerator.csproj @@ -3,13 +3,6 @@ Exe net7.0 - true - - - - - - diff --git a/tools/X10D.MetaServices/X10D.MetaServices.csproj b/tools/X10D.MetaServices/X10D.MetaServices.csproj index 0a38293..2756020 100644 --- a/tools/X10D.MetaServices/X10D.MetaServices.csproj +++ b/tools/X10D.MetaServices/X10D.MetaServices.csproj @@ -2,12 +2,6 @@ netstandard2.0 - - - - - - From 1e71029f384d7bea35f729ad7eb35146ccca18a7 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Tue, 22 Aug 2023 17:51:51 +0100 Subject: [PATCH 081/102] refactor: remove X10D.DSharpPlus --- .github/workflows/nightly.yml | 1 - .github/workflows/prerelease.yml | 1 - .github/workflows/release.yml | 1 - CHANGELOG.md | 1 + X10D.DSharpPlus/X10D.DSharpPlus.csproj | 12 - X10D.DSharpPlus/src/Assembly.cs | 1 - .../src/DiscordChannelExtensions.cs | 71 ---- .../src/DiscordClientExtensions.cs | 71 ---- .../src/DiscordEmbedBuilderExtensions.cs | 212 ----------- X10D.DSharpPlus/src/DiscordGuildExtensions.cs | 84 ----- .../src/DiscordMemberExtensions.cs | 63 ---- .../src/DiscordMessageExtensions.cs | 76 ---- X10D.DSharpPlus/src/DiscordUserExtensions.cs | 145 -------- X10D.DSharpPlus/src/MentionUtility.cs | 329 ------------------ X10D.sln | 6 - 15 files changed, 1 insertion(+), 1073 deletions(-) delete mode 100644 X10D.DSharpPlus/X10D.DSharpPlus.csproj delete mode 100644 X10D.DSharpPlus/src/Assembly.cs delete mode 100644 X10D.DSharpPlus/src/DiscordChannelExtensions.cs delete mode 100644 X10D.DSharpPlus/src/DiscordClientExtensions.cs delete mode 100644 X10D.DSharpPlus/src/DiscordEmbedBuilderExtensions.cs delete mode 100644 X10D.DSharpPlus/src/DiscordGuildExtensions.cs delete mode 100644 X10D.DSharpPlus/src/DiscordMemberExtensions.cs delete mode 100644 X10D.DSharpPlus/src/DiscordMessageExtensions.cs delete mode 100644 X10D.DSharpPlus/src/DiscordUserExtensions.cs delete mode 100644 X10D.DSharpPlus/src/MentionUtility.cs diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index ca14ed1..9f1a02d 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -33,7 +33,6 @@ jobs: run: | mkdir build dotnet pack X10D --configuration Debug --no-build -p:SymbolPackageFormat=snupkg --include-symbols --include-source -o build -p:VersionSuffix='nightly' -p:BuildNumber=${{ github.run_number }} - dotnet pack X10D.DSharpPlus --configuration Debug --no-build -p:SymbolPackageFormat=snupkg --include-symbols --include-source -o build -p:VersionSuffix='nightly' -p:BuildNumber=${{ github.run_number }} dotnet pack X10D.Hosting --configuration Debug --no-build -p:SymbolPackageFormat=snupkg --include-symbols --include-source -o build -p:VersionSuffix='nightly' -p:BuildNumber=${{ github.run_number }} dotnet pack X10D.Unity --configuration Debug --no-build -p:SymbolPackageFormat=snupkg --include-symbols --include-source -o build -p:VersionSuffix='nightly' -p:BuildNumber=${{ github.run_number }} diff --git a/.github/workflows/prerelease.yml b/.github/workflows/prerelease.yml index 7b9940b..01af506 100644 --- a/.github/workflows/prerelease.yml +++ b/.github/workflows/prerelease.yml @@ -32,7 +32,6 @@ jobs: run: | mkdir build dotnet pack X10D --configuration Release --no-build -p:SymbolPackageFormat=snupkg --include-symbols --include-source -o build -p:VersionSuffix='prerelease' -p:BuildNumber=${{ github.run_number }} - dotnet pack X10D.DSharpPlus --configuration Release --no-build -p:SymbolPackageFormat=snupkg --include-symbols --include-source -o build -p:VersionSuffix='prerelease' -p:BuildNumber=${{ github.run_number }} dotnet pack X10D.Hosting --configuration Release --no-build -p:SymbolPackageFormat=snupkg --include-symbols --include-source -o build -p:VersionSuffix='prerelease' -p:BuildNumber=${{ github.run_number }} dotnet pack X10D.Unity --configuration Release --no-build -p:SymbolPackageFormat=snupkg --include-symbols --include-source -o build -p:VersionSuffix='prerelease' -p:BuildNumber=${{ github.run_number }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 0bdbb14..c5fd973 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -32,7 +32,6 @@ jobs: run: | mkdir build dotnet pack X10D --configuration Release --no-build -p:SymbolPackageFormat=snupkg --include-symbols --include-source -o build - dotnet pack X10D.DSharpPlus --configuration Release --no-build -p:SymbolPackageFormat=snupkg --include-symbols --include-source -o build dotnet pack X10D.Hosting --configuration Release --no-build -p:SymbolPackageFormat=snupkg --include-symbols --include-source -o build dotnet pack X10D.Unity --configuration Release --no-build -p:SymbolPackageFormat=snupkg --include-symbols --include-source -o build diff --git a/CHANGELOG.md b/CHANGELOG.md index 23f6c22..c1d3e44 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -34,6 +34,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Removed - X10D: Removed `IEnumerable.ConcatOne` - this functionality already exists with `Append`. +- X10D.DSharpPlus: Complete sunset of library. This library will not be updated to support DSharpPlus v5.0.0. ## [3.3.1] - 2023-08-21 diff --git a/X10D.DSharpPlus/X10D.DSharpPlus.csproj b/X10D.DSharpPlus/X10D.DSharpPlus.csproj deleted file mode 100644 index 9128252..0000000 --- a/X10D.DSharpPlus/X10D.DSharpPlus.csproj +++ /dev/null @@ -1,12 +0,0 @@ - - - - net7.0;net6.0;netstandard2.1 - true - - - - - - - diff --git a/X10D.DSharpPlus/src/Assembly.cs b/X10D.DSharpPlus/src/Assembly.cs deleted file mode 100644 index 4e11466..0000000 --- a/X10D.DSharpPlus/src/Assembly.cs +++ /dev/null @@ -1 +0,0 @@ -[assembly: CLSCompliant(false)] diff --git a/X10D.DSharpPlus/src/DiscordChannelExtensions.cs b/X10D.DSharpPlus/src/DiscordChannelExtensions.cs deleted file mode 100644 index 820ced0..0000000 --- a/X10D.DSharpPlus/src/DiscordChannelExtensions.cs +++ /dev/null @@ -1,71 +0,0 @@ -using DSharpPlus; -using DSharpPlus.Entities; - -namespace X10D.DSharpPlus; - -/// -/// Extension methods for . -/// -public static class DiscordChannelExtensions -{ - /// - /// Gets the category of this channel. - /// - /// The channel whose category to retrieve. - /// - /// The category of , or itself if it is already a category; - /// if this channel is not defined in a category. - /// - /// is . - public static DiscordChannel? GetCategory(this DiscordChannel channel) - { - if (channel is null) - { - throw new ArgumentNullException(nameof(channel)); - } - - while (true) - { - if (channel.IsCategory) - { - return channel; - } - - if (channel.Parent is not { } parent) - { - return null; - } - - channel = parent; - } - } - - /// - /// Normalizes a so that the internal client is assured to be a specified value. - /// - /// The to normalize. - /// The target client. - /// - /// A whose public values will match , but whose internal client - /// is . - /// - /// - /// is - /// -or- - /// is - /// - public static async Task NormalizeClientAsync(this DiscordChannel channel, DiscordClient client) - { - if (channel is null) - { - throw new ArgumentNullException(nameof(channel)); - } - - if (client is null) - { - throw new ArgumentNullException(nameof(client)); - } - - return await client.GetChannelAsync(channel.Id).ConfigureAwait(false); - } -} diff --git a/X10D.DSharpPlus/src/DiscordClientExtensions.cs b/X10D.DSharpPlus/src/DiscordClientExtensions.cs deleted file mode 100644 index 5dfd415..0000000 --- a/X10D.DSharpPlus/src/DiscordClientExtensions.cs +++ /dev/null @@ -1,71 +0,0 @@ -using DSharpPlus; -using DSharpPlus.Entities; -using DSharpPlus.Exceptions; - -namespace X10D.DSharpPlus; - -/// -/// Extension methods for . -/// -public static class DiscordClientExtensions -{ - /// - /// Instructs the client to automatically join all existing threads, and any newly-created threads. - /// - /// The whose events should be subscribed. - /// - /// to automatically rejoin a thread if this client was removed; otherwise, - /// . - /// - /// is . - public static void AutoJoinThreads(this DiscordClient client, bool rejoinIfRemoved = true) - { - if (client is null) - { - throw new ArgumentNullException(nameof(client)); - } - - client.GuildAvailable += (_, args) => args.Guild.JoinAllThreadsAsync(); - client.ThreadCreated += (_, args) => args.Thread.JoinThreadAsync(); - - if (rejoinIfRemoved) - { - client.ThreadMembersUpdated += (_, args) => - { - if (args.RemovedMembers.Any(m => m.Id == client.CurrentUser.Id)) - return args.Thread.JoinThreadAsync(); - - return Task.CompletedTask; - }; - } - } - - /// - /// Gets a user by their ID. If the user is not found, is returned instead of - /// being thrown. - /// - /// The Discord client. - /// The ID of the user to retrieve. - /// is . - public static async Task GetUserOrNullAsync(this DiscordClient client, ulong userId) - { - if (client is null) - { - throw new ArgumentNullException(nameof(client)); - } - - try - { - // we should never use exceptions for flow control but this is D#+ we're talking about. - // NotFoundException isn't even documented, and yet it gets thrown when a user doesn't exist. - // so this method should hopefully clearly express that - and at least using exceptions for flow control *here*, - // removes the need to do the same in consumer code. - // god I hate this. - return await client.GetUserAsync(userId).ConfigureAwait(false); - } - catch (NotFoundException) - { - return null; - } - } -} diff --git a/X10D.DSharpPlus/src/DiscordEmbedBuilderExtensions.cs b/X10D.DSharpPlus/src/DiscordEmbedBuilderExtensions.cs deleted file mode 100644 index 1c2c479..0000000 --- a/X10D.DSharpPlus/src/DiscordEmbedBuilderExtensions.cs +++ /dev/null @@ -1,212 +0,0 @@ -using DSharpPlus.Entities; - -namespace X10D.DSharpPlus; - -/// -/// Extension methods for . -/// -public static class DiscordEmbedBuilderExtensions -{ - /// - /// Adds a field of any value type to the embed. - /// - /// The to modify. - /// The name of the embed field. - /// The value of the embed field. - /// to display this field inline; otherwise, . - /// The type of . - /// The current instance of ; that is, . - /// is . - public static DiscordEmbedBuilder AddField( - this DiscordEmbedBuilder builder, - string name, - T? value, - bool inline = false) - { - if (builder is null) - { - throw new ArgumentNullException(nameof(builder)); - } - - return builder.AddField(name, value?.ToString(), inline); - } - - /// - /// Conditionally adds a field to the embed. - /// - /// The to modify. - /// The condition whose value is used to determine whether the field will be added. - /// The name of the embed field. - /// The value of the embed field. - /// to display this field inline; otherwise, . - /// The type of . - /// The current instance of ; that is, . - /// is . - public static DiscordEmbedBuilder AddFieldIf( - this DiscordEmbedBuilder builder, - bool condition, - string name, - T? value, - bool inline = false) - { - if (builder is null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (condition) - { - builder.AddField(name, value?.ToString(), inline); - } - - return builder; - } - - /// - /// Conditionally adds a field to the embed. - /// - /// The to modify. - /// The predicate whose return value is used to determine whether the field will be added. - /// The name of the embed field. - /// The value of the embed field. - /// to display this field inline; otherwise, . - /// The type of . - /// The current instance of ; that is, . - /// - /// is . - /// -or- - /// is . - /// - public static DiscordEmbedBuilder AddFieldIf( - this DiscordEmbedBuilder builder, - Func predicate, - string name, - T? value, - bool inline = false) - { - if (builder is null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (predicate is null) - { - throw new ArgumentNullException(nameof(predicate)); - } - - if (predicate.Invoke()) - { - builder.AddField(name, value?.ToString(), inline); - } - - return builder; - } - - /// - /// Conditionally adds a field to the embed. - /// - /// The to modify. - /// The predicate whose return value is used to determine whether the field will be added. - /// The name of the embed field. - /// The delegate whose return value will be used as the value of the embed field. - /// to display this field inline; otherwise, . - /// The return type of . - /// The current instance of ; that is, . - /// - /// is . - /// -or- - /// is . - /// -or- - /// is . - /// - public static DiscordEmbedBuilder AddFieldIf( - this DiscordEmbedBuilder builder, - Func predicate, - string name, - Func valueFactory, - bool inline = false) - { - if (builder is null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (predicate is null) - { - throw new ArgumentNullException(nameof(predicate)); - } - - if (valueFactory is null) - { - throw new ArgumentNullException(nameof(valueFactory)); - } - - if (predicate.Invoke()) - { - builder.AddField(name, valueFactory.Invoke()?.ToString(), inline); - } - - return builder; - } - - /// - /// Conditionally adds a field to the embed. - /// - /// The to modify. - /// The condition whose value is used to determine whether the field will be added. - /// The name of the embed field. - /// The delegate whose return value will be used as the value of the embed field. - /// to display this field inline; otherwise, . - /// The return type of . - /// The current instance of ; that is, . - /// - /// is . - /// -or- - /// is . - /// - public static DiscordEmbedBuilder AddFieldIf( - this DiscordEmbedBuilder builder, - bool condition, - string name, - Func valueFactory, - bool inline = false) - { - if (builder is null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (valueFactory is null) - { - throw new ArgumentNullException(nameof(valueFactory)); - } - - if (condition) - { - builder.AddField(name, valueFactory.Invoke()?.ToString(), inline); - } - - return builder; - } - - /// - /// Sets the embed's author. - /// - /// The embed builder to modify. - /// The author. - /// The current instance of . - public static DiscordEmbedBuilder WithAuthor(this DiscordEmbedBuilder builder, DiscordUser user) - { - if (builder is null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (user is null) - { - throw new ArgumentNullException(nameof(user)); - } - - return builder.WithAuthor(user.GetUsernameWithDiscriminator(), iconUrl: user.AvatarUrl); - } -} diff --git a/X10D.DSharpPlus/src/DiscordGuildExtensions.cs b/X10D.DSharpPlus/src/DiscordGuildExtensions.cs deleted file mode 100644 index ff4636e..0000000 --- a/X10D.DSharpPlus/src/DiscordGuildExtensions.cs +++ /dev/null @@ -1,84 +0,0 @@ -using DSharpPlus; -using DSharpPlus.Entities; -using DSharpPlus.Exceptions; - -namespace X10D.DSharpPlus; - -/// -/// Extension methods for . -/// -public static class DiscordGuildExtensions -{ - /// - /// Joins all active threads in the guild that this client has permission to view. - /// - /// The guild whose active threads to join. - /// is . - public static async Task JoinAllThreadsAsync(this DiscordGuild guild) - { - if (guild is null) - { - throw new ArgumentNullException(nameof(guild)); - } - - await Task.WhenAll(guild.Threads.Values.Select(t => t.JoinThreadAsync())).ConfigureAwait(false); - } - - /// - /// Gets a guild member by their ID. If the member is not found, is returned instead of - /// being thrown. - /// - /// The guild whose member list to search. - /// The ID of the member to retrieve. - /// is . - public static async Task GetMemberOrNullAsync(this DiscordGuild guild, ulong userId) - { - if (guild is null) - { - throw new ArgumentNullException(nameof(guild)); - } - - try - { - // we should never use exceptions for flow control but this is D#+ we're talking about. - // NotFoundException isn't even documented, and yet it gets thrown when a member doesn't exist. - // so this method should hopefully clearly express that - and at least using exceptions for flow control *here*, - // removes the need to do the same in consumer code. - // god I hate this. - return await guild.GetMemberAsync(userId).ConfigureAwait(false); - } - catch (NotFoundException) - { - return null; - } - } - - /// - /// Normalizes a so that the internal client is assured to be a specified value. - /// - /// The to normalize. - /// The target client. - /// - /// A whose public values will match , but whose internal client is - /// . - /// - /// - /// is - /// -or- - /// is - /// - public static async Task NormalizeClientAsync(this DiscordGuild guild, DiscordClient client) - { - if (guild is null) - { - throw new ArgumentNullException(nameof(guild)); - } - - if (client is null) - { - throw new ArgumentNullException(nameof(client)); - } - - return await client.GetGuildAsync(guild.Id).ConfigureAwait(false); - } -} diff --git a/X10D.DSharpPlus/src/DiscordMemberExtensions.cs b/X10D.DSharpPlus/src/DiscordMemberExtensions.cs deleted file mode 100644 index 7ec9925..0000000 --- a/X10D.DSharpPlus/src/DiscordMemberExtensions.cs +++ /dev/null @@ -1,63 +0,0 @@ -using DSharpPlus; -using DSharpPlus.Entities; - -namespace X10D.DSharpPlus; - -/// -/// Extension methods for . -/// -public static class DiscordMemberExtensions -{ - /// - /// Returns a value indicating whether this member has the specified role. - /// - /// The member whose roles to search. - /// The role for which to check. - /// - /// if has the role; otherwise, . - /// - public static bool HasRole(this DiscordMember member, DiscordRole role) - { - if (member is null) - { - throw new ArgumentNullException(nameof(member)); - } - - if (role is null) - { - throw new ArgumentNullException(nameof(role)); - } - - return member.Roles.Contains(role); - } - - /// - /// Normalizes a so that the internal client is assured to be a specified value. - /// - /// The to normalize. - /// The target client. - /// - /// A whose public values will match , but whose internal client - /// is . - /// - /// - /// is - /// -or- - /// is - /// - public static async Task NormalizeClientAsync(this DiscordMember member, DiscordClient client) - { - if (member is null) - { - throw new ArgumentNullException(nameof(member)); - } - - if (client is null) - { - throw new ArgumentNullException(nameof(client)); - } - - DiscordGuild guild = await member.Guild.NormalizeClientAsync(client).ConfigureAwait(false); - return await guild.GetMemberAsync(member.Id).ConfigureAwait(false); - } -} diff --git a/X10D.DSharpPlus/src/DiscordMessageExtensions.cs b/X10D.DSharpPlus/src/DiscordMessageExtensions.cs deleted file mode 100644 index f43116d..0000000 --- a/X10D.DSharpPlus/src/DiscordMessageExtensions.cs +++ /dev/null @@ -1,76 +0,0 @@ -using DSharpPlus; -using DSharpPlus.Entities; - -namespace X10D.DSharpPlus; - -/// -/// Extension methods for . -/// -public static class DiscordMessageExtensions -{ - /// - /// Deletes this message after a specified delay. - /// - /// The message to delete. - /// The delay before deletion. - /// The reason for the deletion. - /// is . - public static async Task DeleteAfterAsync(this DiscordMessage message, TimeSpan delay, string? reason = null) - { - if (message is null) - { - throw new ArgumentNullException(nameof(message)); - } - - await Task.Delay(delay).ConfigureAwait(false); - await message.DeleteAsync(reason).ConfigureAwait(false); - } - - /// - /// Deletes the message as created by this task after a specified delay. - /// - /// The task whose result should be deleted. - /// The delay before deletion. - /// The reason for the deletion. - /// is . - public static async Task DeleteAfterAsync(this Task task, TimeSpan delay, string? reason = null) - { - if (task is null) - { - throw new ArgumentNullException(nameof(task)); - } - - DiscordMessage message = await task.ConfigureAwait(false); - await message.DeleteAfterAsync(delay, reason).ConfigureAwait(false); - } - - /// - /// Normalizes a so that the internal client is assured to be a specified value. - /// - /// The to normalize. - /// The target client. - /// - /// A whose public values will match , but whose internal client - /// is . - /// - /// - /// is - /// -or- - /// is - /// - public static async Task NormalizeClientAsync(this DiscordMessage message, DiscordClient client) - { - if (message is null) - { - throw new ArgumentNullException(nameof(message)); - } - - if (client is null) - { - throw new ArgumentNullException(nameof(client)); - } - - DiscordChannel channel = await message.Channel.NormalizeClientAsync(client).ConfigureAwait(false); - return await channel.GetMessageAsync(message.Id).ConfigureAwait(false); - } -} diff --git a/X10D.DSharpPlus/src/DiscordUserExtensions.cs b/X10D.DSharpPlus/src/DiscordUserExtensions.cs deleted file mode 100644 index 33eaa6e..0000000 --- a/X10D.DSharpPlus/src/DiscordUserExtensions.cs +++ /dev/null @@ -1,145 +0,0 @@ -using DSharpPlus; -using DSharpPlus.Entities; -using DSharpPlus.Exceptions; - -namespace X10D.DSharpPlus; - -/// -/// Extension methods for . -/// -public static class DiscordUserExtensions -{ - /// - /// Returns the current as a member of the specified guild. - /// - /// The user to transform. - /// The guild whose member list to search. - /// - /// A whose is equal to , or - /// if this user is not in the specified . - /// - /// - /// is . - /// -or- - /// is . - /// - public static async Task GetAsMemberOfAsync(this DiscordUser user, DiscordGuild guild) - { - if (user is null) - { - throw new ArgumentNullException(nameof(user)); - } - - if (guild is null) - { - throw new ArgumentNullException(nameof(guild)); - } - - if (user is DiscordMember member && member.Guild == guild) - { - return member; - } - - if (guild.Members.TryGetValue(user.Id, out member!)) - { - return member; - } - - try - { - return await guild.GetMemberAsync(user.Id).ConfigureAwait(false); - } - catch (NotFoundException) - { - return null; - } - } - - /// - /// Returns the user's username with the discriminator, in the format username#discriminator. - /// - /// The user whose username and discriminator to retrieve. - /// A string in the format username#discriminator - /// is . - public static string GetUsernameWithDiscriminator(this DiscordUser user) - { - if (user is null) - { - throw new ArgumentNullException(nameof(user)); - } - - if (user.Discriminator == "0") - { - // user has a new username. see: https://discord.com/blog/usernames - return user.Username; - } - - return $"{user.Username}#{user.Discriminator}"; - } - - /// - /// Returns a value indicating whether the current user is in the specified guild. - /// - /// The user to check. - /// The guild whose member list to search. - /// - /// if is a member of ; otherwise, - /// . - /// - public static async Task IsInGuildAsync(this DiscordUser user, DiscordGuild guild) - { - if (user is null) - { - throw new ArgumentNullException(nameof(user)); - } - - if (guild is null) - { - throw new ArgumentNullException(nameof(guild)); - } - - if (guild.Members.TryGetValue(user.Id, out _)) - { - return true; - } - - try - { - DiscordMember? member = await guild.GetMemberAsync(user.Id).ConfigureAwait(false); - return member is not null; - } - catch (NotFoundException) - { - return false; - } - } - - /// - /// Normalizes a so that the internal client is assured to be a specified value. - /// - /// The to normalize. - /// The target client. - /// - /// A whose public values will match , but whose internal client is - /// . - /// - /// - /// is - /// -or- - /// is - /// - public static async Task NormalizeClientAsync(this DiscordUser user, DiscordClient client) - { - if (user is null) - { - throw new ArgumentNullException(nameof(user)); - } - - if (client is null) - { - throw new ArgumentNullException(nameof(client)); - } - - return await client.GetUserAsync(user.Id).ConfigureAwait(false); - } -} diff --git a/X10D.DSharpPlus/src/MentionUtility.cs b/X10D.DSharpPlus/src/MentionUtility.cs deleted file mode 100644 index efda930..0000000 --- a/X10D.DSharpPlus/src/MentionUtility.cs +++ /dev/null @@ -1,329 +0,0 @@ -using System.Globalization; - -namespace X10D.DSharpPlus; - -/// -/// Provides methods for encoding and decoding Discord mention strings. -/// -/// -/// The implementations in this class are designed to resemble MentionUtils as provided by Discord.NET. The source is -/// available -/// -/// here -/// . -/// -public static class MentionUtility -{ - /// - /// Returns a channel mention string built from the specified channel ID. - /// - /// The ID of the channel to mention. - /// A channel mention string in the format <#123>. - public static string MentionChannel(decimal id) - { - return $"<#{id:N0}>"; - } - - /// - /// Returns a channel mention string built from the specified channel ID. - /// - /// The ID of the channel to mention. - /// A channel mention string in the format <#123>. - [CLSCompliant(false)] - public static string MentionChannel(ulong id) - { - return $"<#{id}>"; - } - - /// - /// Returns a role mention string built from the specified channel ID. - /// - /// The ID of the role to mention. - /// A role mention string in the format <@&123>. - public static string MentionRole(decimal id) - { - return $"<@&{id:N0}>"; - } - - /// - /// Returns a role mention string built from the specified role ID. - /// - /// The ID of the role to mention. - /// A role mention string in the format <@&123>. - [CLSCompliant(false)] - public static string MentionRole(ulong id) - { - return $"<@&{id}>"; - } - - /// - /// Returns a user mention string built from the specified user ID. - /// - /// The ID of the user to mention. - /// A user mention string in the format <@123>. - [CLSCompliant(false)] - public static string MentionUser(decimal id) - { - return MentionUser(id, false); - } - - /// - /// Returns a user mention string built from the specified user ID. - /// - /// The ID of the user to mention. - /// - /// if the mention string should account for nicknames; otherwise, . - /// - /// - /// A user mention string in the format <@!123> if is , - /// or in the format <@123> if is . - /// - [CLSCompliant(false)] - public static string MentionUser(decimal id, bool nickname) - { - return nickname ? $"<@!{id:N0}>" : $"<@{id:N0}>"; - } - - /// - /// Returns a user mention string built from the specified user ID. - /// - /// The ID of the user to mention. - /// A user mention string in the format <@123>. - [CLSCompliant(false)] - public static string MentionUser(ulong id) - { - return MentionUser(id, false); - } - - /// - /// Returns a user mention string built from the specified user ID. - /// - /// The ID of the user to mention. - /// - /// if the mention string should account for nicknames; otherwise, . - /// - /// - /// A user mention string in the format <@!123> if is , - /// or in the format <@123> if is . - /// - [CLSCompliant(false)] - public static string MentionUser(ulong id, bool nickname) - { - return nickname ? $"<@!{id}>" : $"<@{id}>"; - } - - /// - /// Parses a provided channel mention string to a decimal value representing the channel ID. A return value indicates - /// whether the parse succeeded. - /// - /// A string containing a mention string to parse, in the format <#123>. - /// - /// When this method returns, contains the decimal value representing the channel ID contained within - /// , if the conversion succeeded, or zero if the conversion failed. The conversion fails if the - /// parameter is or , is not of the correct - /// format, or represents a number less than or greater than . - /// - /// if the parse was successful; otherwise, . - public static bool TryParseChannel(string? value, out decimal result) - { - result = 0; - if (string.IsNullOrWhiteSpace(value)) - { - return false; - } - - if (value.Length < 3 || value[0] != '<' || value[1] != '#' || value[^1] != '>') - { - return false; - } - - value = value.Substring(2, value.Length - 3); // <#123> - if (!ulong.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out ulong actual)) - { - return false; - } - - result = actual; - return true; - } - - /// - /// Parses a provided channel mention string to a 64-bit unsigned integer representing the channel ID. A return value - /// indicates whether the parse succeeded. - /// - /// A string containing a mention string to parse, in the format <#123>. - /// - /// When this method returns, contains the 64-bit unsigned integer value representing the channel ID contained within - /// , if the conversion succeeded, or zero if the conversion failed. The conversion fails if the - /// parameter is or , is not of the correct - /// format, or represents a number less than or greater than . - /// - /// if the parse was successful; otherwise, . - [CLSCompliant(false)] - public static bool TryParseChannel(string? value, out ulong result) - { - result = 0; - if (string.IsNullOrWhiteSpace(value)) - { - return false; - } - - if (value.Length < 3 || value[0] != '<' || value[1] != '#' || value[^1] != '>') - { - return false; - } - - value = value.Substring(2, value.Length - 3); // <#123> - return ulong.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out result); - } - - /// - /// Parses a provided role mention string to a decimal value representing the role ID. A return value indicates whether - /// the parse succeeded. - /// - /// A string containing a mention string to parse, in the format <@&123>. - /// - /// When this method returns, contains the decimal value representing the role ID contained within - /// , if the conversion succeeded, or zero if the conversion failed. The conversion fails if the - /// parameter is or , is not of the correct - /// format, or represents a number less than or greater than . - /// - /// if the parse was successful; otherwise, . - public static bool TryParseRole(string? value, out decimal result) - { - result = 0; - if (string.IsNullOrWhiteSpace(value)) - { - return false; - } - - if (value.Length < 4 || value[0] != '<' || value[1] != '@' || value[2] != '&' || value[^1] != '>') - { - return false; - } - - value = value.Substring(3, value.Length - 4); // <@&123> - if (!ulong.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out ulong actual)) - { - return false; - } - - result = actual; - return true; - } - - /// - /// Parses a provided role mention string to a 64-bit unsigned integer representing the role ID. A return value indicates - /// whether the parse succeeded. - /// - /// A string containing a mention string to parse, in the format <@&123>. - /// - /// When this method returns, contains the 64-bit unsigned integer value representing the role ID contained within - /// , if the conversion succeeded, or zero if the conversion failed. The conversion fails if the - /// parameter is or , is not of the correct - /// format, or represents a number less than or greater than . - /// - /// if the parse was successful; otherwise, . - [CLSCompliant(false)] - public static bool TryParseRole(string? value, out ulong result) - { - result = 0; - if (string.IsNullOrWhiteSpace(value)) - { - return false; - } - - if (value.Length < 4 || value[0] != '<' || value[1] != '@' || value[2] != '&' || value[^1] != '>') - { - return false; - } - - value = value.Substring(3, value.Length - 4); // <@&123> - return ulong.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out result); - } - - /// - /// Parses a provided user mention string to a decimal value representing the user ID. A return value indicates whether - /// the parse succeeded. - /// - /// - /// A string containing a mention string to parse, in the format <@123> or <@!123>. - /// - /// - /// When this method returns, contains the decimal value representing the user ID contained within - /// , if the conversion succeeded, or zero if the conversion failed. The conversion fails if the - /// parameter is or , is not of the correct - /// format, or represents a number less than or greater than . - /// - /// if the parse was successful; otherwise, . - public static bool TryParseUser(string? value, out decimal result) - { - result = 0; - if (string.IsNullOrWhiteSpace(value)) - { - return false; - } - - if (value.Length < 3 || value[0] != '<' || value[1] != '@' || value[^1] != '>') - { - return false; - } - - if (value.Length >= 4 && value[2] == '!') - { - value = value.Substring(3, value.Length - 4); // <@!123> - } - else - { - value = value.Substring(2, value.Length - 3); // <@123> - } - - if (!ulong.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out ulong actual)) - { - return false; - } - - result = actual; - return true; - } - - /// - /// Parses a provided user mention string to a 64-bit unsigned integer representing the user ID. A return value indicates - /// whether the parse succeeded. - /// - /// - /// A string containing a mention string to parse, in the format <@123> or <@!123>. - /// - /// - /// When this method returns, contains the 64-bit unsigned integer value representing the user ID contained within - /// , if the conversion succeeded, or zero if the conversion failed. The conversion fails if the - /// parameter is or , is not of the correct - /// format, or represents a number less than or greater than . - /// - /// if the parse was successful; otherwise, . - [CLSCompliant(false)] - public static bool TryParseUser(string? value, out ulong result) - { - result = 0; - if (string.IsNullOrWhiteSpace(value)) - { - return false; - } - - if (value.Length < 3 || value[0] != '<' || value[1] != '@' || value[^1] != '>') - { - return false; - } - - if (value.Length >= 4 && value[2] == '!') - { - value = value.Substring(3, value.Length - 4); // <@!123> - } - else - { - value = value.Substring(2, value.Length - 3); // <@123> - } - - return ulong.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out result); - } -} diff --git a/X10D.sln b/X10D.sln index b114966..d552642 100644 --- a/X10D.sln +++ b/X10D.sln @@ -25,8 +25,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "X10D.Unity", "X10D.Unity\X1 EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SourceGenerator", "tools\SourceGenerator\SourceGenerator.csproj", "{077A5D33-AD55-4C55-8A67-972CEBC32C7A}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "X10D.DSharpPlus", "X10D.DSharpPlus\X10D.DSharpPlus.csproj", "{675D3B25-7EA0-4FC3-B513-8DF27874F2CF}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "X10D.Hosting", "X10D.Hosting\X10D.Hosting.csproj", "{B04AF429-30CF-4B69-81BA-38F560CA9126}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Workflows", "Workflows", "{1FC74E58-F3BA-4F1A-8693-5F80895DA69D}" @@ -79,10 +77,6 @@ Global {077A5D33-AD55-4C55-8A67-972CEBC32C7A}.Debug|Any CPU.Build.0 = Debug|Any CPU {077A5D33-AD55-4C55-8A67-972CEBC32C7A}.Release|Any CPU.ActiveCfg = Release|Any CPU {077A5D33-AD55-4C55-8A67-972CEBC32C7A}.Release|Any CPU.Build.0 = Release|Any CPU - {675D3B25-7EA0-4FC3-B513-8DF27874F2CF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {675D3B25-7EA0-4FC3-B513-8DF27874F2CF}.Debug|Any CPU.Build.0 = Debug|Any CPU - {675D3B25-7EA0-4FC3-B513-8DF27874F2CF}.Release|Any CPU.ActiveCfg = Release|Any CPU - {675D3B25-7EA0-4FC3-B513-8DF27874F2CF}.Release|Any CPU.Build.0 = Release|Any CPU {B04AF429-30CF-4B69-81BA-38F560CA9126}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {B04AF429-30CF-4B69-81BA-38F560CA9126}.Debug|Any CPU.Build.0 = Debug|Any CPU {B04AF429-30CF-4B69-81BA-38F560CA9126}.Release|Any CPU.ActiveCfg = Release|Any CPU From 5b2c83e2eb138f9133eb73de2c757d71c7efeb9f Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Tue, 22 Aug 2023 22:40:49 +0100 Subject: [PATCH 082/102] chore: define TargetFrameworks in shared props --- Directory.Build.props | 1 + X10D.Hosting/X10D.Hosting.csproj | 4 ---- X10D/X10D.csproj | 4 ---- 3 files changed, 1 insertion(+), 8 deletions(-) diff --git a/Directory.Build.props b/Directory.Build.props index be302ef..3250f61 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,5 +1,6 @@ + net7.0;net6.0;netstandard2.1 11.0 true true diff --git a/X10D.Hosting/X10D.Hosting.csproj b/X10D.Hosting/X10D.Hosting.csproj index a534fa0..0d99bec 100644 --- a/X10D.Hosting/X10D.Hosting.csproj +++ b/X10D.Hosting/X10D.Hosting.csproj @@ -1,9 +1,5 @@ - - net7.0;net6.0;netstandard2.1 - - diff --git a/X10D/X10D.csproj b/X10D/X10D.csproj index 7994902..c288f87 100644 --- a/X10D/X10D.csproj +++ b/X10D/X10D.csproj @@ -1,9 +1,5 @@ - - net7.0;net6.0;netstandard2.1 - - True From 9c5ed12cadd9aaa202c06fae66af8a85fc027b36 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Tue, 22 Aug 2023 22:40:59 +0100 Subject: [PATCH 083/102] chore: enable NRT for tools --- tools/Directory.Build.props | 1 + 1 file changed, 1 insertion(+) diff --git a/tools/Directory.Build.props b/tools/Directory.Build.props index b933b03..39e3440 100644 --- a/tools/Directory.Build.props +++ b/tools/Directory.Build.props @@ -1,6 +1,7 @@  11.0 + enable true true From 0868b698c50e773cc8557d269262ceeb3e974443 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Tue, 22 Aug 2023 22:42:07 +0100 Subject: [PATCH 084/102] [ci skip] docs: fix README branding header in X10D.Unity --- X10D.Unity/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/X10D.Unity/README.md b/X10D.Unity/README.md index 2e4e1f6..888c724 100644 --- a/X10D.Unity/README.md +++ b/X10D.Unity/README.md @@ -1,4 +1,4 @@ -

+

GitHub Workflow Status From 457fbbb83c8a3979e06fd6f2e333df05f6402013 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Tue, 22 Aug 2023 22:42:23 +0100 Subject: [PATCH 085/102] [ci skip] docs: fix README branding header in X10D.Unity --- X10D.Unity/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/X10D.Unity/README.md b/X10D.Unity/README.md index 2e4e1f6..888c724 100644 --- a/X10D.Unity/README.md +++ b/X10D.Unity/README.md @@ -1,4 +1,4 @@ -

+

GitHub Workflow Status From bf0930ee1740105345fdd057feb234371d126fb0 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Tue, 22 Aug 2023 23:25:10 +0100 Subject: [PATCH 086/102] [ci skip] docs: update latest stable ref in X10D.Unity readme --- X10D.Unity/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/X10D.Unity/README.md b/X10D.Unity/README.md index 888c724..0b02dec 100644 --- a/X10D.Unity/README.md +++ b/X10D.Unity/README.md @@ -26,7 +26,7 @@ To install X10D in Unity, follow the steps blow: The [upm](https://github.com/oliverbooth/X10D/tree/upm) branch contains the latest nightly - that is the bleeding edge version of X10D. If you'd like to remain on a stable release, specify a commit hash after the `#` instead of `upm`. -The latest current stable is 3.2.0, which is commit [55898d9e70228380b2d039c55e36d89cfe8a0fa2](https://github.com/oliverbooth/X10D/commit/55898d9e70228380b2d039c55e36d89cfe8a0fa2). +The latest current stable is 3.3.1, which is commit [71a9c787e25bd89d8bb6f352e5585379a04103d3](https://github.com/oliverbooth/X10D/commit/71a9c787e25bd89d8bb6f352e5585379a04103d3). Keep in mind that referencing a specific commit rather than the `upm` branch will prevent the auto-updater in Unity from detecting new versions. ## Contributing From f57318a381efb1079f16cfe0f669c00cf6279642 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Tue, 22 Aug 2023 23:27:26 +0100 Subject: [PATCH 087/102] [ci skip] fix(docs): fix incorrect stable commit ref --- X10D.Unity/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/X10D.Unity/README.md b/X10D.Unity/README.md index 0b02dec..105de43 100644 --- a/X10D.Unity/README.md +++ b/X10D.Unity/README.md @@ -26,7 +26,7 @@ To install X10D in Unity, follow the steps blow: The [upm](https://github.com/oliverbooth/X10D/tree/upm) branch contains the latest nightly - that is the bleeding edge version of X10D. If you'd like to remain on a stable release, specify a commit hash after the `#` instead of `upm`. -The latest current stable is 3.3.1, which is commit [71a9c787e25bd89d8bb6f352e5585379a04103d3](https://github.com/oliverbooth/X10D/commit/71a9c787e25bd89d8bb6f352e5585379a04103d3). +The latest current stable is 3.3.1, which is commit [0bb35bb565fff170a3848acdffbb5d53087de64b](https://github.com/oliverbooth/X10D/commit/0bb35bb565fff170a3848acdffbb5d53087de64b). Keep in mind that referencing a specific commit rather than the `upm` branch will prevent the auto-updater in Unity from detecting new versions. ## Contributing From fa375e77580bb5e211c6a75f1c2c7fbd55d922be Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Tue, 22 Aug 2023 23:38:18 +0100 Subject: [PATCH 088/102] refactor: conditionally import System.Runtime.Intrinsics.X86 --- X10D.Tests/src/Collections/Int16Tests.cs | 4 +++- X10D.Tests/src/Collections/Int32Tests.cs | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/X10D.Tests/src/Collections/Int16Tests.cs b/X10D.Tests/src/Collections/Int16Tests.cs index 9e44f49..8672a0a 100644 --- a/X10D.Tests/src/Collections/Int16Tests.cs +++ b/X10D.Tests/src/Collections/Int16Tests.cs @@ -1,4 +1,6 @@ -using System.Runtime.Intrinsics.X86; +#if NET5_0_OR_GREATER +using System.Runtime.Intrinsics.X86; +#endif using NUnit.Framework; using X10D.Collections; diff --git a/X10D.Tests/src/Collections/Int32Tests.cs b/X10D.Tests/src/Collections/Int32Tests.cs index 219ecd3..97485e1 100644 --- a/X10D.Tests/src/Collections/Int32Tests.cs +++ b/X10D.Tests/src/Collections/Int32Tests.cs @@ -1,4 +1,6 @@ -using System.Runtime.Intrinsics.X86; +#if NET5_0_OR_GREATER +using System.Runtime.Intrinsics.X86; +#endif using NUnit.Framework; using X10D.Collections; From 15107ea90fde3dccaf9ee39793106587851cf36c Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Tue, 22 Aug 2023 23:53:13 +0100 Subject: [PATCH 089/102] docs: fix xmldoc for Line3D --- CHANGELOG.md | 4 ++++ X10D/src/Drawing/Line3D.cs | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c1d3e44..14b8711 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,6 +27,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - X10D.Unity: Added `RaycastHit.GetComponent` and `RaycastHit.TryGetComponent`. - X10D.Unity: Added `DebugUtility.DrawFunction`, and `DebugUtility.DrawUnjoinedPolyhedron` on which it relies. +### Fixed + +- X10D: Fixed XMLDoc for `Line3D` to read "single-precision floating-point" instead of "32-bit signed integer". + ### Changed - X10D: DateTime.Age(DateTime) and DateTimeOffset.Age(DateTimeOffset) parameter renamed from asOf to referenceDate. diff --git a/X10D/src/Drawing/Line3D.cs b/X10D/src/Drawing/Line3D.cs index d2e4177..9775c72 100644 --- a/X10D/src/Drawing/Line3D.cs +++ b/X10D/src/Drawing/Line3D.cs @@ -4,7 +4,7 @@ using System.Numerics; namespace X10D.Drawing; ///

-/// Represents a line in 3D space that is composed of 32-bit signed integer X, Y and Z coordinates. +/// Represents a line in 3D space that is composed of single-precision floating-point X, Y and Z coordinates. /// public readonly struct Line3D : IEquatable, IComparable, IComparable { From 5c21c86a5207cb935287657a19dd8d45b4528c34 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Wed, 23 Aug 2023 14:15:52 +0100 Subject: [PATCH 090/102] refactor!: replace Endianness enum with explicit Big/Little methods --- CHANGELOG.md | 3 + X10D.Tests/src/IO/DoubleTests.cs | 58 +- X10D.Tests/src/IO/Int16Tests.cs | 54 +- X10D.Tests/src/IO/Int32Tests.cs | 54 +- X10D.Tests/src/IO/Int64Tests.cs | 58 +- X10D.Tests/src/IO/SingleTests.cs | 58 +- X10D.Tests/src/IO/StreamTests.ReadDecimal.cs | 53 +- X10D.Tests/src/IO/StreamTests.ReadDouble.cs | 57 +- X10D.Tests/src/IO/StreamTests.ReadInt16.cs | 57 +- X10D.Tests/src/IO/StreamTests.ReadInt32.cs | 57 +- X10D.Tests/src/IO/StreamTests.ReadInt64.cs | 52 +- X10D.Tests/src/IO/StreamTests.ReadSingle.cs | 57 +- X10D.Tests/src/IO/StreamTests.ReadUInt16.cs | 57 +- X10D.Tests/src/IO/StreamTests.ReadUInt32.cs | 57 +- X10D.Tests/src/IO/StreamTests.ReadUInt64.cs | 57 +- X10D.Tests/src/IO/StreamTests.WriteDecimal.cs | 52 +- X10D.Tests/src/IO/StreamTests.WriteDouble.cs | 56 +- X10D.Tests/src/IO/StreamTests.WriteInt16.cs | 56 +- X10D.Tests/src/IO/StreamTests.WriteInt32.cs | 56 +- X10D.Tests/src/IO/StreamTests.WriteInt64.cs | 56 +- X10D.Tests/src/IO/StreamTests.WriteSingle.cs | 56 +- X10D.Tests/src/IO/StreamTests.WriteUInt16.cs | 56 +- X10D.Tests/src/IO/StreamTests.WriteUInt32.cs | 56 +- X10D.Tests/src/IO/StreamTests.WriteUInt64.cs | 56 +- X10D.Tests/src/IO/UInt16Tests.cs | 54 +- X10D.Tests/src/IO/UInt32Tests.cs | 54 +- X10D.Tests/src/IO/UInt64Tests.cs | 58 +- X10D/src/Endianness.cs | 19 - X10D/src/IO/DecimalExtensions.cs | 111 ++ X10D/src/IO/DoubleExtensions.cs | 82 +- X10D/src/IO/Int16Extensions.cs | 76 +- X10D/src/IO/Int32Extensions.cs | 60 +- X10D/src/IO/Int64Extensions.cs | 36 +- X10D/src/IO/SingleExtensions.cs | 70 +- X10D/src/IO/StreamExtensions.cs | 1585 ++++++++--------- X10D/src/IO/UInt16Extensions.cs | 40 +- X10D/src/IO/UInt32Extensions.cs | 40 +- X10D/src/IO/UInt64Extensions.cs | 36 +- 38 files changed, 1835 insertions(+), 1775 deletions(-) delete mode 100644 X10D/src/Endianness.cs create mode 100644 X10D/src/IO/DecimalExtensions.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 14b8711..1957cf2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -34,10 +34,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed - X10D: DateTime.Age(DateTime) and DateTimeOffset.Age(DateTimeOffset) parameter renamed from asOf to referenceDate. +- X10D: Methods which accepted the `Endianness` enum as an argument have been replaced with explicit +BigEndian/LittleEndian methods. ### Removed - X10D: Removed `IEnumerable.ConcatOne` - this functionality already exists with `Append`. +- X10D: Removed `Endianness` enum. - X10D.DSharpPlus: Complete sunset of library. This library will not be updated to support DSharpPlus v5.0.0. ## [3.3.1] - 2023-08-21 diff --git a/X10D.Tests/src/IO/DoubleTests.cs b/X10D.Tests/src/IO/DoubleTests.cs index f58e26c..9b8a43a 100644 --- a/X10D.Tests/src/IO/DoubleTests.cs +++ b/X10D.Tests/src/IO/DoubleTests.cs @@ -7,60 +7,60 @@ namespace X10D.Tests.IO; internal class DoubleTests { [Test] - public void GetBytes_ReturnsCorrectValue() + public void GetBigEndianBytes_ReturnsCorrectValue() { const double value = 42.5; - byte[] bytes = BitConverter.IsLittleEndian - ? new byte[] {0, 0, 0, 0, 0, 0x40, 0x45, 0x40} - : new byte[] {0x40, 0x45, 0x40, 0, 0, 0, 0, 0}; - CollectionAssert.AreEqual(bytes, value.GetBytes()); + + var expected = new byte[] { 0x40, 0x45, 0x40, 0, 0, 0, 0, 0 }; + byte[] actual = value.GetBigEndianBytes(); + CollectionAssert.AreEqual(expected, actual); } [Test] - public void GetBytes_ReturnsCorrectValue_WithEndianness() + public void GetLittleEndianBytes_ReturnsCorrectValue() { const double value = 42.5; - byte[] littleEndian = {0, 0, 0, 0, 0, 0x40, 0x45, 0x40}; - byte[] bigEndian = {0x40, 0x45, 0x40, 0, 0, 0, 0, 0}; - CollectionAssert.AreEqual(littleEndian, value.GetBytes(Endianness.LittleEndian)); - CollectionAssert.AreEqual(bigEndian, value.GetBytes(Endianness.BigEndian)); + var expected = new byte[] { 0, 0, 0, 0, 0, 0x40, 0x45, 0x40 }; + byte[] actual = value.GetLittleEndianBytes(); + CollectionAssert.AreEqual(expected, actual); } [Test] - public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan() + public void TryWriteBigEndian_ReturnsTrue_FillsSpanCorrectly() { const double value = 42.5; - byte[] bytes = BitConverter.IsLittleEndian - ? new byte[] {0, 0, 0, 0, 0, 0x40, 0x45, 0x40} - : new byte[] {0x40, 0x45, 0x40, 0, 0, 0, 0, 0}; - Span buffer = stackalloc byte[8]; - Assert.That(value.TryWriteBytes(buffer)); - CollectionAssert.AreEqual(bytes, buffer.ToArray()); + var expected = new byte[] { 0x40, 0x45, 0x40, 0, 0, 0, 0, 0 }; + Span actual = stackalloc byte[8]; + Assert.That(value.TryWriteBigEndian(actual)); + CollectionAssert.AreEqual(expected, actual.ToArray()); } [Test] - public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan_WithEndianness() + public void TryWriteLittleEndian_ReturnsTrue_FillsSpanCorrectly() { const double value = 42.5; - byte[] littleEndian = {0, 0, 0, 0, 0, 0x40, 0x45, 0x40}; - byte[] bigEndian = {0x40, 0x45, 0x40, 0, 0, 0, 0, 0}; - Span buffer = stackalloc byte[8]; - - Assert.That(value.TryWriteBytes(buffer, Endianness.LittleEndian)); - CollectionAssert.AreEqual(littleEndian, buffer.ToArray()); - - Assert.That(value.TryWriteBytes(buffer, Endianness.BigEndian)); - CollectionAssert.AreEqual(bigEndian, buffer.ToArray()); + var expected = new byte[] { 0, 0, 0, 0, 0, 0x40, 0x45, 0x40 }; + Span actual = stackalloc byte[8]; + Assert.That(value.TryWriteLittleEndian(actual)); + CollectionAssert.AreEqual(expected, actual.ToArray()); } [Test] - public void TryWriteBytes_ReturnsFalse_GivenSmallSpan() + public void TryWriteBigEndian_ReturnsFalse_GivenSmallSpan() { const double value = 42.5; Span buffer = stackalloc byte[0]; - Assert.That(value.TryWriteBytes(buffer), Is.False); + Assert.That(value.TryWriteBigEndian(buffer), Is.False); + } + + [Test] + public void TryWriteLittleEndian_RReturnsFalse_GivenSmallSpan() + { + const double value = 42.5; + Span buffer = stackalloc byte[0]; + Assert.That(value.TryWriteLittleEndian(buffer), Is.False); } } diff --git a/X10D.Tests/src/IO/Int16Tests.cs b/X10D.Tests/src/IO/Int16Tests.cs index 11d6bb1..8d64f97 100644 --- a/X10D.Tests/src/IO/Int16Tests.cs +++ b/X10D.Tests/src/IO/Int16Tests.cs @@ -7,56 +7,60 @@ namespace X10D.Tests.IO; internal class Int16Tests { [Test] - public void GetBytes_ReturnsCorrectValue() + public void GetLittleEndianBytes_ReturnsCorrectValue() { const short value = 0x0F; - byte[] bytes = BitConverter.IsLittleEndian ? new byte[] {0x0F, 0} : new byte[] {0, 0x0F}; - CollectionAssert.AreEqual(bytes, value.GetBytes()); + + byte[] expected = { 0x0F, 0 }; + byte[] actual = value.GetLittleEndianBytes(); + CollectionAssert.AreEqual(expected, actual); } [Test] - public void GetBytes_ReturnsCorrectValue_WithEndianness() + public void GetBigEndianBytes_ReturnsCorrectValue() { const short value = 0x0F; - byte[] littleEndian = {0x0F, 0}; - byte[] bigEndian = {0, 0x0F}; - CollectionAssert.AreEqual(littleEndian, value.GetBytes(Endianness.LittleEndian)); - CollectionAssert.AreEqual(bigEndian, value.GetBytes(Endianness.BigEndian)); + byte[] expected = { 0, 0x0F }; + byte[] actual = value.GetBigEndianBytes(); + CollectionAssert.AreEqual(expected, actual); } [Test] - public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan() + public void TryWriteLittleEndian_ReturnsTrue_FillsSpanCorrectly() { const short value = 0x0F; - byte[] bytes = BitConverter.IsLittleEndian ? new byte[] {0x0F, 0} : new byte[] {0, 0x0F}; - Span buffer = stackalloc byte[2]; - Assert.That(value.TryWriteBytes(buffer)); - CollectionAssert.AreEqual(bytes, buffer.ToArray()); + byte[] expected = { 0x0F, 0 }; + Span actual = stackalloc byte[2]; + Assert.That(value.TryWriteLittleEndian(actual)); + CollectionAssert.AreEqual(expected, actual.ToArray()); } [Test] - public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan_WithEndianness() + public void TryWriteBigEndian_ReturnsTrue_FillsSpanCorrectly() { const short value = 0x0F; - byte[] littleEndian = {0x0F, 0}; - byte[] bigEndian = {0, 0x0F}; - Span buffer = stackalloc byte[2]; - - Assert.That(value.TryWriteBytes(buffer, Endianness.LittleEndian)); - CollectionAssert.AreEqual(littleEndian, buffer.ToArray()); - - Assert.That(value.TryWriteBytes(buffer, Endianness.BigEndian)); - CollectionAssert.AreEqual(bigEndian, buffer.ToArray()); + byte[] expected = { 0, 0x0F }; + Span actual = stackalloc byte[2]; + Assert.That(value.TryWriteBigEndian(actual)); + CollectionAssert.AreEqual(expected, actual.ToArray()); } [Test] - public void TryWriteBytes_ReturnsFalse_GivenSmallSpan() + public void TryWriteLittleEndian_RReturnsFalse_GivenSmallSpan() { const short value = 0x0F; Span buffer = stackalloc byte[0]; - Assert.That(value.TryWriteBytes(buffer), Is.False); + Assert.That(value.TryWriteLittleEndian(buffer), Is.False); + } + + [Test] + public void TryWriteBigEndian_ReturnsFalse_GivenSmallSpan() + { + const short value = 0x0F; + Span buffer = stackalloc byte[0]; + Assert.That(value.TryWriteBigEndian(buffer), Is.False); } } diff --git a/X10D.Tests/src/IO/Int32Tests.cs b/X10D.Tests/src/IO/Int32Tests.cs index c123980..31898a0 100644 --- a/X10D.Tests/src/IO/Int32Tests.cs +++ b/X10D.Tests/src/IO/Int32Tests.cs @@ -7,56 +7,60 @@ namespace X10D.Tests.IO; internal class Int32Tests { [Test] - public void GetBytes_ReturnsCorrectValue() + public void GetBigEndianBytes_ReturnsCorrectValue() { const int value = 0x0F; - byte[] bytes = BitConverter.IsLittleEndian ? new byte[] {0x0F, 0, 0, 0} : new byte[] {0, 0, 0, 0x0F}; - CollectionAssert.AreEqual(bytes, value.GetBytes()); + + var expected = new byte[] { 0, 0, 0, 0x0F }; + byte[] actual = value.GetBigEndianBytes(); + CollectionAssert.AreEqual(expected, actual); } [Test] - public void GetBytes_ReturnsCorrectValue_WithEndianness() + public void GetLittleEndianBytes_ReturnsCorrectValue() { const int value = 0x0F; - byte[] littleEndian = {0x0F, 0, 0, 0}; - byte[] bigEndian = {0, 0, 0, 0x0F}; - CollectionAssert.AreEqual(littleEndian, value.GetBytes(Endianness.LittleEndian)); - CollectionAssert.AreEqual(bigEndian, value.GetBytes(Endianness.BigEndian)); + var expected = new byte[] { 0x0F, 0, 0, 0 }; + byte[] actual = value.GetLittleEndianBytes(); + CollectionAssert.AreEqual(expected, actual); } [Test] - public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan() + public void TryWriteBigEndian_ReturnsTrue_FillsSpanCorrectly() { const int value = 0x0F; - byte[] bytes = BitConverter.IsLittleEndian ? new byte[] {0x0F, 0, 0, 0} : new byte[] {0, 0, 0, 0x0F}; - Span buffer = stackalloc byte[4]; - Assert.That(value.TryWriteBytes(buffer)); - CollectionAssert.AreEqual(bytes, buffer.ToArray()); + var expected = new byte[] { 0, 0, 0, 0x0F }; + Span actual = stackalloc byte[4]; + Assert.That(value.TryWriteBigEndian(actual)); + CollectionAssert.AreEqual(expected, actual.ToArray()); } [Test] - public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan_WithEndianness() + public void TryWriteLittleEndian_ReturnsTrue_FillsSpanCorrectly() { const int value = 0x0F; - byte[] littleEndian = {0x0F, 0, 0, 0}; - byte[] bigEndian = {0, 0, 0, 0x0F}; - Span buffer = stackalloc byte[4]; - - Assert.That(value.TryWriteBytes(buffer, Endianness.LittleEndian)); - CollectionAssert.AreEqual(littleEndian, buffer.ToArray()); - - Assert.That(value.TryWriteBytes(buffer, Endianness.BigEndian)); - CollectionAssert.AreEqual(bigEndian, buffer.ToArray()); + var expected = new byte[] { 0x0F, 0, 0, 0 }; + Span actual = stackalloc byte[4]; + Assert.That(value.TryWriteLittleEndian(actual)); + CollectionAssert.AreEqual(expected, actual.ToArray()); } [Test] - public void TryWriteBytes_ReturnsFalse_GivenSmallSpan() + public void TryWriteBigEndian_ReturnsFalse_GivenSmallSpan() { const int value = 0x0F; Span buffer = stackalloc byte[0]; - Assert.That(value.TryWriteBytes(buffer), Is.False); + Assert.That(value.TryWriteBigEndian(buffer), Is.False); + } + + [Test] + public void TryWriteLittleEndian_RReturnsFalse_GivenSmallSpan() + { + const int value = 0x0F; + Span buffer = stackalloc byte[0]; + Assert.That(value.TryWriteLittleEndian(buffer), Is.False); } } diff --git a/X10D.Tests/src/IO/Int64Tests.cs b/X10D.Tests/src/IO/Int64Tests.cs index 6183d13..393b9e0 100644 --- a/X10D.Tests/src/IO/Int64Tests.cs +++ b/X10D.Tests/src/IO/Int64Tests.cs @@ -7,60 +7,60 @@ namespace X10D.Tests.IO; internal class Int64Tests { [Test] - public void GetBytes_ReturnsCorrectValue() + public void GetLittleEndianBytes_ReturnsCorrectValue() { const long value = 0x0F; - byte[] bytes = BitConverter.IsLittleEndian - ? new byte[] {0x0F, 0, 0, 0, 0, 0, 0, 0} - : new byte[] {0, 0, 0, 0, 0, 0, 0, 0x0F}; - CollectionAssert.AreEqual(bytes, value.GetBytes()); + + byte[] expected = { 0x0F, 0, 0, 0, 0, 0, 0, 0 }; + byte[] actual = value.GetLittleEndianBytes(); + CollectionAssert.AreEqual(expected, actual); } [Test] - public void GetBytes_ReturnsCorrectValue_WithEndianness() + public void GetBigEndianBytes_ReturnsCorrectValue() { const long value = 0x0F; - byte[] littleEndian = {0x0F, 0, 0, 0, 0, 0, 0, 0}; - byte[] bigEndian = {0, 0, 0, 0, 0, 0, 0, 0x0F}; - CollectionAssert.AreEqual(littleEndian, value.GetBytes(Endianness.LittleEndian)); - CollectionAssert.AreEqual(bigEndian, value.GetBytes(Endianness.BigEndian)); + byte[] expected = { 0, 0, 0, 0, 0, 0, 0, 0x0F }; + byte[] actual = value.GetBigEndianBytes(); + CollectionAssert.AreEqual(expected, actual); } [Test] - public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan() + public void TryWriteLittleEndian_ReturnsTrue_FillsSpanCorrectly() { const long value = 0x0F; - byte[] bytes = BitConverter.IsLittleEndian - ? new byte[] {0x0F, 0, 0, 0, 0, 0, 0, 0} - : new byte[] {0, 0, 0, 0, 0, 0, 0, 0x0F}; - Span buffer = stackalloc byte[8]; - Assert.That(value.TryWriteBytes(buffer)); - CollectionAssert.AreEqual(bytes, buffer.ToArray()); + byte[] expected = { 0x0F, 0, 0, 0, 0, 0, 0, 0 }; + Span actual = stackalloc byte[8]; + Assert.That(value.TryWriteLittleEndian(actual)); + CollectionAssert.AreEqual(expected, actual.ToArray()); } [Test] - public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan_WithEndianness() + public void TryWriteBigEndian_ReturnsTrue_FillsSpanCorrectly() { const long value = 0x0F; - byte[] littleEndian = {0x0F, 0, 0, 0, 0, 0, 0, 0}; - byte[] bigEndian = {0, 0, 0, 0, 0, 0, 0, 0x0F}; - Span buffer = stackalloc byte[8]; - - Assert.That(value.TryWriteBytes(buffer, Endianness.LittleEndian)); - CollectionAssert.AreEqual(littleEndian, buffer.ToArray()); - - Assert.That(value.TryWriteBytes(buffer, Endianness.BigEndian)); - CollectionAssert.AreEqual(bigEndian, buffer.ToArray()); + byte[] expected = { 0, 0, 0, 0, 0, 0, 0, 0x0F }; + Span actual = stackalloc byte[8]; + Assert.That(value.TryWriteBigEndian(actual)); + CollectionAssert.AreEqual(expected, actual.ToArray()); } [Test] - public void TryWriteBytes_ReturnsFalse_GivenSmallSpan() + public void TryWriteLittleEndian_RReturnsFalse_GivenSmallSpan() { const long value = 0x0F; Span buffer = stackalloc byte[0]; - Assert.That(value.TryWriteBytes(buffer), Is.False); + Assert.That(value.TryWriteLittleEndian(buffer), Is.False); + } + + [Test] + public void TryWriteBigEndian_ReturnsFalse_GivenSmallSpan() + { + const long value = 0x0F; + Span buffer = stackalloc byte[0]; + Assert.That(value.TryWriteBigEndian(buffer), Is.False); } } diff --git a/X10D.Tests/src/IO/SingleTests.cs b/X10D.Tests/src/IO/SingleTests.cs index 5f753c4..e7de74d 100644 --- a/X10D.Tests/src/IO/SingleTests.cs +++ b/X10D.Tests/src/IO/SingleTests.cs @@ -7,60 +7,60 @@ namespace X10D.Tests.IO; internal class SingleTests { [Test] - public void GetBytes_ReturnsCorrectValue() + public void GetBigEndianBytes_ReturnsCorrectValue() { const float value = 42.5f; - byte[] bytes = BitConverter.IsLittleEndian - ? new byte[] {0, 0, 0x2A, 0x42} - : new byte[] {0x42, 0x2A, 0, 0}; - CollectionAssert.AreEqual(bytes, value.GetBytes()); + + var expected = new byte[] { 0x42, 0x2A, 0, 0 }; + byte[] actual = value.GetBigEndianBytes(); + CollectionAssert.AreEqual(expected, actual); } [Test] - public void GetBytes_ReturnsCorrectValue_WithEndianness() + public void GetLittleEndianBytes_ReturnsCorrectValue() { const float value = 42.5f; - byte[] littleEndian = {0, 0, 0x2A, 0x42}; - byte[] bigEndian = {0x42, 0x2A, 0, 0}; - CollectionAssert.AreEqual(littleEndian, value.GetBytes(Endianness.LittleEndian)); - CollectionAssert.AreEqual(bigEndian, value.GetBytes(Endianness.BigEndian)); + var expected = new byte[] { 0, 0, 0x2A, 0x42 }; + byte[] actual = value.GetLittleEndianBytes(); + CollectionAssert.AreEqual(expected, actual); } [Test] - public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan() + public void TryWriteBigEndian_ReturnsTrue_FillsSpanCorrectly() { const float value = 42.5f; - byte[] bytes = BitConverter.IsLittleEndian - ? new byte[] {0, 0, 0x2A, 0x42} - : new byte[] {0x42, 0x2A, 0, 0}; - Span buffer = stackalloc byte[4]; - Assert.That(value.TryWriteBytes(buffer)); - CollectionAssert.AreEqual(bytes, buffer.ToArray()); + var expected = new byte[] { 0x42, 0x2A, 0, 0 }; + Span actual = stackalloc byte[4]; + Assert.That(value.TryWriteBigEndian(actual)); + CollectionAssert.AreEqual(expected, actual.ToArray()); } [Test] - public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan_WithEndianness() + public void TryWriteLittleEndian_ReturnsTrue_FillsSpanCorrectly() { const float value = 42.5f; - byte[] littleEndian = {0, 0, 0x2A, 0x42}; - byte[] bigEndian = {0x42, 0x2A, 0, 0}; - Span buffer = stackalloc byte[4]; - - Assert.That(value.TryWriteBytes(buffer, Endianness.LittleEndian)); - CollectionAssert.AreEqual(littleEndian, buffer.ToArray()); - - Assert.That(value.TryWriteBytes(buffer, Endianness.BigEndian)); - CollectionAssert.AreEqual(bigEndian, buffer.ToArray()); + var expected = new byte[] { 0, 0, 0x2A, 0x42 }; + Span actual = stackalloc byte[4]; + Assert.That(value.TryWriteLittleEndian(actual)); + CollectionAssert.AreEqual(expected, actual.ToArray()); } [Test] - public void TryWriteBytes_ReturnsFalse_GivenSmallSpan() + public void TryWriteBigEndian_ReturnsFalse_GivenSmallSpan() { const float value = 42.5f; Span buffer = stackalloc byte[0]; - Assert.That(value.TryWriteBytes(buffer), Is.False); + Assert.That(value.TryWriteBigEndian(buffer), Is.False); + } + + [Test] + public void TryWriteLittleEndian_RReturnsFalse_GivenSmallSpan() + { + const float value = 42.5f; + Span buffer = stackalloc byte[0]; + Assert.That(value.TryWriteLittleEndian(buffer), Is.False); } } diff --git a/X10D.Tests/src/IO/StreamTests.ReadDecimal.cs b/X10D.Tests/src/IO/StreamTests.ReadDecimal.cs index 7f61b76..c7fcdb5 100644 --- a/X10D.Tests/src/IO/StreamTests.ReadDecimal.cs +++ b/X10D.Tests/src/IO/StreamTests.ReadDecimal.cs @@ -1,4 +1,5 @@ -using NUnit.Framework; +using System.Diagnostics.CodeAnalysis; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; @@ -6,37 +7,37 @@ namespace X10D.Tests.IO; internal partial class StreamTests { [Test] - public void ReadDecimal_ShouldThrowArgumentException_GivenNonReadableStream() - { - Stream stream = new DummyStream(); - Assert.Throws(() => stream.ReadDecimal()); - Assert.Throws(() => stream.ReadDecimal(Endianness.LittleEndian)); - Assert.Throws(() => stream.ReadDecimal(Endianness.BigEndian)); - } - - [Test] - public void ReadDecimal_ShouldThrowArgumentNullException_GivenNullStream() + public void ReadDecimalBigEndian_ShouldThrowArgumentNullException_GivenNullStream() { Stream stream = null!; - Assert.Throws(() => stream.ReadDecimal()); - Assert.Throws(() => stream.ReadDecimal(Endianness.LittleEndian)); - Assert.Throws(() => stream.ReadDecimal(Endianness.BigEndian)); + Assert.Throws(() => stream.ReadDecimalBigEndian()); } [Test] - public void ReadDecimal_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() + public void ReadDecimalLittleEndian_ShouldThrowArgumentNullException_GivenNullStream() { - // we don't need to enclose this stream in a using declaration, since disposing a - // null stream is meaningless. NullStream.Dispose actually does nothing, anyway. - // that - coupled with the fact that encapsulating the stream in a using declaration causes the - // analyser to trip up and think the stream is disposed by the time the local is captured in - // assertion lambda - means this line is fine as it is. please do not change. - Stream stream = Stream.Null; - Assert.Throws(() => stream.ReadDecimal((Endianness)(-1))); + Stream stream = null!; + Assert.Throws(() => stream.ReadDecimalLittleEndian()); } [Test] - public void ReadDecimal_ShouldReadBigEndian_GivenBigEndian() + [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] + public void ReadDecimalBigEndian_ShouldThrowArgumentException_GivenNonReadableStream() + { + Stream stream = new DummyStream(); + Assert.Throws(() => stream.ReadDecimalBigEndian()); + } + + [Test] + [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] + public void ReadDecimalLittleEndian_ShouldThrowArgumentException_GivenNonReadableStream() + { + Stream stream = new DummyStream(); + Assert.Throws(() => stream.ReadDecimalLittleEndian()); + } + + [Test] + public void ReadDecimalBigEndian_ShouldReadBigEndian() { using var stream = new MemoryStream(); ReadOnlySpan bytes = stackalloc byte[] @@ -47,7 +48,7 @@ internal partial class StreamTests stream.Position = 0; const decimal expected = 420.0m; - decimal actual = stream.ReadDecimal(Endianness.BigEndian); + decimal actual = stream.ReadDecimalBigEndian(); Assert.Multiple(() => { @@ -57,7 +58,7 @@ internal partial class StreamTests } [Test] - public void ReadDecimal_ShouldWriteLittleEndian_GivenLittleEndian() + public void ReadDecimalLittleEndian_ShouldWriteLittleEndian() { using var stream = new MemoryStream(); ReadOnlySpan bytes = stackalloc byte[] @@ -68,7 +69,7 @@ internal partial class StreamTests stream.Position = 0; const decimal expected = 420.0m; - decimal actual = stream.ReadDecimal(Endianness.LittleEndian); + decimal actual = stream.ReadDecimalLittleEndian(); Assert.Multiple(() => { diff --git a/X10D.Tests/src/IO/StreamTests.ReadDouble.cs b/X10D.Tests/src/IO/StreamTests.ReadDouble.cs index b400ac1..02f7991 100644 --- a/X10D.Tests/src/IO/StreamTests.ReadDouble.cs +++ b/X10D.Tests/src/IO/StreamTests.ReadDouble.cs @@ -1,4 +1,5 @@ -using NUnit.Framework; +using System.Diagnostics.CodeAnalysis; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; @@ -6,60 +7,60 @@ namespace X10D.Tests.IO; internal partial class StreamTests { [Test] - public void ReadDouble_ShouldThrowArgumentException_GivenNonReadableStream() - { - Stream stream = new DummyStream(); - Assert.Throws(() => stream.ReadDouble()); - Assert.Throws(() => stream.ReadDouble(Endianness.LittleEndian)); - Assert.Throws(() => stream.ReadDouble(Endianness.BigEndian)); - } - - [Test] - public void ReadDouble_ShouldThrowArgumentNullException_GivenNullStream() + public void ReadDoubleBigEndian_ShouldThrowArgumentNullException_GivenNullStream() { Stream stream = null!; - Assert.Throws(() => stream.ReadDouble()); - Assert.Throws(() => stream.ReadDouble(Endianness.LittleEndian)); - Assert.Throws(() => stream.ReadDouble(Endianness.BigEndian)); + Assert.Throws(() => stream.ReadDoubleBigEndian()); } [Test] - public void ReadDouble_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() + public void ReadDoubleLittleEndian_ShouldThrowArgumentNullException_GivenNullStream() { - // we don't need to enclose this stream in a using declaration, since disposing a - // null stream is meaningless. NullStream.Dispose actually does nothing, anyway. - // that - coupled with the fact that encapsulating the stream in a using declaration causes the - // analyser to trip up and think the stream is disposed by the time the local is captured in - // assertion lambda - means this line is fine as it is. please do not change. - Stream stream = Stream.Null; - Assert.Throws(() => stream.ReadDouble((Endianness)(-1))); + Stream stream = null!; + Assert.Throws(() => stream.ReadDoubleLittleEndian()); } [Test] - public void ReadDouble_ShouldReadBigEndian_GivenBigEndian() + [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] + public void ReadDoubleBigEndian_ShouldThrowArgumentException_GivenNonReadableStream() + { + Stream stream = new DummyStream(); + Assert.Throws(() => stream.ReadDoubleBigEndian()); + } + + [Test] + [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] + public void ReadDoubleLittleEndian_ShouldThrowArgumentException_GivenNonReadableStream() + { + Stream stream = new DummyStream(); + Assert.Throws(() => stream.ReadDoubleLittleEndian()); + } + + [Test] + public void ReadDoubleBigEndian_ShouldReadBigEndian() { using var stream = new MemoryStream(); - ReadOnlySpan bytes = stackalloc byte[] {0x40, 0x7A, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00}; + ReadOnlySpan bytes = stackalloc byte[] { 0x40, 0x7A, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00 }; stream.Write(bytes); stream.Position = 0; const double expected = 420.0; - double actual = stream.ReadDouble(Endianness.BigEndian); + double actual = stream.ReadDoubleBigEndian(); Assert.That(stream.Position, Is.EqualTo(8)); Assert.That(actual, Is.EqualTo(expected)); } [Test] - public void ReadDouble_ShouldWriteLittleEndian_GivenLittleEndian() + public void ReadDoubleLittleEndian_ShouldWriteLittleEndian() { using var stream = new MemoryStream(); - ReadOnlySpan bytes = stackalloc byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x7A, 0x40}; + ReadOnlySpan bytes = stackalloc byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x7A, 0x40 }; stream.Write(bytes); stream.Position = 0; const double expected = 420.0; - double actual = stream.ReadDouble(Endianness.LittleEndian); + double actual = stream.ReadDoubleLittleEndian(); Assert.That(stream.Position, Is.EqualTo(8)); Assert.That(actual, Is.EqualTo(expected)); diff --git a/X10D.Tests/src/IO/StreamTests.ReadInt16.cs b/X10D.Tests/src/IO/StreamTests.ReadInt16.cs index 950f368..a71d4bd 100644 --- a/X10D.Tests/src/IO/StreamTests.ReadInt16.cs +++ b/X10D.Tests/src/IO/StreamTests.ReadInt16.cs @@ -1,4 +1,5 @@ -using NUnit.Framework; +using System.Diagnostics.CodeAnalysis; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; @@ -6,60 +7,60 @@ namespace X10D.Tests.IO; internal partial class StreamTests { [Test] - public void ReadInt16_ShouldThrowArgumentException_GivenNonReadableStream() - { - Stream stream = new DummyStream(); - Assert.Throws(() => stream.ReadInt16()); - Assert.Throws(() => stream.ReadInt16(Endianness.LittleEndian)); - Assert.Throws(() => stream.ReadInt16(Endianness.BigEndian)); - } - - [Test] - public void ReadInt16_ShouldThrowArgumentNullException_GivenNullStream() + public void ReadInt16BigEndian_ShouldThrowArgumentNullException_GivenNullStream() { Stream stream = null!; - Assert.Throws(() => stream.ReadInt16()); - Assert.Throws(() => stream.ReadInt16(Endianness.LittleEndian)); - Assert.Throws(() => stream.ReadInt16(Endianness.BigEndian)); + Assert.Throws(() => stream.ReadInt16BigEndian()); } [Test] - public void ReadInt16_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() + public void ReadInt16LittleEndian_ShouldThrowArgumentNullException_GivenNullStream() { - // we don't need to enclose this stream in a using declaration, since disposing a - // null stream is meaningless. NullStream.Dispose actually does nothing, anyway. - // that - coupled with the fact that encapsulating the stream in a using declaration causes the - // analyser to trip up and think the stream is disposed by the time the local is captured in - // assertion lambda - means this line is fine as it is. please do not change. - Stream stream = Stream.Null; - Assert.Throws(() => stream.ReadInt16((Endianness)(-1))); + Stream stream = null!; + Assert.Throws(() => stream.ReadInt16LittleEndian()); } [Test] - public void ReadInt16_ShouldReadBigEndian_GivenBigEndian() + [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] + public void ReadInt16BigEndian_ShouldThrowArgumentException_GivenNonReadableStream() + { + Stream stream = new DummyStream(); + Assert.Throws(() => stream.ReadInt16BigEndian()); + } + + [Test] + [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] + public void ReadInt16LittleEndian_ShouldThrowArgumentException_GivenNonReadableStream() + { + Stream stream = new DummyStream(); + Assert.Throws(() => stream.ReadInt16LittleEndian()); + } + + [Test] + public void ReadInt16BigEndian_ShouldReadBigEndian() { using var stream = new MemoryStream(); - ReadOnlySpan bytes = stackalloc byte[] {0x01, 0xA4}; + ReadOnlySpan bytes = stackalloc byte[] { 0x01, 0xA4 }; stream.Write(bytes); stream.Position = 0; const short expected = 420; - short actual = stream.ReadInt16(Endianness.BigEndian); + short actual = stream.ReadInt16BigEndian(); Assert.That(stream.Position, Is.EqualTo(2)); Assert.That(actual, Is.EqualTo(expected)); } [Test] - public void ReadInt16_ShouldReadLittleEndian_GivenLittleEndian() + public void ReadInt16LittleEndian_ShouldReadLittleEndian() { using var stream = new MemoryStream(); - ReadOnlySpan bytes = stackalloc byte[] {0xA4, 0x01}; + ReadOnlySpan bytes = stackalloc byte[] { 0xA4, 0x01 }; stream.Write(bytes); stream.Position = 0; const short expected = 420; - short actual = stream.ReadInt16(Endianness.LittleEndian); + short actual = stream.ReadInt16LittleEndian(); Assert.That(stream.Position, Is.EqualTo(2)); Assert.That(actual, Is.EqualTo(expected)); diff --git a/X10D.Tests/src/IO/StreamTests.ReadInt32.cs b/X10D.Tests/src/IO/StreamTests.ReadInt32.cs index 8b45594..e51ef95 100644 --- a/X10D.Tests/src/IO/StreamTests.ReadInt32.cs +++ b/X10D.Tests/src/IO/StreamTests.ReadInt32.cs @@ -1,4 +1,5 @@ -using NUnit.Framework; +using System.Diagnostics.CodeAnalysis; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; @@ -6,60 +7,60 @@ namespace X10D.Tests.IO; internal partial class StreamTests { [Test] - public void ReadInt32_ShouldThrowArgumentException_GivenNonReadableStream() - { - Stream stream = new DummyStream(); - Assert.Throws(() => stream.ReadInt32()); - Assert.Throws(() => stream.ReadInt32(Endianness.LittleEndian)); - Assert.Throws(() => stream.ReadInt32(Endianness.BigEndian)); - } - - [Test] - public void ReadInt32_ShouldThrowArgumentNullException_GivenNullStream() + public void ReadInt32BigEndian_ShouldThrowArgumentNullException_GivenNullStream() { Stream stream = null!; - Assert.Throws(() => stream.ReadInt32()); - Assert.Throws(() => stream.ReadInt32(Endianness.LittleEndian)); - Assert.Throws(() => stream.ReadInt32(Endianness.BigEndian)); + Assert.Throws(() => stream.ReadInt32BigEndian()); } [Test] - public void ReadInt32_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() + public void ReadInt32LittleEndian_ShouldThrowArgumentNullException_GivenNullStream() { - // we don't need to enclose this stream in a using declaration, since disposing a - // null stream is meaningless. NullStream.Dispose actually does nothing, anyway. - // that - coupled with the fact that encapsulating the stream in a using declaration causes the - // analyser to trip up and think the stream is disposed by the time the local is captured in - // assertion lambda - means this line is fine as it is. please do not change. - Stream stream = Stream.Null; - Assert.Throws(() => stream.ReadInt32((Endianness)(-1))); + Stream stream = null!; + Assert.Throws(() => stream.ReadInt32LittleEndian()); } [Test] - public void ReadInt32_ShouldReadBigEndian_GivenBigEndian() + [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] + public void ReadInt32BigEndian_ShouldThrowArgumentException_GivenNonReadableStream() + { + Stream stream = new DummyStream(); + Assert.Throws(() => stream.ReadInt32BigEndian()); + } + + [Test] + [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] + public void ReadInt32LittleEndian_ShouldThrowArgumentException_GivenNonReadableStream() + { + Stream stream = new DummyStream(); + Assert.Throws(() => stream.ReadInt32LittleEndian()); + } + + [Test] + public void ReadInt32BigEndian_ShouldReadBigEndian() { using var stream = new MemoryStream(); - ReadOnlySpan bytes = stackalloc byte[] {0x00, 0x00, 0x01, 0xA4}; + ReadOnlySpan bytes = stackalloc byte[] { 0x00, 0x00, 0x01, 0xA4 }; stream.Write(bytes); stream.Position = 0; const int expected = 420; - int actual = stream.ReadInt32(Endianness.BigEndian); + int actual = stream.ReadInt32BigEndian(); Assert.That(stream.Position, Is.EqualTo(4)); Assert.That(actual, Is.EqualTo(expected)); } [Test] - public void ReadInt32_ShouldReadLittleEndian_GivenLittleEndian() + public void ReadInt32LittleEndian_ShouldReadLittleEndian() { using var stream = new MemoryStream(); - ReadOnlySpan bytes = stackalloc byte[] {0xA4, 0x01, 0x00, 0x00}; + ReadOnlySpan bytes = stackalloc byte[] { 0xA4, 0x01, 0x00, 0x00 }; stream.Write(bytes); stream.Position = 0; const int expected = 420; - int actual = stream.ReadInt32(Endianness.LittleEndian); + int actual = stream.ReadInt32LittleEndian(); Assert.That(stream.Position, Is.EqualTo(4)); Assert.That(actual, Is.EqualTo(expected)); diff --git a/X10D.Tests/src/IO/StreamTests.ReadInt64.cs b/X10D.Tests/src/IO/StreamTests.ReadInt64.cs index d094a56..faebfda 100644 --- a/X10D.Tests/src/IO/StreamTests.ReadInt64.cs +++ b/X10D.Tests/src/IO/StreamTests.ReadInt64.cs @@ -6,60 +6,58 @@ namespace X10D.Tests.IO; internal partial class StreamTests { [Test] - public void ReadInt64_ShouldThrowArgumentException_GivenNonReadableStream() - { - Stream stream = new DummyStream(); - Assert.Throws(() => stream.ReadInt64()); - Assert.Throws(() => stream.ReadInt64(Endianness.LittleEndian)); - Assert.Throws(() => stream.ReadInt64(Endianness.BigEndian)); - } - - [Test] - public void ReadInt64_ShouldThrowArgumentNullException_GivenNullStream() + public void ReadInt64BigEndian_ShouldThrowArgumentNullException_GivenNullStream() { Stream stream = null!; - Assert.Throws(() => stream.ReadInt64()); - Assert.Throws(() => stream.ReadInt64(Endianness.LittleEndian)); - Assert.Throws(() => stream.ReadInt64(Endianness.BigEndian)); + Assert.Throws(() => stream.ReadInt64BigEndian()); } [Test] - public void ReadInt64_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() + public void ReadInt64LittleEndian_ShouldThrowArgumentNullException_GivenNullStream() { - // we don't need to enclose this stream in a using declaration, since disposing a - // null stream is meaningless. NullStream.Dispose actually does nothing, anyway. - // that - coupled with the fact that encapsulating the stream in a using declaration causes the - // analyser to trip up and think the stream is disposed by the time the local is captured in - // assertion lambda - means this line is fine as it is. please do not change. - Stream stream = Stream.Null; - Assert.Throws(() => stream.ReadInt64((Endianness)(-1))); + Stream stream = null!; + Assert.Throws(() => stream.ReadInt64LittleEndian()); } [Test] - public void ReadInt64_ShouldReadBigEndian_GivenBigEndian() + public void ReadInt64BigEndian_ShouldThrowArgumentException_GivenNonReadableStream() + { + Stream stream = new DummyStream(); + Assert.Throws(() => stream.ReadInt64BigEndian()); + } + + [Test] + public void ReadInt64LittleEndian_ShouldThrowArgumentException_GivenNonReadableStream() + { + Stream stream = new DummyStream(); + Assert.Throws(() => stream.ReadInt64LittleEndian()); + } + + [Test] + public void ReadInt64BigEndian_ShouldReadBigEndian() { using var stream = new MemoryStream(); - ReadOnlySpan bytes = stackalloc byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xA4}; + ReadOnlySpan bytes = stackalloc byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xA4 }; stream.Write(bytes); stream.Position = 0; const long expected = 420; - long actual = stream.ReadInt64(Endianness.BigEndian); + long actual = stream.ReadInt64BigEndian(); Assert.That(stream.Position, Is.EqualTo(8)); Assert.That(actual, Is.EqualTo(expected)); } [Test] - public void ReadInt64_ShouldWriteLittleEndian_GivenLittleEndian() + public void ReadInt64LittleEndian_ShouldWriteLittleEndian() { using var stream = new MemoryStream(); - ReadOnlySpan bytes = stackalloc byte[] {0xA4, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + ReadOnlySpan bytes = stackalloc byte[] { 0xA4, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; stream.Write(bytes); stream.Position = 0; const long expected = 420; - long actual = stream.ReadInt64(Endianness.LittleEndian); + long actual = stream.ReadInt64LittleEndian(); Assert.That(stream.Position, Is.EqualTo(8)); Assert.That(actual, Is.EqualTo(expected)); diff --git a/X10D.Tests/src/IO/StreamTests.ReadSingle.cs b/X10D.Tests/src/IO/StreamTests.ReadSingle.cs index 7d5a396..ff2336b 100644 --- a/X10D.Tests/src/IO/StreamTests.ReadSingle.cs +++ b/X10D.Tests/src/IO/StreamTests.ReadSingle.cs @@ -1,4 +1,5 @@ -using NUnit.Framework; +using System.Diagnostics.CodeAnalysis; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; @@ -6,60 +7,60 @@ namespace X10D.Tests.IO; internal partial class StreamTests { [Test] - public void ReadSingle_ShouldThrowArgumentException_GivenNonReadableStream() - { - Stream stream = new DummyStream(); - Assert.Throws(() => stream.ReadSingle()); - Assert.Throws(() => stream.ReadSingle(Endianness.LittleEndian)); - Assert.Throws(() => stream.ReadSingle(Endianness.BigEndian)); - } - - [Test] - public void ReadSingle_ShouldThrowArgumentNullException_GivenNullStream() + public void ReadSingleBigEndian_ShouldThrowArgumentNullException_GivenNullStream() { Stream stream = null!; - Assert.Throws(() => stream.ReadSingle()); - Assert.Throws(() => stream.ReadSingle(Endianness.LittleEndian)); - Assert.Throws(() => stream.ReadSingle(Endianness.BigEndian)); + Assert.Throws(() => stream.ReadSingleBigEndian()); } [Test] - public void ReadSingle_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() + public void ReadSingleLittleEndian_ShouldThrowArgumentNullException_GivenNullStream() { - // we don't need to enclose this stream in a using declaration, since disposing a - // null stream is meaningless. NullStream.Dispose actually does nothing, anyway. - // that - coupled with the fact that encapsulating the stream in a using declaration causes the - // analyser to trip up and think the stream is disposed by the time the local is captured in - // assertion lambda - means this line is fine as it is. please do not change. - Stream stream = Stream.Null; - Assert.Throws(() => stream.ReadSingle((Endianness)(-1))); + Stream stream = null!; + Assert.Throws(() => stream.ReadSingleLittleEndian()); } [Test] - public void ReadSingle_ShouldReadBigEndian_GivenBigEndian() + [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] + public void ReadSingleBigEndian_ShouldThrowArgumentException_GivenNonReadableStream() + { + Stream stream = new DummyStream(); + Assert.Throws(() => stream.ReadSingleBigEndian()); + } + + [Test] + [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] + public void ReadSingleLittleEndian_ShouldThrowArgumentException_GivenNonReadableStream() + { + Stream stream = new DummyStream(); + Assert.Throws(() => stream.ReadSingleLittleEndian()); + } + + [Test] + public void ReadSingleBigEndian_ShouldReadBigEndian() { using var stream = new MemoryStream(); - ReadOnlySpan bytes = stackalloc byte[] {0x43, 0xD2, 0x00, 0x00}; + ReadOnlySpan bytes = stackalloc byte[] { 0x43, 0xD2, 0x00, 0x00 }; stream.Write(bytes); stream.Position = 0; const float expected = 420.0f; - float actual = stream.ReadSingle(Endianness.BigEndian); + float actual = stream.ReadSingleBigEndian(); Assert.That(stream.Position, Is.EqualTo(4)); Assert.That(actual, Is.EqualTo(expected)); } [Test] - public void ReadSingle_ShouldReadLittleEndian_GivenLittleEndian() + public void ReadSingleLittleEndian_ShouldReadLittleEndian() { using var stream = new MemoryStream(); - ReadOnlySpan bytes = stackalloc byte[] {0x00, 0x00, 0xD2, 0x43}; + ReadOnlySpan bytes = stackalloc byte[] { 0x00, 0x00, 0xD2, 0x43 }; stream.Write(bytes); stream.Position = 0; const float expected = 420.0f; - float actual = stream.ReadSingle(Endianness.LittleEndian); + float actual = stream.ReadSingleLittleEndian(); Assert.That(stream.Position, Is.EqualTo(4)); Assert.That(actual, Is.EqualTo(expected)); diff --git a/X10D.Tests/src/IO/StreamTests.ReadUInt16.cs b/X10D.Tests/src/IO/StreamTests.ReadUInt16.cs index cd8d726..0cd249d 100644 --- a/X10D.Tests/src/IO/StreamTests.ReadUInt16.cs +++ b/X10D.Tests/src/IO/StreamTests.ReadUInt16.cs @@ -1,4 +1,5 @@ -using NUnit.Framework; +using System.Diagnostics.CodeAnalysis; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; @@ -6,60 +7,60 @@ namespace X10D.Tests.IO; internal partial class StreamTests { [Test] - public void ReadUInt16_ShouldThrowArgumentException_GivenNonReadableStream() - { - Stream stream = new DummyStream(); - Assert.Throws(() => stream.ReadUInt16()); - Assert.Throws(() => stream.ReadUInt16(Endianness.LittleEndian)); - Assert.Throws(() => stream.ReadUInt16(Endianness.BigEndian)); - } - - [Test] - public void ReadUInt16_ShouldThrowArgumentNullException_GivenNullStream() + public void ReadUInt16BigEndian_ShouldThrowArgumentNullException_GivenNullStream() { Stream stream = null!; - Assert.Throws(() => stream.ReadUInt16()); - Assert.Throws(() => stream.ReadUInt16(Endianness.LittleEndian)); - Assert.Throws(() => stream.ReadUInt16(Endianness.BigEndian)); + Assert.Throws(() => stream.ReadUInt16BigEndian()); } [Test] - public void ReadUInt16_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() + public void ReadUInt16LittleEndian_ShouldThrowArgumentNullException_GivenNullStream() { - // we don't need to enclose this stream in a using declaration, since disposing a - // null stream is meaningless. NullStream.Dispose actually does nothing, anyway. - // that - coupled with the fact that encapsulating the stream in a using declaration causes the - // analyser to trip up and think the stream is disposed by the time the local is captured in - // assertion lambda - means this line is fine as it is. please do not change. - Stream stream = Stream.Null; - Assert.Throws(() => stream.ReadUInt16((Endianness)(-1))); + Stream stream = null!; + Assert.Throws(() => stream.ReadUInt16LittleEndian()); } [Test] - public void ReadUInt16_ShouldReadBigEndian_GivenBigEndian() + [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] + public void ReadUInt16BigEndian_ShouldThrowArgumentException_GivenNonReadableStream() + { + Stream stream = new DummyStream(); + Assert.Throws(() => stream.ReadUInt16BigEndian()); + } + + [Test] + [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] + public void ReadUInt16LittleEndian_ShouldThrowArgumentException_GivenNonReadableStream() + { + Stream stream = new DummyStream(); + Assert.Throws(() => stream.ReadUInt16LittleEndian()); + } + + [Test] + public void ReadUInt16BigEndian_ShouldReadBigEndian() { using var stream = new MemoryStream(); - ReadOnlySpan bytes = stackalloc byte[] {0x01, 0xA4}; + ReadOnlySpan bytes = stackalloc byte[] { 0x01, 0xA4 }; stream.Write(bytes); stream.Position = 0; const ushort expected = 420; - ushort actual = stream.ReadUInt16(Endianness.BigEndian); + ushort actual = stream.ReadUInt16BigEndian(); Assert.That(stream.Position, Is.EqualTo(2)); Assert.That(actual, Is.EqualTo(expected)); } [Test] - public void ReadUInt16_ShouldReadLittleEndian_GivenLittleEndian() + public void ReadUInt16LittleEndian_ShouldReadLittleEndian() { using var stream = new MemoryStream(); - ReadOnlySpan bytes = stackalloc byte[] {0xA4, 0x01}; + ReadOnlySpan bytes = stackalloc byte[] { 0xA4, 0x01 }; stream.Write(bytes); stream.Position = 0; const ushort expected = 420; - ushort actual = stream.ReadUInt16(Endianness.LittleEndian); + ushort actual = stream.ReadUInt16LittleEndian(); Assert.That(stream.Position, Is.EqualTo(2)); Assert.That(actual, Is.EqualTo(expected)); diff --git a/X10D.Tests/src/IO/StreamTests.ReadUInt32.cs b/X10D.Tests/src/IO/StreamTests.ReadUInt32.cs index cc5c67d..3164afe 100644 --- a/X10D.Tests/src/IO/StreamTests.ReadUInt32.cs +++ b/X10D.Tests/src/IO/StreamTests.ReadUInt32.cs @@ -1,4 +1,5 @@ -using NUnit.Framework; +using System.Diagnostics.CodeAnalysis; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; @@ -6,60 +7,60 @@ namespace X10D.Tests.IO; internal partial class StreamTests { [Test] - public void ReadUInt32_ShouldThrowArgumentException_GivenNonReadableStream() - { - Stream stream = new DummyStream(); - Assert.Throws(() => stream.ReadUInt32()); - Assert.Throws(() => stream.ReadUInt32(Endianness.LittleEndian)); - Assert.Throws(() => stream.ReadUInt32(Endianness.BigEndian)); - } - - [Test] - public void ReadUInt32_ShouldThrowArgumentNullException_GivenNullStream() + public void ReadUInt32BigEndian_ShouldThrowArgumentNullException_GivenNullStream() { Stream stream = null!; - Assert.Throws(() => stream.ReadUInt32()); - Assert.Throws(() => stream.ReadUInt32(Endianness.LittleEndian)); - Assert.Throws(() => stream.ReadUInt32(Endianness.BigEndian)); + Assert.Throws(() => stream.ReadUInt32BigEndian()); } [Test] - public void ReadUInt32_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() + public void ReadUInt32LittleEndian_ShouldThrowArgumentNullException_GivenNullStream() { - // we don't need to enclose this stream in a using declaration, since disposing a - // null stream is meaningless. NullStream.Dispose actually does nothing, anyway. - // that - coupled with the fact that encapsulating the stream in a using declaration causes the - // analyser to trip up and think the stream is disposed by the time the local is captured in - // assertion lambda - means this line is fine as it is. please do not change. - Stream stream = Stream.Null; - Assert.Throws(() => stream.ReadUInt32((Endianness)(-1))); + Stream stream = null!; + Assert.Throws(() => stream.ReadUInt32LittleEndian()); } [Test] - public void ReadUInt32_ShouldReadBigEndian_GivenBigEndian() + [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] + public void ReadUInt32BigEndian_ShouldThrowArgumentException_GivenNonReadableStream() + { + Stream stream = new DummyStream(); + Assert.Throws(() => stream.ReadUInt32BigEndian()); + } + + [Test] + [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] + public void ReadUInt32LittleEndian_ShouldThrowArgumentException_GivenNonReadableStream() + { + Stream stream = new DummyStream(); + Assert.Throws(() => stream.ReadUInt32LittleEndian()); + } + + [Test] + public void ReadUInt32BigEndian_ShouldReadBigEndian() { using var stream = new MemoryStream(); - ReadOnlySpan bytes = stackalloc byte[] {0x00, 0x00, 0x01, 0xA4}; + ReadOnlySpan bytes = stackalloc byte[] { 0x00, 0x00, 0x01, 0xA4 }; stream.Write(bytes); stream.Position = 0; const uint expected = 420; - uint actual = stream.ReadUInt32(Endianness.BigEndian); + uint actual = stream.ReadUInt32BigEndian(); Assert.That(stream.Position, Is.EqualTo(4)); Assert.That(actual, Is.EqualTo(expected)); } [Test] - public void ReadUInt32_ShouldReadLittleEndian_GivenLittleEndian() + public void ReadUInt32LittleEndian_ShouldReadLittleEndian() { using var stream = new MemoryStream(); - ReadOnlySpan bytes = stackalloc byte[] {0xA4, 0x01, 0x00, 0x00}; + ReadOnlySpan bytes = stackalloc byte[] { 0xA4, 0x01, 0x00, 0x00 }; stream.Write(bytes); stream.Position = 0; const uint expected = 420; - uint actual = stream.ReadUInt32(Endianness.LittleEndian); + uint actual = stream.ReadUInt32LittleEndian(); Assert.That(stream.Position, Is.EqualTo(4)); Assert.That(actual, Is.EqualTo(expected)); diff --git a/X10D.Tests/src/IO/StreamTests.ReadUInt64.cs b/X10D.Tests/src/IO/StreamTests.ReadUInt64.cs index 0d916a7..ca33b01 100644 --- a/X10D.Tests/src/IO/StreamTests.ReadUInt64.cs +++ b/X10D.Tests/src/IO/StreamTests.ReadUInt64.cs @@ -1,4 +1,5 @@ -using NUnit.Framework; +using System.Diagnostics.CodeAnalysis; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; @@ -6,60 +7,60 @@ namespace X10D.Tests.IO; internal partial class StreamTests { [Test] - public void ReadUInt64_ShouldThrowArgumentException_GivenNonReadableStream() - { - Stream stream = new DummyStream(); - Assert.Throws(() => stream.ReadUInt64()); - Assert.Throws(() => stream.ReadUInt64(Endianness.LittleEndian)); - Assert.Throws(() => stream.ReadUInt64(Endianness.BigEndian)); - } - - [Test] - public void ReadUInt64_ShouldThrowArgumentNullException_GivenNullStream() + public void ReadUInt64BigEndian_ShouldThrowArgumentNullException_GivenNullStream() { Stream stream = null!; - Assert.Throws(() => stream.ReadUInt64()); - Assert.Throws(() => stream.ReadUInt64(Endianness.LittleEndian)); - Assert.Throws(() => stream.ReadUInt64(Endianness.BigEndian)); + Assert.Throws(() => stream.ReadUInt64BigEndian()); } [Test] - public void ReadUInt64_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() + public void ReadUInt64LittleEndian_ShouldThrowArgumentNullException_GivenNullStream() { - // we don't need to enclose this stream in a using declaration, since disposing a - // null stream is meaningless. NullStream.Dispose actually does nothing, anyway. - // that - coupled with the fact that encapsulating the stream in a using declaration causes the - // analyser to trip up and think the stream is disposed by the time the local is captured in - // assertion lambda - means this line is fine as it is. please do not change. - Stream stream = Stream.Null; - Assert.Throws(() => stream.ReadUInt64((Endianness)(-1))); + Stream stream = null!; + Assert.Throws(() => stream.ReadUInt64LittleEndian()); } [Test] - public void ReadUInt64_ShouldReadBigEndian_GivenBigEndian() + [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] + public void ReadUInt64BigEndian_ShouldThrowArgumentException_GivenNonReadableStream() + { + Stream stream = new DummyStream(); + Assert.Throws(() => stream.ReadUInt64BigEndian()); + } + + [Test] + [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] + public void ReadUInt64LittleEndian_ShouldThrowArgumentException_GivenNonReadableStream() + { + Stream stream = new DummyStream(); + Assert.Throws(() => stream.ReadUInt64LittleEndian()); + } + + [Test] + public void ReadUInt64BigEndian_ShouldReadBigEndian() { using var stream = new MemoryStream(); - ReadOnlySpan bytes = stackalloc byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xA4}; + ReadOnlySpan bytes = stackalloc byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xA4 }; stream.Write(bytes); stream.Position = 0; const ulong expected = 420; - ulong actual = stream.ReadUInt64(Endianness.BigEndian); + ulong actual = stream.ReadUInt64BigEndian(); Assert.That(stream.Position, Is.EqualTo(8)); Assert.That(actual, Is.EqualTo(expected)); } [Test] - public void ReadUInt64_ShouldWriteLittleEndian_GivenLittleEndian() + public void ReadUInt64LittleEndian_ShouldWriteLittleEndian() { using var stream = new MemoryStream(); - ReadOnlySpan bytes = stackalloc byte[] {0xA4, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + ReadOnlySpan bytes = stackalloc byte[] { 0xA4, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; stream.Write(bytes); stream.Position = 0; const ulong expected = 420; - ulong actual = stream.ReadUInt64(Endianness.LittleEndian); + ulong actual = stream.ReadUInt64LittleEndian(); Assert.That(stream.Position, Is.EqualTo(8)); Assert.That(actual, Is.EqualTo(expected)); diff --git a/X10D.Tests/src/IO/StreamTests.WriteDecimal.cs b/X10D.Tests/src/IO/StreamTests.WriteDecimal.cs index 3aaa113..911dd5d 100644 --- a/X10D.Tests/src/IO/StreamTests.WriteDecimal.cs +++ b/X10D.Tests/src/IO/StreamTests.WriteDecimal.cs @@ -1,4 +1,5 @@ using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using NUnit.Framework; using X10D.IO; @@ -7,46 +8,47 @@ namespace X10D.Tests.IO; internal partial class StreamTests { [Test] - public void WriteDecimal_ShouldThrowArgumentException_GivenNonWriteableStream() - { - Stream stream = new DummyStream(); - Assert.Throws(() => stream.Write(420.0m, Endianness.LittleEndian)); - Assert.Throws(() => stream.Write(420.0m, Endianness.BigEndian)); - } - - [Test] - public void WriteDecimal_ShouldThrowArgumentNullException_GivenNullStream() + public void WriteBigEndian_ShouldThrowArgumentNullException_GivenNullStream_AndDecimalArgument() { Stream stream = null!; - Assert.Throws(() => stream.Write(420.0m, Endianness.LittleEndian)); - Assert.Throws(() => stream.Write(420.0m, Endianness.BigEndian)); + Assert.Throws(() => stream.WriteBigEndian(420.0m)); } [Test] - public void WriteDecimal_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() + [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] + public void WriteBigEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndDecimalArgument() { - // we don't need to enclose this stream in a using declaration, since disposing a - // null stream is meaningless. NullStream.Dispose actually does nothing, anyway. - // that - coupled with the fact that encapsulating the stream in a using declaration causes the - // analyser to trip up and think the stream is disposed by the time the local is captured in - // assertion lambda - means this line is fine as it is. please do not change. - Stream stream = Stream.Null; - Assert.Throws(() => stream.Write(420.0m, (Endianness)(-1))); - Assert.Throws(() => stream.Write(420.0m, (Endianness)(-1))); + Stream stream = new DummyStream(); + Assert.Throws(() => stream.WriteBigEndian(420.0m)); } [Test] - public void WriteDecimal_ShouldWriteBigEndian_GivenBigEndian() + public void WriteLittleEndian_ShouldThrowArgumentNullException_GivenNullStream_AndDecimalArgument() + { + Stream stream = null!; + Assert.Throws(() => stream.WriteLittleEndian(420.0m)); + } + + [Test] + [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] + public void WriteLittleEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndDecimalArgument() + { + Stream stream = new DummyStream(); + Assert.Throws(() => stream.WriteLittleEndian(420.0m)); + } + + [Test] + public void WriteBigEndian_ShouldWriteBigEndian_GivenDecimalArgument() { using var stream = new MemoryStream(); - stream.Write(420.0m, Endianness.BigEndian); + stream.WriteBigEndian(420.0m); Assert.That(stream.Position, Is.EqualTo(16)); stream.Position = 0; Span actual = stackalloc byte[16]; ReadOnlySpan expected = stackalloc byte[] { - 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x68 + 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x68, 0x10, 0x00, 0x00 }; int read = stream.Read(actual); @@ -55,10 +57,10 @@ internal partial class StreamTests } [Test] - public void WriteDecimal_ShouldWriteLittleEndian_GivenLittleEndian() + public void WriteLittleEndian_ShouldWriteLittleEndian_GivenDecimalArgument() { using var stream = new MemoryStream(); - stream.Write(420.0m, Endianness.LittleEndian); + stream.WriteLittleEndian(420.0m); Assert.That(stream.Position, Is.EqualTo(16)); stream.Position = 0; diff --git a/X10D.Tests/src/IO/StreamTests.WriteDouble.cs b/X10D.Tests/src/IO/StreamTests.WriteDouble.cs index e933858..8828325 100644 --- a/X10D.Tests/src/IO/StreamTests.WriteDouble.cs +++ b/X10D.Tests/src/IO/StreamTests.WriteDouble.cs @@ -1,4 +1,5 @@ -using NUnit.Framework; +using System.Diagnostics.CodeAnalysis; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; @@ -6,44 +7,45 @@ namespace X10D.Tests.IO; internal partial class StreamTests { [Test] - public void WriteDouble_ShouldThrowArgumentException_GivenNonWriteableStream() - { - Stream stream = new DummyStream(); - Assert.Throws(() => stream.Write(420.0, Endianness.LittleEndian)); - Assert.Throws(() => stream.Write(420.0, Endianness.BigEndian)); - } - - [Test] - public void WriteDouble_ShouldThrowArgumentNullException_GivenNullStream() + public void WriteBigEndian_ShouldThrowArgumentNullException_GivenNullStream_AndDoubleArgument() { Stream stream = null!; - Assert.Throws(() => stream.Write(420.0, Endianness.LittleEndian)); - Assert.Throws(() => stream.Write(420.0, Endianness.BigEndian)); + Assert.Throws(() => stream.WriteBigEndian(420.0)); } [Test] - public void WriteDouble_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() + [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] + public void WriteBigEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndDoubleArgument() { - // we don't need to enclose this stream in a using declaration, since disposing a - // null stream is meaningless. NullStream.Dispose actually does nothing, anyway. - // that - coupled with the fact that encapsulating the stream in a using declaration causes the - // analyser to trip up and think the stream is disposed by the time the local is captured in - // assertion lambda - means this line is fine as it is. please do not change. - Stream stream = Stream.Null; - Assert.Throws(() => stream.Write(420.0, (Endianness)(-1))); - Assert.Throws(() => stream.Write(420.0, (Endianness)(-1))); + Stream stream = new DummyStream(); + Assert.Throws(() => stream.WriteBigEndian(420.0)); } [Test] - public void WriteDouble_ShouldWriteBigEndian_GivenBigEndian() + public void WriteLittleEndian_ShouldThrowArgumentNullException_GivenNullStream_AndDoubleArgument() + { + Stream stream = null!; + Assert.Throws(() => stream.WriteLittleEndian(420.0)); + } + + [Test] + [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] + public void WriteLittleEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndDoubleArgument() + { + Stream stream = new DummyStream(); + Assert.Throws(() => stream.WriteLittleEndian(420.0)); + } + + [Test] + public void WriteBigEndian_ShouldWriteBigEndian_GivenDoubleArgument() { using var stream = new MemoryStream(); - stream.Write(420.0, Endianness.BigEndian); + stream.WriteBigEndian(420.0); Assert.That(stream.Position, Is.EqualTo(8)); stream.Position = 0; Span actual = stackalloc byte[8]; - ReadOnlySpan expected = stackalloc byte[] {0x40, 0x7A, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00}; + ReadOnlySpan expected = stackalloc byte[] { 0x40, 0x7A, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00 }; int read = stream.Read(actual); Assert.That(read, Is.EqualTo(8)); @@ -51,15 +53,15 @@ internal partial class StreamTests } [Test] - public void WriteDouble_ShouldWriteLittleEndian_GivenLittleEndian() + public void WriteLittleEndian_ShouldWriteLittleEndian_GivenDoubleArgument() { using var stream = new MemoryStream(); - stream.Write(420.0, Endianness.LittleEndian); + stream.WriteLittleEndian(420.0); Assert.That(stream.Position, Is.EqualTo(8)); stream.Position = 0; Span actual = stackalloc byte[8]; - ReadOnlySpan expected = stackalloc byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x7A, 0x40}; + ReadOnlySpan expected = stackalloc byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x7A, 0x40 }; int read = stream.Read(actual); Assert.That(read, Is.EqualTo(8)); diff --git a/X10D.Tests/src/IO/StreamTests.WriteInt16.cs b/X10D.Tests/src/IO/StreamTests.WriteInt16.cs index cc17549..bc38dd8 100644 --- a/X10D.Tests/src/IO/StreamTests.WriteInt16.cs +++ b/X10D.Tests/src/IO/StreamTests.WriteInt16.cs @@ -1,4 +1,5 @@ -using NUnit.Framework; +using System.Diagnostics.CodeAnalysis; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; @@ -6,44 +7,45 @@ namespace X10D.Tests.IO; internal partial class StreamTests { [Test] - public void WriteInt16_ShouldThrowArgumentException_GivenNonWriteableStream() - { - Stream stream = new DummyStream(); - Assert.Throws(() => stream.Write((short)420, Endianness.LittleEndian)); - Assert.Throws(() => stream.Write((short)420, Endianness.BigEndian)); - } - - [Test] - public void WriteInt16_ShouldThrowArgumentNullException_GivenNullStream() + public void WriteBigEndian_ShouldThrowArgumentNullException_GivenNullStream_AndInt16Argument() { Stream stream = null!; - Assert.Throws(() => stream.Write((short)420, Endianness.LittleEndian)); - Assert.Throws(() => stream.Write((short)420, Endianness.BigEndian)); + Assert.Throws(() => stream.WriteBigEndian((short)420)); } [Test] - public void WriteInt16_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() + [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] + public void WriteBigEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndInt16Argument() { - // we don't need to enclose this stream in a using declaration, since disposing a - // null stream is meaningless. NullStream.Dispose actually does nothing, anyway. - // that - coupled with the fact that encapsulating the stream in a using declaration causes the - // analyser to trip up and think the stream is disposed by the time the local is captured in - // assertion lambda - means this line is fine as it is. please do not change. - Stream stream = Stream.Null; - Assert.Throws(() => stream.Write((short)420, (Endianness)(-1))); - Assert.Throws(() => stream.Write((short)420, (Endianness)(-1))); + Stream stream = new DummyStream(); + Assert.Throws(() => stream.WriteBigEndian((short)420)); } [Test] - public void WriteInt16_ShouldWriteBigEndian_GivenBigEndian() + public void WriteLittleEndian_ShouldThrowArgumentNullException_GivenNullStream_AndInt16Argument() + { + Stream stream = null!; + Assert.Throws(() => stream.WriteLittleEndian((short)420)); + } + + [Test] + [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] + public void WriteLittleEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndInt16Argument() + { + Stream stream = new DummyStream(); + Assert.Throws(() => stream.WriteLittleEndian((short)420)); + } + + [Test] + public void WriteBigEndian_ShouldWriteBigEndian_GivenInt16Argument() { using var stream = new MemoryStream(); - stream.Write((short)420, Endianness.BigEndian); + stream.WriteBigEndian((short)420); Assert.That(stream.Position, Is.EqualTo(2)); stream.Position = 0; Span actual = stackalloc byte[2]; - ReadOnlySpan expected = stackalloc byte[] {0x01, 0xA4}; + ReadOnlySpan expected = stackalloc byte[] { 0x01, 0xA4 }; int read = stream.Read(actual); Assert.That(read, Is.EqualTo(2)); @@ -51,15 +53,15 @@ internal partial class StreamTests } [Test] - public void WriteInt16_ShouldWriteLittleEndian_GivenLittleEndian() + public void WriteLittleEndian_ShouldWriteLittleEndian_GivenInt16Argument() { using var stream = new MemoryStream(); - stream.Write((short)420, Endianness.LittleEndian); + stream.WriteLittleEndian((short)420); Assert.That(stream.Position, Is.EqualTo(2)); stream.Position = 0; Span actual = stackalloc byte[2]; - ReadOnlySpan expected = stackalloc byte[] {0xA4, 0x01}; + ReadOnlySpan expected = stackalloc byte[] { 0xA4, 0x01 }; int read = stream.Read(actual); Assert.That(read, Is.EqualTo(2)); diff --git a/X10D.Tests/src/IO/StreamTests.WriteInt32.cs b/X10D.Tests/src/IO/StreamTests.WriteInt32.cs index 95f748e..75688f9 100644 --- a/X10D.Tests/src/IO/StreamTests.WriteInt32.cs +++ b/X10D.Tests/src/IO/StreamTests.WriteInt32.cs @@ -1,4 +1,5 @@ -using NUnit.Framework; +using System.Diagnostics.CodeAnalysis; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; @@ -6,44 +7,45 @@ namespace X10D.Tests.IO; internal partial class StreamTests { [Test] - public void WriteInt32_ShouldThrowArgumentException_GivenNonWriteableStream() - { - Stream stream = new DummyStream(); - Assert.Throws(() => stream.Write(420, Endianness.LittleEndian)); - Assert.Throws(() => stream.Write(420, Endianness.BigEndian)); - } - - [Test] - public void WriteInt32_ShouldThrowArgumentNullException_GivenNullStream() + public void WriteBigEndian_ShouldThrowArgumentNullException_GivenNullStream_AndInt32Argument() { Stream stream = null!; - Assert.Throws(() => stream.Write(420, Endianness.LittleEndian)); - Assert.Throws(() => stream.Write(420, Endianness.BigEndian)); + Assert.Throws(() => stream.WriteBigEndian(420)); } [Test] - public void WriteInt32_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() + [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] + public void WriteBigEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndInt32Argument() { - // we don't need to enclose this stream in a using declaration, since disposing a - // null stream is meaningless. NullStream.Dispose actually does nothing, anyway. - // that - coupled with the fact that encapsulating the stream in a using declaration causes the - // analyser to trip up and think the stream is disposed by the time the local is captured in - // assertion lambda - means this line is fine as it is. please do not change. - Stream stream = Stream.Null; - Assert.Throws(() => stream.Write(420, (Endianness)(-1))); - Assert.Throws(() => stream.Write(420, (Endianness)(-1))); + Stream stream = new DummyStream(); + Assert.Throws(() => stream.WriteBigEndian(420)); } [Test] - public void WriteInt32_ShouldWriteBigEndian_GivenBigEndian() + public void WriteLittleEndian_ShouldThrowArgumentNullException_GivenNullStream_AndInt32Argument() + { + Stream stream = null!; + Assert.Throws(() => stream.WriteLittleEndian(420)); + } + + [Test] + [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] + public void WriteLittleEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndInt32Argument() + { + Stream stream = new DummyStream(); + Assert.Throws(() => stream.WriteLittleEndian(420)); + } + + [Test] + public void WriteBigEndian_ShouldWriteBigEndian_GivenInt32Argument() { using var stream = new MemoryStream(); - stream.Write(420, Endianness.BigEndian); + stream.WriteBigEndian(420); Assert.That(stream.Position, Is.EqualTo(4)); stream.Position = 0; Span actual = stackalloc byte[4]; - ReadOnlySpan expected = stackalloc byte[] {0x00, 0x00, 0x01, 0xA4}; + ReadOnlySpan expected = stackalloc byte[] { 0x00, 0x00, 0x01, 0xA4 }; int read = stream.Read(actual); Assert.That(read, Is.EqualTo(4)); @@ -51,15 +53,15 @@ internal partial class StreamTests } [Test] - public void WriteInt32_ShouldWriteLittleEndian_GivenLittleEndian() + public void WriteLittleEndian_ShouldWriteLittleEndian_GivenInt32Argument() { using var stream = new MemoryStream(); - stream.Write(420, Endianness.LittleEndian); + stream.WriteLittleEndian(420); Assert.That(stream.Position, Is.EqualTo(4)); stream.Position = 0; Span actual = stackalloc byte[4]; - ReadOnlySpan expected = stackalloc byte[] {0xA4, 0x01, 0x00, 0x00}; + ReadOnlySpan expected = stackalloc byte[] { 0xA4, 0x01, 0x00, 0x00 }; int read = stream.Read(actual); Assert.That(read, Is.EqualTo(4)); diff --git a/X10D.Tests/src/IO/StreamTests.WriteInt64.cs b/X10D.Tests/src/IO/StreamTests.WriteInt64.cs index adb8ce2..feeb677 100644 --- a/X10D.Tests/src/IO/StreamTests.WriteInt64.cs +++ b/X10D.Tests/src/IO/StreamTests.WriteInt64.cs @@ -1,4 +1,5 @@ -using NUnit.Framework; +using System.Diagnostics.CodeAnalysis; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; @@ -6,44 +7,45 @@ namespace X10D.Tests.IO; internal partial class StreamTests { [Test] - public void WriteInt64_ShouldThrowArgumentException_GivenNonWriteableStream() - { - Stream stream = new DummyStream(); - Assert.Throws(() => stream.Write(420L, Endianness.LittleEndian)); - Assert.Throws(() => stream.Write(420L, Endianness.BigEndian)); - } - - [Test] - public void WriteInt64_ShouldThrowArgumentNullException_GivenNullStream() + public void WriteBigEndian_ShouldThrowArgumentNullException_GivenNullStream_AndInt64Argument() { Stream stream = null!; - Assert.Throws(() => stream.Write(420L, Endianness.LittleEndian)); - Assert.Throws(() => stream.Write(420L, Endianness.BigEndian)); + Assert.Throws(() => stream.WriteBigEndian(420L)); } [Test] - public void WriteInt64_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() + [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] + public void WriteBigEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndInt64Argument() { - // we don't need to enclose this stream in a using declaration, since disposing a - // null stream is meaningless. NullStream.Dispose actually does nothing, anyway. - // that - coupled with the fact that encapsulating the stream in a using declaration causes the - // analyser to trip up and think the stream is disposed by the time the local is captured in - // assertion lambda - means this line is fine as it is. please do not change. - Stream stream = Stream.Null; - Assert.Throws(() => stream.Write(420L, (Endianness)(-1))); - Assert.Throws(() => stream.Write(420L, (Endianness)(-1))); + Stream stream = new DummyStream(); + Assert.Throws(() => stream.WriteBigEndian(420L)); } [Test] - public void WriteInt64_ShouldWriteBigEndian_GivenBigEndian() + public void WriteLittleEndian_ShouldThrowArgumentNullException_GivenNullStream_AndInt64Argument() + { + Stream stream = null!; + Assert.Throws(() => stream.WriteLittleEndian(420L)); + } + + [Test] + [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] + public void WriteLittleEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndInt64Argument() + { + Stream stream = new DummyStream(); + Assert.Throws(() => stream.WriteLittleEndian(420L)); + } + + [Test] + public void WriteBigEndian_ShouldWriteBigEndian_GivenInt64Argument() { using var stream = new MemoryStream(); - stream.Write(420L, Endianness.BigEndian); + stream.WriteBigEndian(420L); Assert.That(stream.Position, Is.EqualTo(8)); stream.Position = 0; Span actual = stackalloc byte[8]; - ReadOnlySpan expected = stackalloc byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xA4}; + ReadOnlySpan expected = stackalloc byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xA4 }; int read = stream.Read(actual); Assert.That(read, Is.EqualTo(8)); @@ -51,15 +53,15 @@ internal partial class StreamTests } [Test] - public void WriteInt64_ShouldWriteLittleEndian_GivenLittleEndian() + public void WriteLittleEndian_ShouldWriteLittleEndian_GivenLittleEndian() { using var stream = new MemoryStream(); - stream.Write(420L, Endianness.LittleEndian); + stream.WriteLittleEndian(420L); Assert.That(stream.Position, Is.EqualTo(8)); stream.Position = 0; Span actual = stackalloc byte[8]; - ReadOnlySpan expected = stackalloc byte[] {0xA4, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + ReadOnlySpan expected = stackalloc byte[] { 0xA4, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; int read = stream.Read(actual); Assert.That(read, Is.EqualTo(8)); diff --git a/X10D.Tests/src/IO/StreamTests.WriteSingle.cs b/X10D.Tests/src/IO/StreamTests.WriteSingle.cs index 4a7376e..7df8eb8 100644 --- a/X10D.Tests/src/IO/StreamTests.WriteSingle.cs +++ b/X10D.Tests/src/IO/StreamTests.WriteSingle.cs @@ -1,4 +1,5 @@ -using NUnit.Framework; +using System.Diagnostics.CodeAnalysis; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; @@ -6,44 +7,45 @@ namespace X10D.Tests.IO; internal partial class StreamTests { [Test] - public void WriteSingle_ShouldThrowArgumentException_GivenNonWriteableStream() - { - Stream stream = new DummyStream(); - Assert.Throws(() => stream.Write(420.0f, Endianness.LittleEndian)); - Assert.Throws(() => stream.Write(420.0f, Endianness.BigEndian)); - } - - [Test] - public void WriteSingle_ShouldThrowArgumentNullException_GivenNullStream() + public void WriteBigEndian_ShouldThrowArgumentNullException_GivenNullStream_AndSingleArgument() { Stream stream = null!; - Assert.Throws(() => stream.Write(420.0f, Endianness.LittleEndian)); - Assert.Throws(() => stream.Write(420.0f, Endianness.BigEndian)); + Assert.Throws(() => stream.WriteBigEndian(420.0f)); } [Test] - public void WriteSingle_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() + [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] + public void WriteBigEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndSingleArgument() { - // we don't need to enclose this stream in a using declaration, since disposing a - // null stream is meaningless. NullStream.Dispose actually does nothing, anyway. - // that - coupled with the fact that encapsulating the stream in a using declaration causes the - // analyser to trip up and think the stream is disposed by the time the local is captured in - // assertion lambda - means this line is fine as it is. please do not change. - Stream stream = Stream.Null; - Assert.Throws(() => stream.Write(420.0f, (Endianness)(-1))); - Assert.Throws(() => stream.Write(420.0f, (Endianness)(-1))); + Stream stream = new DummyStream(); + Assert.Throws(() => stream.WriteBigEndian(420.0f)); } [Test] - public void WriteSingle_ShouldWriteBigEndian_GivenBigEndian() + public void WriteLittleEndian_ShouldThrowArgumentNullException_GivenNullStream_AndSingleArgument() + { + Stream stream = null!; + Assert.Throws(() => stream.WriteLittleEndian(420.0f)); + } + + [Test] + [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] + public void WriteLittleEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndSingleArgument() + { + Stream stream = new DummyStream(); + Assert.Throws(() => stream.WriteLittleEndian(420.0f)); + } + + [Test] + public void WriteBigEndian_ShouldWriteBigEndian_GivenSingleArgument() { using var stream = new MemoryStream(); - stream.Write(420.0f, Endianness.BigEndian); + stream.WriteBigEndian(420.0f); Assert.That(stream.Position, Is.EqualTo(4)); stream.Position = 0; Span actual = stackalloc byte[4]; - ReadOnlySpan expected = stackalloc byte[] {0x43, 0xD2, 0x00, 0x00}; + ReadOnlySpan expected = stackalloc byte[] { 0x43, 0xD2, 0x00, 0x00 }; int read = stream.Read(actual); Assert.That(read, Is.EqualTo(4)); @@ -51,15 +53,15 @@ internal partial class StreamTests } [Test] - public void WriteSingle_ShouldWriteLittleEndian_GivenLittleEndian() + public void WriteLittleEndian_ShouldWriteLittleEndian_GivenSingleArgument() { using var stream = new MemoryStream(); - stream.Write(420.0f, Endianness.LittleEndian); + stream.WriteLittleEndian(420.0f); Assert.That(stream.Position, Is.EqualTo(4)); stream.Position = 0; Span actual = stackalloc byte[4]; - ReadOnlySpan expected = stackalloc byte[] {0x00, 0x00, 0xD2, 0x43}; + ReadOnlySpan expected = stackalloc byte[] { 0x00, 0x00, 0xD2, 0x43 }; int read = stream.Read(actual); Assert.That(read, Is.EqualTo(4)); diff --git a/X10D.Tests/src/IO/StreamTests.WriteUInt16.cs b/X10D.Tests/src/IO/StreamTests.WriteUInt16.cs index 89a620f..7fde9f2 100644 --- a/X10D.Tests/src/IO/StreamTests.WriteUInt16.cs +++ b/X10D.Tests/src/IO/StreamTests.WriteUInt16.cs @@ -1,4 +1,5 @@ -using NUnit.Framework; +using System.Diagnostics.CodeAnalysis; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; @@ -6,44 +7,45 @@ namespace X10D.Tests.IO; internal partial class StreamTests { [Test] - public void WriteUInt16_ShouldThrowArgumentException_GivenNonWriteableStream() - { - Stream stream = new DummyStream(); - Assert.Throws(() => stream.Write((ushort)420, Endianness.LittleEndian)); - Assert.Throws(() => stream.Write((ushort)420, Endianness.BigEndian)); - } - - [Test] - public void WriteUInt16_ShouldThrowArgumentNullException_GivenNullStream() + public void WriteBigEndian_ShouldThrowArgumentNullException_GivenNullStream_AndUInt16Argument() { Stream stream = null!; - Assert.Throws(() => stream.Write((ushort)420, Endianness.LittleEndian)); - Assert.Throws(() => stream.Write((ushort)420, Endianness.BigEndian)); + Assert.Throws(() => stream.WriteBigEndian((ushort)420)); } [Test] - public void WriteUInt16_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() + [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] + public void WriteBigEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndUInt16Argument() { - // we don't need to enclose this stream in a using declaration, since disposing a - // null stream is meaningless. NullStream.Dispose actually does nothing, anyway. - // that - coupled with the fact that encapsulating the stream in a using declaration causes the - // analyser to trip up and think the stream is disposed by the time the local is captured in - // assertion lambda - means this line is fine as it is. please do not change. - Stream stream = Stream.Null; - Assert.Throws(() => stream.Write((ushort)420, (Endianness)(-1))); - Assert.Throws(() => stream.Write((ushort)420, (Endianness)(-1))); + Stream stream = new DummyStream(); + Assert.Throws(() => stream.WriteBigEndian((ushort)420)); } [Test] - public void WriteUInt16_ShouldWriteBigEndian_GivenBigEndian() + public void WriteLittleEndian_ShouldThrowArgumentNullException_GivenNullStream_AndUInt16Argument() + { + Stream stream = null!; + Assert.Throws(() => stream.WriteLittleEndian((ushort)420)); + } + + [Test] + [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] + public void WriteLittleEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndUInt16Argument() + { + Stream stream = new DummyStream(); + Assert.Throws(() => stream.WriteLittleEndian((ushort)420)); + } + + [Test] + public void WriteBigEndian_ShouldWriteBigEndian_GivenUInt16Endian() { using var stream = new MemoryStream(); - stream.Write((ushort)420, Endianness.BigEndian); + stream.WriteBigEndian((ushort)420); Assert.That(stream.Position, Is.EqualTo(2)); stream.Position = 0; Span actual = stackalloc byte[2]; - ReadOnlySpan expected = stackalloc byte[] {0x01, 0xA4}; + ReadOnlySpan expected = stackalloc byte[] { 0x01, 0xA4 }; int read = stream.Read(actual); Assert.That(read, Is.EqualTo(2)); @@ -51,15 +53,15 @@ internal partial class StreamTests } [Test] - public void WriteUInt16_ShouldWriteLittleEndian_GivenLittleEndian() + public void WriteLittleEndian_ShouldWriteLittleEndian_GivenUInt16tleEndian() { using var stream = new MemoryStream(); - stream.Write((ushort)420, Endianness.LittleEndian); + stream.WriteLittleEndian((ushort)420); Assert.That(stream.Position, Is.EqualTo(2)); stream.Position = 0; Span actual = stackalloc byte[2]; - ReadOnlySpan expected = stackalloc byte[] {0xA4, 0x01}; + ReadOnlySpan expected = stackalloc byte[] { 0xA4, 0x01 }; int read = stream.Read(actual); Assert.That(read, Is.EqualTo(2)); diff --git a/X10D.Tests/src/IO/StreamTests.WriteUInt32.cs b/X10D.Tests/src/IO/StreamTests.WriteUInt32.cs index a9c3bb9..e5eafb7 100644 --- a/X10D.Tests/src/IO/StreamTests.WriteUInt32.cs +++ b/X10D.Tests/src/IO/StreamTests.WriteUInt32.cs @@ -1,4 +1,5 @@ -using NUnit.Framework; +using System.Diagnostics.CodeAnalysis; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; @@ -6,44 +7,45 @@ namespace X10D.Tests.IO; internal partial class StreamTests { [Test] - public void WriteUInt32_ShouldThrowArgumentException_GivenNonWriteableStream() - { - Stream stream = new DummyStream(); - Assert.Throws(() => stream.Write(420U, Endianness.LittleEndian)); - Assert.Throws(() => stream.Write(420U, Endianness.BigEndian)); - } - - [Test] - public void WriteUInt32_ShouldThrowArgumentNullException_GivenNullStream() + public void WriteBigEndian_ShouldThrowArgumentNullException_GivenNullStream_AndUInt32Argument() { Stream stream = null!; - Assert.Throws(() => stream.Write(420U, Endianness.LittleEndian)); - Assert.Throws(() => stream.Write(420U, Endianness.BigEndian)); + Assert.Throws(() => stream.WriteBigEndian(420U)); } [Test] - public void WriteUInt32_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() + [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] + public void WriteBigEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndUInt32Argument() { - // we don't need to enclose this stream in a using declaration, since disposing a - // null stream is meaningless. NullStream.Dispose actually does nothing, anyway. - // that - coupled with the fact that encapsulating the stream in a using declaration causes the - // analyser to trip up and think the stream is disposed by the time the local is captured in - // assertion lambda - means this line is fine as it is. please do not change. - Stream stream = Stream.Null; - Assert.Throws(() => stream.Write(420U, (Endianness)(-1))); - Assert.Throws(() => stream.Write(420U, (Endianness)(-1))); + Stream stream = new DummyStream(); + Assert.Throws(() => stream.WriteBigEndian(420U)); } [Test] - public void WriteUInt32_ShouldWriteBigEndian_GivenBigEndian() + public void WriteLittleEndian_ShouldThrowArgumentNullException_GivenNullStream_AndUInt32Argument() + { + Stream stream = null!; + Assert.Throws(() => stream.WriteLittleEndian(420U)); + } + + [Test] + [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] + public void WriteLittleEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndUInt32Argument() + { + Stream stream = new DummyStream(); + Assert.Throws(() => stream.WriteLittleEndian(420U)); + } + + [Test] + public void WriteBigEndian_ShouldWriteBigEndian_GivenUInt32Argument() { using var stream = new MemoryStream(); - stream.Write(420U, Endianness.BigEndian); + stream.WriteBigEndian(420U); Assert.That(stream.Position, Is.EqualTo(4)); stream.Position = 0; Span actual = stackalloc byte[4]; - ReadOnlySpan expected = stackalloc byte[] {0x00, 0x00, 0x01, 0xA4}; + ReadOnlySpan expected = stackalloc byte[] { 0x00, 0x00, 0x01, 0xA4 }; int read = stream.Read(actual); Assert.That(read, Is.EqualTo(4)); @@ -51,15 +53,15 @@ internal partial class StreamTests } [Test] - public void WriteUInt32_ShouldWriteLittleEndian_GivenLittleEndian() + public void WriteLittleEndian_ShouldWriteLittleEndian_GivenUInt32Argument() { using var stream = new MemoryStream(); - stream.Write(420U, Endianness.LittleEndian); + stream.WriteLittleEndian(420U); Assert.That(stream.Position, Is.EqualTo(4)); stream.Position = 0; Span actual = stackalloc byte[4]; - ReadOnlySpan expected = stackalloc byte[] {0xA4, 0x01, 0x00, 0x00}; + ReadOnlySpan expected = stackalloc byte[] { 0xA4, 0x01, 0x00, 0x00 }; int read = stream.Read(actual); Assert.That(read, Is.EqualTo(4)); diff --git a/X10D.Tests/src/IO/StreamTests.WriteUInt64.cs b/X10D.Tests/src/IO/StreamTests.WriteUInt64.cs index dad8cc4..1bf8464 100644 --- a/X10D.Tests/src/IO/StreamTests.WriteUInt64.cs +++ b/X10D.Tests/src/IO/StreamTests.WriteUInt64.cs @@ -1,4 +1,5 @@ -using NUnit.Framework; +using System.Diagnostics.CodeAnalysis; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; @@ -6,44 +7,45 @@ namespace X10D.Tests.IO; internal partial class StreamTests { [Test] - public void WriteUInt64_ShouldThrowArgumentException_GivenNonWriteableStream() - { - Stream stream = new DummyStream(); - Assert.Throws(() => stream.Write(420UL, Endianness.LittleEndian)); - Assert.Throws(() => stream.Write(420UL, Endianness.BigEndian)); - } - - [Test] - public void WriteUInt64_ShouldThrowArgumentNullException_GivenNullStream() + public void WriteBigEndian_ShouldThrowArgumentNullException_GivenNullStream_AndUInt64Argument() { Stream stream = null!; - Assert.Throws(() => stream.Write(420UL, Endianness.LittleEndian)); - Assert.Throws(() => stream.Write(420UL, Endianness.BigEndian)); + Assert.Throws(() => stream.WriteBigEndian(420UL)); } [Test] - public void WriteUInt64_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() + [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] + public void WriteBigEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndUInt64Argument() { - // we don't need to enclose this stream in a using declaration, since disposing a - // null stream is meaningless. NullStream.Dispose actually does nothing, anyway. - // that - coupled with the fact that encapsulating the stream in a using declaration causes the - // analyser to trip up and think the stream is disposed by the time the local is captured in - // assertion lambda - means this line is fine as it is. please do not change. - Stream stream = Stream.Null; - Assert.Throws(() => stream.Write(420UL, (Endianness)(-1))); - Assert.Throws(() => stream.Write(420UL, (Endianness)(-1))); + Stream stream = new DummyStream(); + Assert.Throws(() => stream.WriteBigEndian(420UL)); } [Test] - public void WriteUInt64_ShouldWriteBigEndian_GivenBigEndian() + public void WriteLittleEndian_ShouldThrowArgumentNullException_GivenNullStream_AndUInt64Argument() + { + Stream stream = null!; + Assert.Throws(() => stream.WriteLittleEndian(420UL)); + } + + [Test] + [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] + public void WriteLittleEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndUInt64Argument() + { + Stream stream = new DummyStream(); + Assert.Throws(() => stream.WriteLittleEndian(420UL)); + } + + [Test] + public void WriteBigEndian_ShouldWriteBigEndian_GivenUInt64Argument() { using var stream = new MemoryStream(); - stream.Write(420UL, Endianness.BigEndian); + stream.WriteBigEndian(420UL); Assert.That(stream.Position, Is.EqualTo(8)); stream.Position = 0; Span actual = stackalloc byte[8]; - ReadOnlySpan expected = stackalloc byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xA4}; + ReadOnlySpan expected = stackalloc byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xA4 }; int read = stream.Read(actual); Assert.That(read, Is.EqualTo(8)); @@ -51,15 +53,15 @@ internal partial class StreamTests } [Test] - public void WriteUInt64_ShouldWriteLittleEndian_GivenLittleEndian() + public void WriteLittleEndian_ShouldWriteLittleEndian_GivenUInt64Argument() { using var stream = new MemoryStream(); - stream.Write(420UL, Endianness.LittleEndian); + stream.WriteLittleEndian(420UL); Assert.That(stream.Position, Is.EqualTo(8)); stream.Position = 0; Span actual = stackalloc byte[8]; - ReadOnlySpan expected = stackalloc byte[] {0xA4, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + ReadOnlySpan expected = stackalloc byte[] { 0xA4, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; int read = stream.Read(actual); Assert.That(read, Is.EqualTo(8)); diff --git a/X10D.Tests/src/IO/UInt16Tests.cs b/X10D.Tests/src/IO/UInt16Tests.cs index 6085358..4ce858d 100644 --- a/X10D.Tests/src/IO/UInt16Tests.cs +++ b/X10D.Tests/src/IO/UInt16Tests.cs @@ -7,56 +7,62 @@ namespace X10D.Tests.IO; internal class UInt16Tests { [Test] - public void GetBytes_ReturnsCorrectValue() + public void GetLittleEndianBytes_ReturnsCorrectValue_WithEndianness() { const ushort value = 0x0F; - byte[] bytes = BitConverter.IsLittleEndian ? new byte[] {0x0F, 0} : new byte[] {0, 0x0F}; - CollectionAssert.AreEqual(bytes, value.GetBytes()); + byte[] expected = { 0x0F, 0 }; + byte[] actual = value.GetLittleEndianBytes(); + + CollectionAssert.AreEqual(expected, actual); } [Test] - public void GetBytes_ReturnsCorrectValue_WithEndianness() + public void GetBigEndianBytes_ReturnsCorrectValue_WithEndianness() { const ushort value = 0x0F; - byte[] littleEndian = {0x0F, 0}; - byte[] bigEndian = {0, 0x0F}; + byte[] expected = { 0, 0x0F }; + byte[] actual = value.GetBigEndianBytes(); - CollectionAssert.AreEqual(littleEndian, value.GetBytes(Endianness.LittleEndian)); - CollectionAssert.AreEqual(bigEndian, value.GetBytes(Endianness.BigEndian)); + CollectionAssert.AreEqual(expected, actual); } [Test] - public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan() + public void TryWriteLittleEndian_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan() { const ushort value = 0x0F; - byte[] bytes = BitConverter.IsLittleEndian ? new byte[] {0x0F, 0} : new byte[] {0, 0x0F}; + byte[] expected = { 0x0F, 0 }; - Span buffer = stackalloc byte[2]; - Assert.That(value.TryWriteBytes(buffer)); - CollectionAssert.AreEqual(bytes, buffer.ToArray()); + Span actual = stackalloc byte[2]; + Assert.That(value.TryWriteLittleEndian(actual)); + + CollectionAssert.AreEqual(expected, actual.ToArray()); } [Test] - public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan_WithEndianness() + public void TryWriteBigEndian_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan() { const ushort value = 0x0F; - byte[] littleEndian = {0x0F, 0}; - byte[] bigEndian = {0, 0x0F}; + byte[] expected = { 0, 0x0F }; - Span buffer = stackalloc byte[2]; + Span actual = stackalloc byte[2]; + Assert.That(value.TryWriteBigEndian(actual)); - Assert.That(value.TryWriteBytes(buffer, Endianness.LittleEndian)); - CollectionAssert.AreEqual(littleEndian, buffer.ToArray()); - - Assert.That(value.TryWriteBytes(buffer, Endianness.BigEndian)); - CollectionAssert.AreEqual(bigEndian, buffer.ToArray()); + CollectionAssert.AreEqual(expected, actual.ToArray()); } [Test] - public void TryWriteBytes_ReturnsFalse_GivenSmallSpan() + public void TryWriteLittleEndian_RReturnsFalse_GivenSmallSpan() { const ushort value = 0x0F; Span buffer = stackalloc byte[0]; - Assert.That(value.TryWriteBytes(buffer), Is.False); + Assert.That(value.TryWriteLittleEndian(buffer), Is.False); + } + + [Test] + public void TryWriteBigEndian_ReturnsFalse_GivenSmallSpan() + { + const ushort value = 0x0F; + Span buffer = stackalloc byte[0]; + Assert.That(value.TryWriteBigEndian(buffer), Is.False); } } diff --git a/X10D.Tests/src/IO/UInt32Tests.cs b/X10D.Tests/src/IO/UInt32Tests.cs index a04ea4b..eada9aa 100644 --- a/X10D.Tests/src/IO/UInt32Tests.cs +++ b/X10D.Tests/src/IO/UInt32Tests.cs @@ -7,56 +7,62 @@ namespace X10D.Tests.IO; internal class UInt32Tests { [Test] - public void GetBytes_ReturnsCorrectValue() + public void GetLittleEndianBytes_ReturnsCorrectValue_WithEndianness() { const uint value = 0x0F; - byte[] bytes = BitConverter.IsLittleEndian ? new byte[] {0x0F, 0, 0, 0} : new byte[] {0, 0, 0, 0x0F}; - CollectionAssert.AreEqual(bytes, value.GetBytes()); + byte[] expected = { 0x0F, 0, 0, 0 }; + byte[] actual = value.GetLittleEndianBytes(); + + CollectionAssert.AreEqual(expected, actual); } [Test] - public void GetBytes_ReturnsCorrectValue_WithEndianness() + public void GetBigEndianBytes_ReturnsCorrectValue_WithEndianness() { const uint value = 0x0F; - byte[] littleEndian = {0x0F, 0, 0, 0}; - byte[] bigEndian = {0, 0, 0, 0x0F}; + byte[] expected = { 0, 0, 0, 0x0F }; + byte[] actual = value.GetBigEndianBytes(); - CollectionAssert.AreEqual(littleEndian, value.GetBytes(Endianness.LittleEndian)); - CollectionAssert.AreEqual(bigEndian, value.GetBytes(Endianness.BigEndian)); + CollectionAssert.AreEqual(expected, actual); } [Test] - public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan() + public void TryWriteLittleEndian_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan() { const uint value = 0x0F; - byte[] bytes = BitConverter.IsLittleEndian ? new byte[] {0x0F, 0, 0, 0} : new byte[] {0, 0, 0, 0x0F}; + byte[] expected = { 0x0F, 0, 0, 0 }; - Span buffer = stackalloc byte[4]; - Assert.That(value.TryWriteBytes(buffer)); - CollectionAssert.AreEqual(bytes, buffer.ToArray()); + Span actual = stackalloc byte[4]; + Assert.That(value.TryWriteLittleEndian(actual)); + + CollectionAssert.AreEqual(expected, actual.ToArray()); } [Test] - public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan_WithEndianness() + public void TryWriteBigEndian_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan() { const uint value = 0x0F; - byte[] littleEndian = {0x0F, 0, 0, 0}; - byte[] bigEndian = {0, 0, 0, 0x0F}; + byte[] expected = { 0, 0, 0, 0x0F }; - Span buffer = stackalloc byte[4]; + Span actual = stackalloc byte[4]; + Assert.That(value.TryWriteBigEndian(actual)); - Assert.That(value.TryWriteBytes(buffer, Endianness.LittleEndian)); - CollectionAssert.AreEqual(littleEndian, buffer.ToArray()); - - Assert.That(value.TryWriteBytes(buffer, Endianness.BigEndian)); - CollectionAssert.AreEqual(bigEndian, buffer.ToArray()); + CollectionAssert.AreEqual(expected, actual.ToArray()); } [Test] - public void TryWriteBytes_ReturnsFalse_GivenSmallSpan() + public void TryWriteLittleEndian_RReturnsFalse_GivenSmallSpan() { const uint value = 0x0F; Span buffer = stackalloc byte[0]; - Assert.That(value.TryWriteBytes(buffer), Is.False); + Assert.That(value.TryWriteLittleEndian(buffer), Is.False); + } + + [Test] + public void TryWriteBigEndian_ReturnsFalse_GivenSmallSpan() + { + const uint value = 0x0F; + Span buffer = stackalloc byte[0]; + Assert.That(value.TryWriteBigEndian(buffer), Is.False); } } diff --git a/X10D.Tests/src/IO/UInt64Tests.cs b/X10D.Tests/src/IO/UInt64Tests.cs index af5727d..6ed1be8 100644 --- a/X10D.Tests/src/IO/UInt64Tests.cs +++ b/X10D.Tests/src/IO/UInt64Tests.cs @@ -7,60 +7,62 @@ namespace X10D.Tests.IO; internal class UInt64Tests { [Test] - public void GetBytes_ReturnsCorrectValue() + public void GetLittleEndianBytes_ReturnsCorrectValue_WithEndianness() { const ulong value = 0x0F; - byte[] bytes = BitConverter.IsLittleEndian - ? new byte[] {0x0F, 0, 0, 0, 0, 0, 0, 0} - : new byte[] {0, 0, 0, 0, 0, 0, 0, 0x0F}; - CollectionAssert.AreEqual(bytes, value.GetBytes()); + byte[] expected = { 0x0F, 0, 0, 0, 0, 0, 0, 0 }; + byte[] actual = value.GetLittleEndianBytes(); + + CollectionAssert.AreEqual(expected, actual); } [Test] - public void GetBytes_ReturnsCorrectValue_WithEndianness() + public void GetBigEndianBytes_ReturnsCorrectValue_WithEndianness() { const ulong value = 0x0F; - byte[] littleEndian = {0x0F, 0, 0, 0, 0, 0, 0, 0}; - byte[] bigEndian = {0, 0, 0, 0, 0, 0, 0, 0x0F}; + byte[] expected = { 0, 0, 0, 0, 0, 0, 0, 0x0F }; + byte[] actual = value.GetBigEndianBytes(); - CollectionAssert.AreEqual(littleEndian, value.GetBytes(Endianness.LittleEndian)); - CollectionAssert.AreEqual(bigEndian, value.GetBytes(Endianness.BigEndian)); + CollectionAssert.AreEqual(expected, actual); } [Test] - public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan() + public void TryWriteLittleEndian_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan() { const ulong value = 0x0F; - byte[] bytes = BitConverter.IsLittleEndian - ? new byte[] {0x0F, 0, 0, 0, 0, 0, 0, 0} - : new byte[] {0, 0, 0, 0, 0, 0, 0, 0x0F}; + byte[] expected = { 0x0F, 0, 0, 0, 0, 0, 0, 0 }; - Span buffer = stackalloc byte[8]; - Assert.That(value.TryWriteBytes(buffer)); - CollectionAssert.AreEqual(bytes, buffer.ToArray()); + Span actual = stackalloc byte[8]; + Assert.That(value.TryWriteLittleEndian(actual)); + + CollectionAssert.AreEqual(expected, actual.ToArray()); } [Test] - public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan_WithEndianness() + public void TryWriteBigEndian_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan() { const ulong value = 0x0F; - byte[] littleEndian = {0x0F, 0, 0, 0, 0, 0, 0, 0}; - byte[] bigEndian = {0, 0, 0, 0, 0, 0, 0, 0x0F}; + byte[] expected = { 0, 0, 0, 0, 0, 0, 0, 0x0F }; - Span buffer = stackalloc byte[8]; + Span actual = stackalloc byte[8]; + Assert.That(value.TryWriteBigEndian(actual)); - Assert.That(value.TryWriteBytes(buffer, Endianness.LittleEndian)); - CollectionAssert.AreEqual(littleEndian, buffer.ToArray()); - - Assert.That(value.TryWriteBytes(buffer, Endianness.BigEndian)); - CollectionAssert.AreEqual(bigEndian, buffer.ToArray()); + CollectionAssert.AreEqual(expected, actual.ToArray()); } [Test] - public void TryWriteBytes_ReturnsFalse_GivenSmallSpan() + public void TryWriteLittleEndian_RReturnsFalse_GivenSmallSpan() { const ulong value = 0x0F; Span buffer = stackalloc byte[0]; - Assert.That(value.TryWriteBytes(buffer), Is.False); + Assert.That(value.TryWriteLittleEndian(buffer), Is.False); + } + + [Test] + public void TryWriteBigEndian_ReturnsFalse_GivenSmallSpan() + { + const ulong value = 0x0F; + Span buffer = stackalloc byte[0]; + Assert.That(value.TryWriteBigEndian(buffer), Is.False); } } diff --git a/X10D/src/Endianness.cs b/X10D/src/Endianness.cs deleted file mode 100644 index 3b23c07..0000000 --- a/X10D/src/Endianness.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System.ComponentModel; - -namespace X10D; - -/// -/// Represents an enumeration of endianness values. -/// -public enum Endianness -{ - /// - /// The value should be read as though it uses little endian encoding. - /// - [Description("The value should be read as though it uses little endian encoding.")] LittleEndian, - - /// - /// The value should be read as though it uses big endian encoding. - /// - [Description("The value should be read as though it uses big endian encoding.")] BigEndian -} diff --git a/X10D/src/IO/DecimalExtensions.cs b/X10D/src/IO/DecimalExtensions.cs new file mode 100644 index 0000000..8058f70 --- /dev/null +++ b/X10D/src/IO/DecimalExtensions.cs @@ -0,0 +1,111 @@ +using System.Diagnostics.Contracts; +using System.Runtime.InteropServices; + +namespace X10D.IO; + +/// +/// IO-related extension methods for . +/// +public static class DecimalExtensions +{ + /// + /// Converts the current decimal number into an array of bytes, as little endian. + /// + /// The value. + /// An array of bytes with length 4. + [Pure] + public static byte[] GetBigEndianBytes(this decimal value) + { + Span buffer = stackalloc byte[4]; + value.TryWriteBigEndian(buffer); + return buffer.ToArray(); + } + + /// + /// Converts the current decimal number into an array of bytes, as little endian. + /// + /// The value. + /// An array of bytes with length 4. + [Pure] + public static byte[] GetLittleEndianBytes(this decimal value) + { + Span buffer = stackalloc byte[4]; + value.TryWriteLittleEndian(buffer); + return buffer.ToArray(); + } + + /// + /// Converts the current decimal number into a span of bytes, as big endian. + /// + /// The value. + /// The span of bytes where the value is to be written, as big endian. + /// if the conversion was successful; otherwise, . + public static bool TryWriteBigEndian(this decimal value, Span destination) + { + Span buffer = stackalloc int[4]; + GetBits(value, buffer); + + if (buffer[0].TryWriteBigEndian(destination[..4]) && + buffer[1].TryWriteBigEndian(destination[4..8]) && + buffer[2].TryWriteBigEndian(destination[8..12]) && + buffer[3].TryWriteBigEndian(destination[12..])) + { + if (BitConverter.IsLittleEndian) + { + destination.Reverse(); + } + + return true; + } + + destination.Clear(); + return false; + } + + /// + /// Converts the current decimal number into a span of bytes, as little endian. + /// + /// The value. + /// The span of bytes where the value is to be written, as little endian. + /// if the conversion was successful; otherwise, . + public static bool TryWriteLittleEndian(this decimal value, Span destination) + { + Span buffer = stackalloc int[4]; + GetBits(value, buffer); + + if (buffer[0].TryWriteLittleEndian(destination[..4]) && + buffer[1].TryWriteLittleEndian(destination[4..8]) && + buffer[2].TryWriteLittleEndian(destination[8..12]) && + buffer[3].TryWriteLittleEndian(destination[12..])) + { + if (!BitConverter.IsLittleEndian) + { + destination.Reverse(); + } + + return true; + } + + destination.Clear(); + return false; + } + + private static void GetBits(decimal value, Span destination) + { +#if NET5_0_OR_GREATER + decimal.GetBits(value, destination); +#else + Span buffer = stackalloc byte[16]; + MemoryMarshal.Write(buffer, ref value); + + var flags = MemoryMarshal.Read(buffer[..4]); + var hi = MemoryMarshal.Read(buffer[4..8]); + var lo = MemoryMarshal.Read(buffer[8..]); + + destination[0] = flags; + destination[1] = hi; + destination[2] = (int)(lo & 0xFFFFFFFF); + destination[3] = (int)(lo >> 32); +#endif + } +} diff --git a/X10D/src/IO/DoubleExtensions.cs b/X10D/src/IO/DoubleExtensions.cs index f71e4be..728cada 100644 --- a/X10D/src/IO/DoubleExtensions.cs +++ b/X10D/src/IO/DoubleExtensions.cs @@ -10,58 +10,70 @@ namespace X10D.IO; public static class DoubleExtensions { /// - /// Returns the current double-precision floating-point value as an array of bytes. + /// Converts the current double-precision floating-point number into an array of bytes, as little endian. /// - /// The number to convert. - /// An array of bytes with length 8. + /// The value. + /// An array of bytes with length 4. [Pure] - public static byte[] GetBytes(this double value) + public static byte[] GetBigEndianBytes(this double value) { - byte[] buffer = new byte[8]; - value.TryWriteBytes(buffer); - return buffer; + Span buffer = stackalloc byte[8]; + value.TryWriteBigEndian(buffer); + return buffer.ToArray(); } /// - /// Returns the current double-precision floating-point value as an array of bytes. + /// Converts the current double-precision floating-point number into an array of bytes, as little endian. /// - /// The number to convert. - /// The endianness with which to write the bytes. - /// An array of bytes with length 8. + /// The value. + /// An array of bytes with length 4. [Pure] - public static byte[] GetBytes(this double value, Endianness endianness) + public static byte[] GetLittleEndianBytes(this double value) { - byte[] buffer = new byte[8]; - value.TryWriteBytes(buffer, endianness); - return buffer; + Span buffer = stackalloc byte[8]; + value.TryWriteLittleEndian(buffer); + return buffer.ToArray(); } /// - /// Converts the current double-precision floating-point into a span of bytes. + /// Converts the current double-precision floating-point number into a span of bytes, as big endian. /// - /// The value. - /// When this method returns, the bytes representing the converted . + /// The value. + /// The span of bytes where the value is to be written, as big endian. /// if the conversion was successful; otherwise, . - public static bool TryWriteBytes(this double value, Span destination) + public static bool TryWriteBigEndian(this double value, Span destination) { - return BitConverter.TryWriteBytes(destination, value); - } - - /// - /// Converts the current double-precision floating-point into a span of bytes. - /// - /// The value. - /// When this method returns, the bytes representing the converted . - /// The endianness with which to write the bytes. - /// if the conversion was successful; otherwise, . - public static bool TryWriteBytes(this double value, Span destination, Endianness endianness) - { - if (BitConverter.IsLittleEndian == (endianness == Endianness.BigEndian)) +#if NET5_0_OR_GREATER + return BinaryPrimitives.TryWriteDoubleBigEndian(destination, value); +#else + if (BitConverter.IsLittleEndian) { - long tmp = BinaryPrimitives.ReverseEndianness(BitConverter.DoubleToInt64Bits(value)); - value = BitConverter.Int64BitsToDouble(tmp); + return MemoryMarshal.TryWrite(destination, ref value); } - return MemoryMarshal.TryWrite(destination, ref value); + long tmp = BinaryPrimitives.ReverseEndianness(BitConverter.DoubleToInt64Bits(value)); + return MemoryMarshal.TryWrite(destination, ref tmp); +#endif + } + + /// + /// Converts the current double-precision floating-point number into a span of bytes, as little endian. + /// + /// The value. + /// The span of bytes where the value is to be written, as little endian. + /// if the conversion was successful; otherwise, . + public static bool TryWriteLittleEndian(this double value, Span destination) + { +#if NET5_0_OR_GREATER + return BinaryPrimitives.TryWriteDoubleLittleEndian(destination, value); +#else + if (!BitConverter.IsLittleEndian) + { + return MemoryMarshal.TryWrite(destination, ref value); + } + + long tmp = BinaryPrimitives.ReverseEndianness(BitConverter.DoubleToInt64Bits(value)); + return MemoryMarshal.TryWrite(destination, ref tmp); +#endif } } diff --git a/X10D/src/IO/Int16Extensions.cs b/X10D/src/IO/Int16Extensions.cs index 60b0b87..6c0dcc4 100644 --- a/X10D/src/IO/Int16Extensions.cs +++ b/X10D/src/IO/Int16Extensions.cs @@ -9,54 +9,50 @@ namespace X10D.IO; public static class Int16Extensions { /// - /// Returns the current 16-bit signed integer value as an array of bytes. - /// - /// The number to convert. - /// An array of bytes with length 2. - [Pure] - public static byte[] GetBytes(this short value) - { - byte[] buffer = new byte[2]; - value.TryWriteBytes(buffer); - return buffer; - } - - /// - /// Returns the current 16-bit signed integer value as an array of bytes. - /// - /// The number to convert. - /// The endianness with which to write the bytes. - /// An array of bytes with length 2. - [Pure] - public static byte[] GetBytes(this short value, Endianness endianness) - { - byte[] buffer = new byte[2]; - value.TryWriteBytes(buffer, endianness); - return buffer; - } - - /// - /// Converts the current 16-bit signed integer into a span of bytes. + /// Converts the current 16-bit signed integer into an array of bytes, as big endian. /// /// The value. - /// When this method returns, the bytes representing the converted . - /// if the conversion was successful; otherwise, . - public static bool TryWriteBytes(this short value, Span destination) + /// An array of bytes with length 8. + [Pure] + public static byte[] GetBigEndianBytes(this short value) { - return BitConverter.TryWriteBytes(destination, value); + Span buffer = stackalloc byte[2]; + value.TryWriteBigEndian(buffer); + return buffer.ToArray(); } /// - /// Converts the current 16-bit signed integer into a span of bytes. + /// Converts the current 16-bit signed integer into an array of bytes, as big endian. /// /// The value. - /// When this method returns, the bytes representing the converted . - /// The endianness with which to write the bytes. - /// if the conversion was successful; otherwise, . - public static bool TryWriteBytes(this short value, Span destination, Endianness endianness) + /// An array of bytes with length 8. + [Pure] + public static byte[] GetLittleEndianBytes(this short value) { - return endianness == Endianness.BigEndian - ? BinaryPrimitives.TryWriteInt16BigEndian(destination, value) - : BinaryPrimitives.TryWriteInt16LittleEndian(destination, value); + Span buffer = stackalloc byte[2]; + value.TryWriteLittleEndian(buffer); + return buffer.ToArray(); + } + + /// + /// Writes the current 16-bit signed integer into a span of bytes, as big endian. + /// + /// The value. + /// The span of bytes where the value is to be written, as big endian. + /// if the conversion was successful; otherwise, . + public static bool TryWriteBigEndian(this short value, Span destination) + { + return BinaryPrimitives.TryWriteInt16BigEndian(destination, value); + } + + /// + /// Writes the current 16-bit signed integer into a span of bytes, as little endian. + /// + /// The value. + /// The span of bytes where the value is to be written, as little endian. + /// if the conversion was successful; otherwise, . + public static bool TryWriteLittleEndian(this short value, Span destination) + { + return BinaryPrimitives.TryWriteInt16LittleEndian(destination, value); } } diff --git a/X10D/src/IO/Int32Extensions.cs b/X10D/src/IO/Int32Extensions.cs index a349dec..7f9d6cb 100644 --- a/X10D/src/IO/Int32Extensions.cs +++ b/X10D/src/IO/Int32Extensions.cs @@ -9,54 +9,50 @@ namespace X10D.IO; public static class Int32Extensions { /// - /// Returns the current 32-bit signed integer value as an array of bytes. + /// Converts the current 32-bit signed integer into an array of bytes, as big endian. /// - /// The number to convert. - /// An array of bytes with length 4. + /// The value. + /// An array of bytes with length 8. [Pure] - public static byte[] GetBytes(this int value) + public static byte[] GetBigEndianBytes(this int value) { - byte[] buffer = new byte[4]; - value.TryWriteBytes(buffer); - return buffer; - } - - /// - /// Returns the current 32-bit signed integer value as an array of bytes. - /// - /// The number to convert. - /// The endianness with which to write the bytes. - /// An array of bytes with length 4. - [Pure] - public static byte[] GetBytes(this int value, Endianness endianness) - { - byte[] buffer = new byte[4]; - value.TryWriteBytes(buffer, endianness); + Span buffer = stackalloc byte[4]; + value.TryWriteBigEndian(buffer); return buffer.ToArray(); } /// - /// Converts the current 32-bit signed integer into a span of bytes. + /// Converts the current 32-bit signed integer into an array of bytes, as big endian. /// /// The value. - /// When this method returns, the bytes representing the converted . - /// if the conversion was successful; otherwise, . - public static bool TryWriteBytes(this int value, Span destination) + /// An array of bytes with length 8. + [Pure] + public static byte[] GetLittleEndianBytes(this int value) { - return BitConverter.TryWriteBytes(destination, value); + Span buffer = stackalloc byte[4]; + value.TryWriteLittleEndian(buffer); + return buffer.ToArray(); } /// - /// Converts the current 32-bit signed integer into a span of bytes. + /// Writes the current 32-bit signed integer into a span of bytes, as big endian. /// /// The value. - /// When this method returns, the bytes representing the converted . - /// The endianness with which to write the bytes. + /// The span of bytes where the value is to be written, as big endian. /// if the conversion was successful; otherwise, . - public static bool TryWriteBytes(this int value, Span destination, Endianness endianness) + public static bool TryWriteBigEndian(this int value, Span destination) { - return endianness == Endianness.BigEndian - ? BinaryPrimitives.TryWriteInt32BigEndian(destination, value) - : BinaryPrimitives.TryWriteInt32LittleEndian(destination, value); + return BinaryPrimitives.TryWriteInt32BigEndian(destination, value); + } + + /// + /// Writes the current 32-bit signed integer into a span of bytes, as little endian. + /// + /// The value. + /// The span of bytes where the value is to be written, as little endian. + /// if the conversion was successful; otherwise, . + public static bool TryWriteLittleEndian(this int value, Span destination) + { + return BinaryPrimitives.TryWriteInt32LittleEndian(destination, value); } } diff --git a/X10D/src/IO/Int64Extensions.cs b/X10D/src/IO/Int64Extensions.cs index 2fd7f05..118fc49 100644 --- a/X10D/src/IO/Int64Extensions.cs +++ b/X10D/src/IO/Int64Extensions.cs @@ -9,54 +9,50 @@ namespace X10D.IO; public static class Int64Extensions { /// - /// Returns the current 64-bit signed integer value as an array of bytes. + /// Converts the current 64-bit signed integer into an array of bytes, as big endian. /// - /// The number to convert. + /// The value. /// An array of bytes with length 8. [Pure] - public static byte[] GetBytes(this long value) + public static byte[] GetBigEndianBytes(this long value) { Span buffer = stackalloc byte[8]; - value.TryWriteBytes(buffer); + value.TryWriteBigEndian(buffer); return buffer.ToArray(); } /// - /// Returns the current 64-bit signed integer value as an array of bytes. + /// Converts the current 64-bit signed integer into an array of bytes, as big endian. /// - /// The number to convert. - /// The endianness with which to write the bytes. + /// The value. /// An array of bytes with length 8. [Pure] - public static byte[] GetBytes(this long value, Endianness endianness) + public static byte[] GetLittleEndianBytes(this long value) { Span buffer = stackalloc byte[8]; - value.TryWriteBytes(buffer, endianness); + value.TryWriteLittleEndian(buffer); return buffer.ToArray(); } /// - /// Converts the current 64-bit signed integer a span of bytes. + /// Writes the current 64-bit signed integer into a span of bytes, as big endian. /// /// The value. - /// When this method returns, the bytes representing the converted . + /// The span of bytes where the value is to be written, as big endian. /// if the conversion was successful; otherwise, . - public static bool TryWriteBytes(this long value, Span destination) + public static bool TryWriteBigEndian(this long value, Span destination) { - return BitConverter.TryWriteBytes(destination, value); + return BinaryPrimitives.TryWriteInt64BigEndian(destination, value); } /// - /// Converts the current 64-bit signed integer a span of bytes. + /// Writes the current 64-bit signed integer into a span of bytes, as little endian. /// /// The value. - /// When this method returns, the bytes representing the converted . - /// The endianness with which to write the bytes. + /// The span of bytes where the value is to be written, as little endian. /// if the conversion was successful; otherwise, . - public static bool TryWriteBytes(this long value, Span destination, Endianness endianness) + public static bool TryWriteLittleEndian(this long value, Span destination) { - return endianness == Endianness.BigEndian - ? BinaryPrimitives.TryWriteInt64BigEndian(destination, value) - : BinaryPrimitives.TryWriteInt64LittleEndian(destination, value); + return BinaryPrimitives.TryWriteInt64LittleEndian(destination, value); } } diff --git a/X10D/src/IO/SingleExtensions.cs b/X10D/src/IO/SingleExtensions.cs index 5db19f5..d799261 100644 --- a/X10D/src/IO/SingleExtensions.cs +++ b/X10D/src/IO/SingleExtensions.cs @@ -1,6 +1,8 @@ using System.Buffers.Binary; using System.Diagnostics.Contracts; +#if !NET5_0_OR_GREATER using System.Runtime.InteropServices; +#endif namespace X10D.IO; @@ -10,58 +12,70 @@ namespace X10D.IO; public static class SingleExtensions { /// - /// Returns the current single-precision floating-point value as an array of bytes. + /// Converts the current single-precision floating-point number into an array of bytes, as little endian. /// - /// The number to convert. + /// The value. /// An array of bytes with length 4. [Pure] - public static byte[] GetBytes(this float value) + public static byte[] GetBigEndianBytes(this float value) { Span buffer = stackalloc byte[4]; - value.TryWriteBytes(buffer); + value.TryWriteBigEndian(buffer); return buffer.ToArray(); } /// - /// Returns the current single-precision floating-point value as an array of bytes. + /// Converts the current single-precision floating-point number into an array of bytes, as little endian. /// - /// The number to convert. - /// The endianness with which to write the bytes. + /// The value. /// An array of bytes with length 4. [Pure] - public static byte[] GetBytes(this float value, Endianness endianness) + public static byte[] GetLittleEndianBytes(this float value) { Span buffer = stackalloc byte[4]; - value.TryWriteBytes(buffer, endianness); + value.TryWriteLittleEndian(buffer); return buffer.ToArray(); } /// - /// Converts the current single-precision floating-point into a span of bytes. + /// Converts the current single-precision floating-point number into a span of bytes, as big endian. /// /// The value. - /// When this method returns, the bytes representing the converted . + /// The span of bytes where the value is to be written, as big endian. /// if the conversion was successful; otherwise, . - public static bool TryWriteBytes(this float value, Span destination) + public static bool TryWriteBigEndian(this float value, Span destination) { - return BitConverter.TryWriteBytes(destination, value); - } - - /// - /// Converts the current single-precision floating-point into a span of bytes. - /// - /// The value. - /// When this method returns, the bytes representing the converted . - /// The endianness with which to write the bytes. - /// if the conversion was successful; otherwise, . - public static bool TryWriteBytes(this float value, Span destination, Endianness endianness) - { - if (BitConverter.IsLittleEndian == (endianness == Endianness.BigEndian)) +#if NET5_0_OR_GREATER + return BinaryPrimitives.TryWriteSingleBigEndian(destination, value); +#else + if (BitConverter.IsLittleEndian) { - int tmp = BinaryPrimitives.ReverseEndianness(BitConverter.SingleToInt32Bits(value)); - value = BitConverter.Int32BitsToSingle(tmp); + return MemoryMarshal.TryWrite(destination, ref value); } - return MemoryMarshal.TryWrite(destination, ref value); + int tmp = BinaryPrimitives.ReverseEndianness(BitConverter.SingleToInt32Bits(value)); + return MemoryMarshal.TryWrite(destination, ref tmp); +#endif + } + + /// + /// Converts the current single-precision floating-point number into a span of bytes, as little endian. + /// + /// The value. + /// The span of bytes where the value is to be written, as little endian. + /// if the conversion was successful; otherwise, . + public static bool TryWriteLittleEndian(this float value, Span destination) + { +#if NET5_0_OR_GREATER + return BinaryPrimitives.TryWriteSingleLittleEndian(destination, value); +#else + if (!BitConverter.IsLittleEndian) + { + return MemoryMarshal.TryWrite(destination, ref value); + } + + int tmp = BinaryPrimitives.ReverseEndianness(BitConverter.SingleToInt32Bits(value)); + return MemoryMarshal.TryWrite(destination, ref tmp); +#endif } } diff --git a/X10D/src/IO/StreamExtensions.cs b/X10D/src/IO/StreamExtensions.cs index d1d44db..9bc7243 100644 --- a/X10D/src/IO/StreamExtensions.cs +++ b/X10D/src/IO/StreamExtensions.cs @@ -1,5 +1,4 @@ -using System.Buffers.Binary; -using System.Diagnostics.CodeAnalysis; +using System.Buffers.Binary; using System.Reflection; using System.Runtime.InteropServices; using System.Security.Cryptography; @@ -11,9 +10,6 @@ namespace X10D.IO; ///
public static class StreamExtensions { - private static readonly Endianness DefaultEndianness = - BitConverter.IsLittleEndian ? Endianness.LittleEndian : Endianness.BigEndian; - /// /// Returns the hash of the current stream as an array of bytes using the specified hash algorithm. /// @@ -64,42 +60,20 @@ public static class StreamExtensions } /// - /// Reads a decimal value from the current stream using the system's default endian encoding, and advances the stream - /// position by sixteen bytes. - /// - /// The stream to read. - /// A sixteen-byte decimal value read from the stream. - public static decimal ReadDecimal(this Stream stream) - { - return stream.ReadDecimal(DefaultEndianness); - } - - /// - /// Reads a decimal value from the current stream using a specified endian encoding, and advances the stream position - /// by sixteen bytes. + /// Reads an from the current stream as big endian, and advances the stream position by sixteen + /// bytes. /// /// The stream from which the value should be read. - /// The endian encoding to use. - /// A decimal value read from the stream. - public static decimal ReadDecimal(this Stream stream, Endianness endianness) + /// The big endian value. + /// is + /// does not support reading. + public static decimal ReadDecimalBigEndian(this Stream stream) { if (stream is null) { throw new ArgumentNullException(nameof(stream)); } -#if NET5_0_OR_GREATER - if (!Enum.IsDefined(endianness)) - { - throw new ArgumentOutOfRangeException(nameof(endianness)); - } -#else - if (!Enum.IsDefined(typeof(Endianness), endianness)) - { - throw new ArgumentOutOfRangeException(nameof(endianness)); - } -#endif - if (!stream.CanRead) { throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); @@ -109,436 +83,496 @@ public static class StreamExtensions const int int32Size = sizeof(int); const int partitionSize = decimalSize / int32Size; - var bits = new int[partitionSize]; + Span buffer = stackalloc int[partitionSize]; for (var index = 0; index < partitionSize; index++) { - bits[index] = stream.ReadInt32(endianness); + buffer[index] = stream.ReadInt32BigEndian(); } - if (endianness != DefaultEndianness) + if (BitConverter.IsLittleEndian) { - Array.Reverse(bits); + buffer.Reverse(); } - return new decimal(bits); +#if NET5_0_OR_GREATER + return new decimal(buffer); +#else + return new decimal(buffer.ToArray()); +#endif } /// - /// Reads a double-precision floating point value from the current stream using the system's default endian encoding, - /// and advances the stream position by eight bytes. + /// Reads an from the current stream as big endian, and advances the stream position by sixteen + /// bytes. /// /// The stream from which the value should be read. - /// A double-precision floating point value read from the stream. - public static double ReadDouble(this Stream stream) - { - return stream.ReadDouble(DefaultEndianness); - } - - /// - /// Reads a double-precision floating point value from the current stream using a specified endian encoding, and - /// advances the stream position by eight bytes. - /// - /// The stream from which the value should be read. - /// The endian encoding to use. - /// A double-precision floating point value read from the stream. - public static double ReadDouble(this Stream stream, Endianness endianness) + /// The big endian value. + /// is + /// does not support reading. + public static decimal ReadDecimalLittleEndian(this Stream stream) { if (stream is null) { throw new ArgumentNullException(nameof(stream)); } -#if NET5_0_OR_GREATER - if (!Enum.IsDefined(endianness)) - { - throw new ArgumentOutOfRangeException(nameof(endianness)); - } -#else - if (!Enum.IsDefined(typeof(Endianness), endianness)) - { - throw new ArgumentOutOfRangeException(nameof(endianness)); - } -#endif - if (!stream.CanRead) { throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); } - Span buffer = stackalloc byte[sizeof(double)]; - stream.Read(buffer); + const int decimalSize = sizeof(decimal); + const int int32Size = sizeof(int); + const int partitionSize = decimalSize / int32Size; - var value = MemoryMarshal.Read(buffer); - - if (BitConverter.IsLittleEndian == (endianness == Endianness.BigEndian)) + Span buffer = stackalloc int[partitionSize]; + for (var index = 0; index < partitionSize; index++) { - long tmp = BinaryPrimitives.ReverseEndianness(BitConverter.DoubleToInt64Bits(value)); - value = BitConverter.Int64BitsToDouble(tmp); + buffer[index] = stream.ReadInt32LittleEndian(); } - return value; + if (!BitConverter.IsLittleEndian) + { + buffer.Reverse(); + } + +#if NET5_0_OR_GREATER + return new decimal(buffer); +#else + return new decimal(buffer.ToArray()); +#endif } /// - /// Reads a two-byte signed integer from the current stream using the system's default endian encoding, and advances - /// the stream position by two bytes. + /// Reads an from the current stream as big endian, and advances the stream position by eight bytes. /// /// The stream from which the value should be read. - /// An two-byte signed integer read from the stream. - public static short ReadInt16(this Stream stream) - { - return stream.ReadInt16(DefaultEndianness); - } - - /// - /// Reads a two-byte signed integer from the current stream using the specified endian encoding, and advances the - /// stream position by two bytes. - /// - /// The stream from which the value should be read. - /// The endian encoding to use. - /// An two-byte unsigned integer read from the stream. - public static short ReadInt16(this Stream stream, Endianness endianness) + /// The big endian value. + /// is + /// does not support reading. + public static double ReadDoubleBigEndian(this Stream stream) { if (stream is null) { throw new ArgumentNullException(nameof(stream)); } -#if NET5_0_OR_GREATER - if (!Enum.IsDefined(endianness)) - { - throw new ArgumentOutOfRangeException(nameof(endianness)); - } -#else - if (!Enum.IsDefined(typeof(Endianness), endianness)) - { - throw new ArgumentOutOfRangeException(nameof(endianness)); - } -#endif - if (!stream.CanRead) { throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); } - Span buffer = stackalloc byte[sizeof(short)]; - stream.Read(buffer); + Span buffer = stackalloc byte[8]; + _ = stream.Read(buffer); +#if NET5_0_OR_GREATER + return BinaryPrimitives.ReadDoubleBigEndian(buffer); +#else + if (BitConverter.IsLittleEndian) + { + buffer.Reverse(); + } - return endianness == Endianness.LittleEndian - ? BinaryPrimitives.ReadInt16LittleEndian(buffer) - : BinaryPrimitives.ReadInt16BigEndian(buffer); + return MemoryMarshal.Read(buffer); +#endif } /// - /// Reads a four-byte signed integer from the current stream using the system's default endian encoding, and advances - /// the stream position by four bytes. + /// Reads an from the current stream as little endian, and advances the stream position by eight + /// bytes. /// /// The stream from which the value should be read. - /// An four-byte signed integer read from the stream. - public static int ReadInt32(this Stream stream) - { - return stream.ReadInt32(DefaultEndianness); - } - - /// - /// Reads a four-byte signed integer from the current stream using the specified endian encoding, and advances the - /// stream position by four bytes. - /// - /// The stream from which the value should be read. - /// The endian encoding to use. - /// An four-byte unsigned integer read from the stream. - public static int ReadInt32(this Stream stream, Endianness endianness) + /// The little endian value. + /// is + /// does not support reading. + public static double ReadDoubleLittleEndian(this Stream stream) { if (stream is null) { throw new ArgumentNullException(nameof(stream)); } -#if NET5_0_OR_GREATER - if (!Enum.IsDefined(endianness)) - { - throw new ArgumentOutOfRangeException(nameof(endianness)); - } -#else - if (!Enum.IsDefined(typeof(Endianness), endianness)) - { - throw new ArgumentOutOfRangeException(nameof(endianness)); - } -#endif - if (!stream.CanRead) { throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); } - Span buffer = stackalloc byte[sizeof(int)]; - stream.Read(buffer); + Span buffer = stackalloc byte[8]; + _ = stream.Read(buffer); +#if NET5_0_OR_GREATER + return BinaryPrimitives.ReadDoubleLittleEndian(buffer); +#else + if (!BitConverter.IsLittleEndian) + { + buffer.Reverse(); + } - return endianness == Endianness.LittleEndian - ? BinaryPrimitives.ReadInt32LittleEndian(buffer) - : BinaryPrimitives.ReadInt32BigEndian(buffer); + return MemoryMarshal.Read(buffer); +#endif } /// - /// Reads an eight-byte signed integer from the current stream using the system's default endian encoding, and - /// advances the stream position by eight bytes. + /// Reads an from the current stream as big endian, and advances the stream position by two bytes. /// /// The stream from which the value should be read. - /// An eight-byte signed integer read from the stream. - public static long ReadInt64(this Stream stream) - { - return stream.ReadInt64(DefaultEndianness); - } - - /// - /// Reads an eight-byte signed integer from the current stream using the specified endian encoding, and advances the - /// stream position by eight bytes. - /// - /// The stream from which the value should be read. - /// The endian encoding to use. - /// An eight-byte unsigned integer read from the stream. - public static long ReadInt64(this Stream stream, Endianness endianness) + /// The big endian value. + /// is + /// does not support reading. + public static short ReadInt16BigEndian(this Stream stream) { if (stream is null) { throw new ArgumentNullException(nameof(stream)); } -#if NET5_0_OR_GREATER - if (!Enum.IsDefined(endianness)) - { - throw new ArgumentOutOfRangeException(nameof(endianness)); - } -#else - if (!Enum.IsDefined(typeof(Endianness), endianness)) - { - throw new ArgumentOutOfRangeException(nameof(endianness)); - } -#endif - if (!stream.CanRead) { throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); } - Span buffer = stackalloc byte[sizeof(long)]; - stream.Read(buffer); - - return endianness == Endianness.LittleEndian - ? BinaryPrimitives.ReadInt64LittleEndian(buffer) - : BinaryPrimitives.ReadInt64BigEndian(buffer); + Span buffer = stackalloc byte[2]; + _ = stream.Read(buffer); + return BinaryPrimitives.ReadInt16BigEndian(buffer); } /// - /// Reads a single-precision floating point value from the current stream using the system's default endian encoding, - /// and advances the stream position by four bytes. + /// Reads an from the current stream as little endian, and advances the stream position by two bytes. /// /// The stream from which the value should be read. - /// A single-precision floating point value read from the stream. - public static double ReadSingle(this Stream stream) - { - return stream.ReadSingle(DefaultEndianness); - } - - /// - /// Reads a double-precision floating point value from the current stream using a specified endian encoding, and - /// advances the stream position by four bytes. - /// - /// The stream from which the value should be read. - /// The endian encoding to use. - /// A single-precision floating point value read from the stream. - public static float ReadSingle(this Stream stream, Endianness endianness) + /// The little endian value. + /// is + /// does not support reading. + public static short ReadInt16LittleEndian(this Stream stream) { if (stream is null) { throw new ArgumentNullException(nameof(stream)); } -#if NET5_0_OR_GREATER - if (!Enum.IsDefined(endianness)) + if (!stream.CanRead) { - throw new ArgumentOutOfRangeException(nameof(endianness)); + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); } -#else - if (!Enum.IsDefined(typeof(Endianness), endianness)) + + Span buffer = stackalloc byte[2]; + _ = stream.Read(buffer); + return BinaryPrimitives.ReadInt16LittleEndian(buffer); + } + + /// + /// Reads an from the current stream as big endian, and advances the stream position by four bytes. + /// + /// The stream from which the value should be read. + /// The big endian value. + /// is + /// does not support reading. + public static int ReadInt32BigEndian(this Stream stream) + { + if (stream is null) { - throw new ArgumentOutOfRangeException(nameof(endianness)); + throw new ArgumentNullException(nameof(stream)); } -#endif if (!stream.CanRead) { throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); } - Span buffer = stackalloc byte[sizeof(float)]; - stream.Read(buffer); - - var value = MemoryMarshal.Read(buffer); - - if (BitConverter.IsLittleEndian == (endianness == Endianness.BigEndian)) - { - int tmp = BinaryPrimitives.ReverseEndianness(BitConverter.SingleToInt32Bits(value)); - value = BitConverter.Int32BitsToSingle(tmp); - } - - return value; + Span buffer = stackalloc byte[4]; + _ = stream.Read(buffer); + return BinaryPrimitives.ReadInt32BigEndian(buffer); } /// - /// Reads a two-byte unsigned integer from the current stream using the system's default endian encoding, and advances - /// the stream position by two bytes. + /// Reads an from the current stream as little endian, and advances the stream position by four bytes. /// /// The stream from which the value should be read. - /// An two-byte unsigned integer read from the stream. + /// The little endian value. + /// is + /// does not support reading. + public static int ReadInt32LittleEndian(this Stream stream) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanRead) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); + } + + Span buffer = stackalloc byte[4]; + _ = stream.Read(buffer); + return BinaryPrimitives.ReadInt32LittleEndian(buffer); + } + + /// + /// Reads an from the current stream as big endian, and advances the stream position by eight bytes. + /// + /// The stream from which the value should be read. + /// The big endian value. + /// is + /// does not support reading. + public static long ReadInt64BigEndian(this Stream stream) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanRead) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); + } + + Span buffer = stackalloc byte[8]; + _ = stream.Read(buffer); + return BinaryPrimitives.ReadInt64BigEndian(buffer); + } + + /// + /// Reads an from the current stream as little endian, and advances the stream position by eight + /// bytes. + /// + /// The stream from which the value should be read. + /// The little endian value. + /// is + /// does not support reading. + public static long ReadInt64LittleEndian(this Stream stream) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanRead) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); + } + + Span buffer = stackalloc byte[8]; + _ = stream.Read(buffer); + return BinaryPrimitives.ReadInt64LittleEndian(buffer); + } + + /// + /// Reads an from the current stream as big endian, and advances the stream position by four bytes. + /// + /// The stream from which the value should be read. + /// The big endian value. + /// is + /// does not support reading. [CLSCompliant(false)] - public static ushort ReadUInt16(this Stream stream) - { - return stream.ReadUInt16(DefaultEndianness); - } - - /// - /// Reads a two-byte unsigned integer from the current stream using the specified endian encoding, and advances the - /// stream position by two bytes. - /// - /// The stream from which the value should be read. - /// The endian encoding to use. - /// An two-byte unsigned integer read from the stream. - [CLSCompliant(false)] - public static ushort ReadUInt16(this Stream stream, Endianness endianness) + public static float ReadSingleBigEndian(this Stream stream) { if (stream is null) { throw new ArgumentNullException(nameof(stream)); } -#if NET5_0_OR_GREATER - if (!Enum.IsDefined(endianness)) - { - throw new ArgumentOutOfRangeException(nameof(endianness)); - } -#else - if (!Enum.IsDefined(typeof(Endianness), endianness)) - { - throw new ArgumentOutOfRangeException(nameof(endianness)); - } -#endif - if (!stream.CanRead) { throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); } - Span buffer = stackalloc byte[sizeof(ushort)]; - stream.Read(buffer); + Span buffer = stackalloc byte[4]; + _ = stream.Read(buffer); +#if NET5_0_OR_GREATER + return BinaryPrimitives.ReadSingleBigEndian(buffer); +#else + if (BitConverter.IsLittleEndian) + { + buffer.Reverse(); + } - return endianness == Endianness.LittleEndian - ? BinaryPrimitives.ReadUInt16LittleEndian(buffer) - : BinaryPrimitives.ReadUInt16BigEndian(buffer); + return MemoryMarshal.Read(buffer); +#endif } /// - /// Reads a four-byte unsigned integer from the current stream using the system's default endian encoding, and - /// advances the stream position by four bytes. + /// Reads an from the current stream as little endian, and advances the stream position by four + /// bytes. /// /// The stream from which the value should be read. - /// An four-byte unsigned integer read from the stream. + /// The little endian value. + /// is + /// does not support reading. [CLSCompliant(false)] - public static uint ReadUInt32(this Stream stream) - { - return stream.ReadUInt32(DefaultEndianness); - } - - /// - /// Reads a four-byte unsigned integer from the current stream using the specified endian encoding, and advances the - /// stream position by four bytes. - /// - /// The stream from which the value should be read. - /// The endian encoding to use. - /// An four-byte unsigned integer read from the stream. - [CLSCompliant(false)] - public static uint ReadUInt32(this Stream stream, Endianness endianness) + public static float ReadSingleLittleEndian(this Stream stream) { if (stream is null) { throw new ArgumentNullException(nameof(stream)); } -#if NET5_0_OR_GREATER - if (!Enum.IsDefined(endianness)) - { - throw new ArgumentOutOfRangeException(nameof(endianness)); - } -#else - if (!Enum.IsDefined(typeof(Endianness), endianness)) - { - throw new ArgumentOutOfRangeException(nameof(endianness)); - } -#endif - if (!stream.CanRead) { throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); } - Span buffer = stackalloc byte[sizeof(uint)]; - stream.Read(buffer); + Span buffer = stackalloc byte[4]; + _ = stream.Read(buffer); +#if NET5_0_OR_GREATER + return BinaryPrimitives.ReadSingleLittleEndian(buffer); +#else + if (!BitConverter.IsLittleEndian) + { + buffer.Reverse(); + } - return endianness == Endianness.LittleEndian - ? BinaryPrimitives.ReadUInt32LittleEndian(buffer) - : BinaryPrimitives.ReadUInt32BigEndian(buffer); + return MemoryMarshal.Read(buffer); +#endif } /// - /// Reads an eight-byte unsigned integer from the current stream using the system's default endian encoding, and - /// advances the stream position by eight bytes. + /// Reads an from the current stream as big endian, and advances the stream position by two bytes. /// /// The stream from which the value should be read. - /// An eight-byte unsigned integer read from the stream. + /// The big endian value. + /// is + /// does not support reading. [CLSCompliant(false)] - public static ulong ReadUInt64(this Stream stream) - { - return stream.ReadUInt64(DefaultEndianness); - } - - /// - /// Reads an eight-byte unsigned integer from the current stream using the specified endian encoding, and advances the - /// stream position by eight bytes. - /// - /// The stream from which the value should be read. - /// The endian encoding to use. - /// An eight-byte unsigned integer read from the stream. - [CLSCompliant(false)] - public static ulong ReadUInt64(this Stream stream, Endianness endianness) + public static ushort ReadUInt16BigEndian(this Stream stream) { if (stream is null) { throw new ArgumentNullException(nameof(stream)); } -#if NET5_0_OR_GREATER - if (!Enum.IsDefined(endianness)) + if (!stream.CanRead) { - throw new ArgumentOutOfRangeException(nameof(endianness)); + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); } -#else - if (!Enum.IsDefined(typeof(Endianness), endianness)) + + Span buffer = stackalloc byte[2]; + _ = stream.Read(buffer); + return BinaryPrimitives.ReadUInt16BigEndian(buffer); + } + + /// + /// Reads an from the current stream as little endian, and advances the stream position by two bytes. + /// + /// The stream from which the value should be read. + /// The little endian value. + /// is + /// does not support reading. + [CLSCompliant(false)] + public static ushort ReadUInt16LittleEndian(this Stream stream) + { + if (stream is null) { - throw new ArgumentOutOfRangeException(nameof(endianness)); + throw new ArgumentNullException(nameof(stream)); } -#endif if (!stream.CanRead) { throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); } - Span buffer = stackalloc byte[sizeof(ulong)]; - stream.Read(buffer); + Span buffer = stackalloc byte[2]; + _ = stream.Read(buffer); + return BinaryPrimitives.ReadUInt16LittleEndian(buffer); + } - return endianness == Endianness.LittleEndian - ? BinaryPrimitives.ReadUInt64LittleEndian(buffer) - : BinaryPrimitives.ReadUInt64BigEndian(buffer); + /// + /// Reads an from the current stream as big endian, and advances the stream position by four bytes. + /// + /// The stream from which the value should be read. + /// The big endian value. + /// is + /// does not support reading. + [CLSCompliant(false)] + public static uint ReadUInt32BigEndian(this Stream stream) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanRead) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); + } + + Span buffer = stackalloc byte[4]; + _ = stream.Read(buffer); + return BinaryPrimitives.ReadUInt32BigEndian(buffer); + } + + /// + /// Reads an from the current stream as little endian, and advances the stream position by four bytes. + /// + /// The stream from which the value should be read. + /// The little endian value. + /// is + /// does not support reading. + [CLSCompliant(false)] + public static uint ReadUInt32LittleEndian(this Stream stream) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanRead) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); + } + + Span buffer = stackalloc byte[4]; + _ = stream.Read(buffer); + return BinaryPrimitives.ReadUInt32LittleEndian(buffer); + } + + /// + /// Reads an from the current stream as big endian, and advances the stream position by eight bytes. + /// + /// The stream from which the value should be read. + /// The big endian value. + /// is + /// does not support reading. + [CLSCompliant(false)] + public static ulong ReadUInt64BigEndian(this Stream stream) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanRead) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); + } + + Span buffer = stackalloc byte[8]; + _ = stream.Read(buffer); + return BinaryPrimitives.ReadUInt64BigEndian(buffer); + } + + /// + /// Reads an from the current stream as little endian, and advances the stream position by eight + /// bytes. + /// + /// The stream from which the value should be read. + /// The little endian value. + /// is + /// does not support reading. + [CLSCompliant(false)] + public static ulong ReadUInt64LittleEndian(this Stream stream) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanRead) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); + } + + Span buffer = stackalloc byte[8]; + _ = stream.Read(buffer); + return BinaryPrimitives.ReadUInt64LittleEndian(buffer); } /// @@ -605,582 +639,465 @@ public static class StreamExtensions } /// - /// Writes a two-byte signed integer to the current stream using the system's default endian encoding, and advances - /// the stream position by two bytes. + /// Writes a to the current stream as big endian, and advances the stream position by two bytes. + /// + /// The stream to which the value should be written. + /// The to write. + /// The number of bytes written to the stream. + /// is . + /// does not support writing. + public static int WriteBigEndian(this Stream stream, short value) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanWrite) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); + } + + Span buffer = stackalloc byte[2]; + value.TryWriteBigEndian(buffer); + return stream.WriteInternal(buffer); + } + + /// + /// Writes a to the current stream as big endian, and advances the stream position by four bytes. + /// + /// The stream to which the value should be written. + /// The to write. + /// The number of bytes written to the stream. + /// is . + /// does not support writing. + public static int WriteBigEndian(this Stream stream, int value) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanWrite) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); + } + + Span buffer = stackalloc byte[4]; + value.TryWriteBigEndian(buffer); + return stream.WriteInternal(buffer); + } + + /// + /// Writes a to the current stream as big endian, and advances the stream position by eight bytes. + /// + /// The stream to which the value should be written. + /// The to write. + /// The number of bytes written to the stream. + /// is . + /// does not support writing. + public static int WriteBigEndian(this Stream stream, long value) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanWrite) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); + } + + Span buffer = stackalloc byte[8]; + value.TryWriteBigEndian(buffer); + return stream.WriteInternal(buffer); + } + + /// + /// Writes a to the current stream as big endian, and advances the stream position by two bytes. + /// + /// The stream to which the value should be written. + /// The to write. + /// The number of bytes written to the stream. + /// is . + /// does not support writing. + [CLSCompliant(false)] + public static int WriteBigEndian(this Stream stream, ushort value) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanWrite) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); + } + + Span buffer = stackalloc byte[2]; + value.TryWriteBigEndian(buffer); + return stream.WriteInternal(buffer); + } + + /// + /// Writes a to the current stream as big endian, and advances the stream position by four bytes. + /// + /// The stream to which the value should be written. + /// The to write. + /// The number of bytes written to the stream. + /// is . + /// does not support writing. + [CLSCompliant(false)] + public static int WriteBigEndian(this Stream stream, uint value) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanWrite) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); + } + + Span buffer = stackalloc byte[4]; + value.TryWriteBigEndian(buffer); + return stream.WriteInternal(buffer); + } + + /// + /// Writes a to the current stream as big endian, and advances the stream position by eight bytes. + /// + /// The stream to which the value should be written. + /// The to write. + /// The number of bytes written to the stream. + /// is . + /// does not support writing. + [CLSCompliant(false)] + public static int WriteBigEndian(this Stream stream, ulong value) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanWrite) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); + } + + Span buffer = stackalloc byte[8]; + value.TryWriteBigEndian(buffer); + return stream.WriteInternal(buffer); + } + + /// + /// Writes a to the current stream as little endian, and advances the stream position by four bytes. + /// + /// The stream to which the value should be written. + /// The to write. + /// The number of bytes written to the stream. + /// is . + /// does not support writing. + public static int WriteBigEndian(this Stream stream, float value) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanWrite) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); + } + + Span buffer = stackalloc byte[4]; + value.TryWriteBigEndian(buffer); + return stream.WriteInternal(buffer); + } + + /// + /// Writes a to the current stream as little endian, and advances the stream position by eight + /// bytes. + /// + /// The stream to which the value should be written. + /// The to write. + /// The number of bytes written to the stream. + /// is . + /// does not support writing. + public static int WriteBigEndian(this Stream stream, double value) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanWrite) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); + } + + Span buffer = stackalloc byte[8]; + value.TryWriteBigEndian(buffer); + return stream.WriteInternal(buffer); + } + + /// + /// Writes a to the current stream as little endian, and advances the stream position by sixteen + /// bytes. + /// + /// The stream to which the value should be written. + /// The to write. + /// The number of bytes written to the stream. + /// is . + /// does not support writing. + public static int WriteBigEndian(this Stream stream, decimal value) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanWrite) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); + } + + Span buffer = stackalloc byte[16]; + value.TryWriteBigEndian(buffer); + return stream.WriteInternal(buffer); + } + + /// + /// Writes a to the current stream as little endian, and advances the stream position by two bytes. + /// + /// The stream to which the value should be written. + /// The to write. + /// The number of bytes written to the stream. + /// is . + /// does not support writing. + public static int WriteLittleEndian(this Stream stream, short value) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanWrite) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); + } + + Span buffer = stackalloc byte[2]; + value.TryWriteLittleEndian(buffer); + return stream.WriteInternal(buffer); + } + + /// + /// Writes an to the current stream as little endian, and advances the stream position by four bytes. + /// + /// The stream to which the value should be written. + /// The to write. + /// The number of bytes written to the stream. + /// is . + /// does not support writing. + public static int WriteLittleEndian(this Stream stream, int value) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanWrite) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); + } + + Span buffer = stackalloc byte[4]; + value.TryWriteLittleEndian(buffer); + return stream.WriteInternal(buffer); + } + + /// + /// Writes a to the current stream as little endian, and advances the stream position by eight bytes. + /// + /// The stream to which the value should be written. + /// The to write. + /// The number of bytes written to the stream. + /// is . + /// does not support writing. + public static int WriteLittleEndian(this Stream stream, long value) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanWrite) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); + } + + Span buffer = stackalloc byte[8]; + value.TryWriteLittleEndian(buffer); + return stream.WriteInternal(buffer); + } + + /// + /// Writes a to the current stream as little endian, and advances the stream position by four bytes. + /// + /// The stream to which the value should be written. + /// The to write. + /// The number of bytes written to the stream. + /// is . + /// does not support writing. + public static int WriteLittleEndian(this Stream stream, float value) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanWrite) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); + } + + Span buffer = stackalloc byte[4]; + value.TryWriteLittleEndian(buffer); + return stream.WriteInternal(buffer); + } + + /// + /// Writes a to the current stream as little endian, and advances the stream position by eight + /// bytes. + /// + /// The stream to which the value should be written. + /// The to write. + /// The number of bytes written to the stream. + /// is . + /// does not support writing. + public static int WriteLittleEndian(this Stream stream, double value) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanWrite) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); + } + + Span buffer = stackalloc byte[8]; + value.TryWriteLittleEndian(buffer); + return stream.WriteInternal(buffer); + } + + /// + /// Writes a to the current stream as little endian, and advances the stream position by sixteen + /// bytes. + /// + /// The stream to which the value should be written. + /// The to write. + /// The number of bytes written to the stream. + /// is . + /// does not support writing. + public static int WriteLittleEndian(this Stream stream, decimal value) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanWrite) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); + } + + Span buffer = stackalloc byte[16]; + value.TryWriteLittleEndian(buffer); + return stream.WriteInternal(buffer); + } + + /// + /// Writes a to the current stream as little endian, and advances the stream position by two bytes. /// /// The stream to which the value should be written. /// The two-byte signed integer to write. /// The number of bytes written to the stream. - [ExcludeFromCodeCoverage] - public static int Write(this Stream stream, short value) + /// is . + /// does not support writing. + [CLSCompliant(false)] + public static int WriteLittleEndian(this Stream stream, ushort value) { - return stream.Write(value, DefaultEndianness); + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanWrite) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); + } + + Span buffer = stackalloc byte[2]; + BinaryPrimitives.WriteUInt16LittleEndian(buffer, value); + return stream.WriteInternal(buffer); } /// - /// Writes a two-byte signed integer to the current stream using the specified endian encoding, and advances the - /// stream position by two bytes. + /// Writes a to the current stream as little endian, and advances the stream position by four bytes. /// /// The stream to which the value should be written. /// The two-byte signed integer to write. - /// The endian encoding to use. - /// The number of bytes written to the stream. - public static int Write(this Stream stream, short value, Endianness endianness) - { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } - -#if NET5_0_OR_GREATER - if (!Enum.IsDefined(endianness)) - { - throw new ArgumentOutOfRangeException(nameof(endianness)); - } -#else - if (!Enum.IsDefined(typeof(Endianness), endianness)) - { - throw new ArgumentOutOfRangeException(nameof(endianness)); - } -#endif - - if (!stream.CanWrite) - { - throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); - } - - Span buffer = stackalloc byte[sizeof(short)]; - - if (endianness == Endianness.LittleEndian) - { - BinaryPrimitives.WriteInt16LittleEndian(buffer, value); - } - else - { - BinaryPrimitives.WriteInt16BigEndian(buffer, value); - } - - return stream.WriteInternal(buffer); - } - - /// - /// Writes a four-byte signed integer to the current stream using the system's default endian encoding, and advances - /// the stream position by four bytes. - /// - /// The stream to which the value should be written. - /// The four-byte signed integer to write. - /// The number of bytes written to the stream. - [ExcludeFromCodeCoverage] - public static int Write(this Stream stream, int value) - { - return stream.Write(value, DefaultEndianness); - } - - /// - /// Writes a four-byte signed integer to the current stream using the specified endian encoding, and advances the - /// stream position by four bytes. - /// - /// The stream to which the value should be written. - /// The four-byte signed integer to write. - /// The endian encoding to use. - /// The number of bytes written to the stream. - /// is . - public static int Write(this Stream stream, int value, Endianness endianness) - { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } - -#if NET5_0_OR_GREATER - if (!Enum.IsDefined(endianness)) - { - throw new ArgumentOutOfRangeException(nameof(endianness)); - } -#else - if (!Enum.IsDefined(typeof(Endianness), endianness)) - { - throw new ArgumentOutOfRangeException(nameof(endianness)); - } -#endif - - if (!stream.CanWrite) - { - throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); - } - - Span buffer = stackalloc byte[sizeof(int)]; - - if (endianness == Endianness.LittleEndian) - { - BinaryPrimitives.WriteInt32LittleEndian(buffer, value); - } - else - { - BinaryPrimitives.WriteInt32BigEndian(buffer, value); - } - - return stream.WriteInternal(buffer); - } - - /// - /// Writes an eight-byte signed integer to the current stream using the system's default endian encoding, and advances - /// the stream position by eight bytes. - /// - /// The stream to which the value should be written. - /// The eight-byte signed integer to write. - /// The number of bytes written to the stream. - /// is . - [ExcludeFromCodeCoverage] - public static int Write(this Stream stream, long value) - { - return stream.Write(value, DefaultEndianness); - } - - /// - /// Writes an eight-byte signed integer to the current stream using the specified endian encoding, and advances the - /// stream position by eight bytes. - /// - /// The stream to which the value should be written. - /// The eight-byte signed integer to write. - /// The endian encoding to use. - /// The number of bytes written to the stream. - /// is . - public static int Write(this Stream stream, long value, Endianness endianness) - { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } - -#if NET5_0_OR_GREATER - if (!Enum.IsDefined(endianness)) - { - throw new ArgumentOutOfRangeException(nameof(endianness)); - } -#else - if (!Enum.IsDefined(typeof(Endianness), endianness)) - { - throw new ArgumentOutOfRangeException(nameof(endianness)); - } -#endif - - if (!stream.CanWrite) - { - throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); - } - - Span buffer = stackalloc byte[sizeof(long)]; - - if (endianness == Endianness.LittleEndian) - { - BinaryPrimitives.WriteInt64LittleEndian(buffer, value); - } - else - { - BinaryPrimitives.WriteInt64BigEndian(buffer, value); - } - - return stream.WriteInternal(buffer); - } - - /// - /// Writes a two-byte unsigned integer to the current stream using the system's default endian encoding, and advances - /// the stream position by two bytes. - /// - /// The stream to which the value should be written. - /// The two-byte unsigned integer to write. /// The number of bytes written to the stream. /// is . + /// does not support writing. [CLSCompliant(false)] - [ExcludeFromCodeCoverage] - public static int Write(this Stream stream, ushort value) - { - return stream.Write(value, DefaultEndianness); - } - - /// - /// Writes a two-byte unsigned integer to the current stream using the specified endian encoding, and advances the - /// stream position by two bytes. - /// - /// The stream to which the value should be written. - /// The two-byte unsigned integer to write. - /// The endian encoding to use. - /// The number of bytes written to the stream. - /// is . - [CLSCompliant(false)] - public static int Write(this Stream stream, ushort value, Endianness endianness) + public static int WriteLittleEndian(this Stream stream, uint value) { if (stream is null) { throw new ArgumentNullException(nameof(stream)); } -#if NET5_0_OR_GREATER - if (!Enum.IsDefined(endianness)) - { - throw new ArgumentOutOfRangeException(nameof(endianness)); - } -#else - if (!Enum.IsDefined(typeof(Endianness), endianness)) - { - throw new ArgumentOutOfRangeException(nameof(endianness)); - } -#endif - if (!stream.CanWrite) { throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); } - Span buffer = stackalloc byte[sizeof(ushort)]; - - if (endianness == Endianness.LittleEndian) - { - BinaryPrimitives.WriteUInt16LittleEndian(buffer, value); - } - else - { - BinaryPrimitives.WriteUInt16BigEndian(buffer, value); - } - + Span buffer = stackalloc byte[4]; + BinaryPrimitives.WriteUInt32LittleEndian(buffer, value); return stream.WriteInternal(buffer); } /// - /// Writes a four-byte unsigned integer to the current stream using the system's default endian encoding, and advances - /// the stream position by four bytes. + /// Writes a to the current stream as little endian, and advances the stream position by eight bytes. /// /// The stream to which the value should be written. - /// The four-byte unsigned integer to write. + /// The two-byte signed integer to write. /// The number of bytes written to the stream. /// is . + /// does not support writing. [CLSCompliant(false)] - [ExcludeFromCodeCoverage] - public static int Write(this Stream stream, uint value) - { - return stream.Write(value, DefaultEndianness); - } - - /// - /// Writes a four-byte unsigned integer to the current stream using the specified endian encoding, and advances the - /// stream position by four bytes. - /// - /// The stream to which the value should be written. - /// The four-byte unsigned integer to write. - /// The endian encoding to use. - /// The number of bytes written to the stream. - /// is . - [CLSCompliant(false)] - public static int Write(this Stream stream, uint value, Endianness endianness) + public static int WriteLittleEndian(this Stream stream, ulong value) { if (stream is null) { throw new ArgumentNullException(nameof(stream)); } -#if NET5_0_OR_GREATER - if (!Enum.IsDefined(endianness)) - { - throw new ArgumentOutOfRangeException(nameof(endianness)); - } -#else - if (!Enum.IsDefined(typeof(Endianness), endianness)) - { - throw new ArgumentOutOfRangeException(nameof(endianness)); - } -#endif - if (!stream.CanWrite) { throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); } - Span buffer = stackalloc byte[sizeof(uint)]; - - if (endianness == Endianness.LittleEndian) - { - BinaryPrimitives.WriteUInt32LittleEndian(buffer, value); - } - else - { - BinaryPrimitives.WriteUInt32BigEndian(buffer, value); - } - + Span buffer = stackalloc byte[8]; + BinaryPrimitives.WriteUInt64LittleEndian(buffer, value); return stream.WriteInternal(buffer); } - /// - /// Writes an eight-byte unsigned integer to the current stream using the system's default endian encoding, and - /// advances the stream position by eight bytes. - /// - /// The stream to which the value should be written. - /// The eight-byte unsigned integer to write. - /// The number of bytes written to the stream. - /// is . - [CLSCompliant(false)] - [ExcludeFromCodeCoverage] - public static int Write(this Stream stream, ulong value) - { - return stream.Write(value, DefaultEndianness); - } - - /// - /// Writes an eight-byte signed integer to the current stream using the specified endian encoding, and advances the - /// stream position by eight bytes. - /// - /// The stream to which the value should be written. - /// The eight-byte signed integer to write. - /// The endian encoding to use. - /// The number of bytes written to the stream. - /// is . - [CLSCompliant(false)] - public static int Write(this Stream stream, ulong value, Endianness endianness) - { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } - -#if NET5_0_OR_GREATER - if (!Enum.IsDefined(endianness)) - { - throw new ArgumentOutOfRangeException(nameof(endianness)); - } -#else - if (!Enum.IsDefined(typeof(Endianness), endianness)) - { - throw new ArgumentOutOfRangeException(nameof(endianness)); - } -#endif - - if (!stream.CanWrite) - { - throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); - } - - Span buffer = stackalloc byte[sizeof(ulong)]; - - if (endianness == Endianness.LittleEndian) - { - BinaryPrimitives.WriteUInt64LittleEndian(buffer, value); - } - else - { - BinaryPrimitives.WriteUInt64BigEndian(buffer, value); - } - - return stream.WriteInternal(buffer); - } - - /// - /// Writes a single-precision floating point value to the current stream using the specified endian encoding, and - /// advances the stream position by four bytes. - /// - /// The stream to which the value should be written. - /// The single-precision floating point value to write. - /// The endian encoding to use. - /// The number of bytes written to the stream. - /// is . - public static int Write(this Stream stream, float value, Endianness endianness) - { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } - -#if NET5_0_OR_GREATER - if (!Enum.IsDefined(endianness)) - { - throw new ArgumentOutOfRangeException(nameof(endianness)); - } -#else - if (!Enum.IsDefined(typeof(Endianness), endianness)) - { - throw new ArgumentOutOfRangeException(nameof(endianness)); - } -#endif - - if (!stream.CanWrite) - { - throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); - } - - Span buffer = stackalloc byte[sizeof(float)]; - - if (endianness == Endianness.LittleEndian) - { -#if NET5_0_OR_GREATER - BinaryPrimitives.WriteSingleLittleEndian(buffer, value); -#else - if (BitConverter.IsLittleEndian) - { - MemoryMarshal.Write(buffer, ref value); - } - else - { - // dotcover disable - //NOSONAR - int temp = BinaryPrimitives.ReverseEndianness(BitConverter.SingleToInt32Bits(value)); - MemoryMarshal.Write(buffer, ref temp); - //NOSONAR - // dotcover enable - } -#endif - } - else - { -#if NET5_0_OR_GREATER - BinaryPrimitives.WriteSingleBigEndian(buffer, value); -#else - if (BitConverter.IsLittleEndian) - { - int temp = BinaryPrimitives.ReverseEndianness(BitConverter.SingleToInt32Bits(value)); - MemoryMarshal.Write(buffer, ref temp); - } - else - { - // dotcover disable - //NOSONAR - MemoryMarshal.Write(buffer, ref value); - //NOSONAR - // dotcover enable - } -#endif - } - - return stream.WriteInternal(buffer); - } - - /// - /// Writes a double-precision floating point value to the current stream using the specified endian encoding, and - /// advances the stream position by eight bytes. - /// - /// The stream to which the value should be written. - /// The double-precision floating point value to write. - /// The endian encoding to use. - /// The number of bytes written to the stream. - /// is . - public static int Write(this Stream stream, double value, Endianness endianness) - { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } - -#if NET5_0_OR_GREATER - if (!Enum.IsDefined(endianness)) - { - throw new ArgumentOutOfRangeException(nameof(endianness)); - } -#else - if (!Enum.IsDefined(typeof(Endianness), endianness)) - { - throw new ArgumentOutOfRangeException(nameof(endianness)); - } -#endif - - if (!stream.CanWrite) - { - throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); - } - - Span buffer = stackalloc byte[sizeof(double)]; - - if (endianness == Endianness.LittleEndian) - { -#if NET5_0_OR_GREATER - BinaryPrimitives.WriteDoubleLittleEndian(buffer, value); -#else - if (BitConverter.IsLittleEndian) - { - MemoryMarshal.Write(buffer, ref value); - } - else - { - // dotcover disable - //NOSONAR - long temp = BinaryPrimitives.ReverseEndianness(BitConverter.DoubleToInt64Bits(value)); - MemoryMarshal.Write(buffer, ref temp); - //NOSONAR - // dotcover enable - } -#endif - } - else - { -#if NET5_0_OR_GREATER - BinaryPrimitives.WriteDoubleBigEndian(buffer, value); -#else - if (BitConverter.IsLittleEndian) - { - long temp = BinaryPrimitives.ReverseEndianness(BitConverter.DoubleToInt64Bits(value)); - MemoryMarshal.Write(buffer, ref temp); - } - else - { - // dotcover disable - //NOSONAR - MemoryMarshal.Write(buffer, ref value); - //NOSONAR - // dotcover enable - } -#endif - } - - return stream.WriteInternal(buffer); - } - - /// - /// Writes a decimal value to the current stream using the specified endian encoding, and advances the stream position - /// by sixteen bytes. - /// - /// The stream to which the value should be written. - /// The decimal value to write. - /// The endian encoding to use. - /// The number of bytes written to the stream. - /// is . - [ExcludeFromCodeCoverage] - public static int Write(this Stream stream, decimal value, Endianness endianness) - { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } - -#if NET5_0_OR_GREATER - if (!Enum.IsDefined(endianness)) - { - throw new ArgumentOutOfRangeException(nameof(endianness)); - } -#else - if (!Enum.IsDefined(typeof(Endianness), endianness)) - { - throw new ArgumentOutOfRangeException(nameof(endianness)); - } -#endif - - if (!stream.CanWrite) - { - throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); - } - - int[] bits = decimal.GetBits(value); - long preWritePosition = stream.Position; - - if (endianness != DefaultEndianness) - { - Array.Reverse(bits); - } - - foreach (int section in bits) - { - stream.Write(section, endianness); - } - - return (int)(stream.Position - preWritePosition); - } - private static int WriteInternal(this Stream stream, ReadOnlySpan value) { long preWritePosition = stream.Position; diff --git a/X10D/src/IO/UInt16Extensions.cs b/X10D/src/IO/UInt16Extensions.cs index 5eb12ae..2cbc777 100644 --- a/X10D/src/IO/UInt16Extensions.cs +++ b/X10D/src/IO/UInt16Extensions.cs @@ -10,54 +10,50 @@ namespace X10D.IO; public static class UInt16Extensions { /// - /// Returns the current 16-bit unsigned integer value as an array of bytes. + /// Converts the current 16-bit unsigned integer into an array of bytes, as big endian. /// - /// The number to convert. - /// An array of bytes with length 2. + /// The value. + /// An array of bytes with length 8. [Pure] - public static byte[] GetBytes(this ushort value) + public static byte[] GetBigEndianBytes(this ushort value) { Span buffer = stackalloc byte[2]; - value.TryWriteBytes(buffer); + value.TryWriteBigEndian(buffer); return buffer.ToArray(); } /// - /// Returns the current 16-bit unsigned integer value as an array of bytes. + /// Converts the current 16-bit unsigned integer into an array of bytes, as big endian. /// - /// The number to convert. - /// The endianness with which to write the bytes. - /// An array of bytes with length 2. + /// The value. + /// An array of bytes with length 8. [Pure] - public static byte[] GetBytes(this ushort value, Endianness endianness) + public static byte[] GetLittleEndianBytes(this ushort value) { Span buffer = stackalloc byte[2]; - value.TryWriteBytes(buffer, endianness); + value.TryWriteLittleEndian(buffer); return buffer.ToArray(); } /// - /// Converts the current 16-bit unsigned integer into a span of bytes. + /// Writes the current 16-bit unsigned integer into a span of bytes, as big endian. /// /// The value. - /// When this method returns, the bytes representing the converted . + /// The span of bytes where the value is to be written, as big endian. /// if the conversion was successful; otherwise, . - public static bool TryWriteBytes(this ushort value, Span destination) + public static bool TryWriteBigEndian(this ushort value, Span destination) { - return BitConverter.TryWriteBytes(destination, value); + return BinaryPrimitives.TryWriteUInt16BigEndian(destination, value); } /// - /// Converts the current 16-bit unsigned integer into a span of bytes. + /// Writes the current 16-bit unsigned integer into a span of bytes, as little endian. /// /// The value. - /// When this method returns, the bytes representing the converted . - /// The endianness with which to write the bytes. + /// The span of bytes where the value is to be written, as little endian. /// if the conversion was successful; otherwise, . - public static bool TryWriteBytes(this ushort value, Span destination, Endianness endianness) + public static bool TryWriteLittleEndian(this ushort value, Span destination) { - return endianness == Endianness.BigEndian - ? BinaryPrimitives.TryWriteUInt16BigEndian(destination, value) - : BinaryPrimitives.TryWriteUInt16LittleEndian(destination, value); + return BinaryPrimitives.TryWriteUInt16LittleEndian(destination, value); } } diff --git a/X10D/src/IO/UInt32Extensions.cs b/X10D/src/IO/UInt32Extensions.cs index c4f3c30..12845ea 100644 --- a/X10D/src/IO/UInt32Extensions.cs +++ b/X10D/src/IO/UInt32Extensions.cs @@ -10,54 +10,50 @@ namespace X10D.IO; public static class UInt32Extensions { /// - /// Returns the current 32-bit unsigned integer value as an array of bytes. + /// Converts the current 32-bit unsigned integer into an array of bytes, as big endian. /// - /// The number to convert. - /// An array of bytes with length 4. + /// The value. + /// An array of bytes with length 8. [Pure] - public static byte[] GetBytes(this uint value) + public static byte[] GetBigEndianBytes(this uint value) { Span buffer = stackalloc byte[4]; - value.TryWriteBytes(buffer); + value.TryWriteBigEndian(buffer); return buffer.ToArray(); } /// - /// Returns the current 32-bit unsigned integer value as an array of bytes. + /// Converts the current 32-bit unsigned integer into an array of bytes, as big endian. /// - /// The number to convert. - /// The endianness with which to write the bytes. - /// An array of bytes with length 4. + /// The value. + /// An array of bytes with length 8. [Pure] - public static byte[] GetBytes(this uint value, Endianness endianness) + public static byte[] GetLittleEndianBytes(this uint value) { Span buffer = stackalloc byte[4]; - value.TryWriteBytes(buffer, endianness); + value.TryWriteLittleEndian(buffer); return buffer.ToArray(); } /// - /// Converts the current 32-bit unsigned integer into a span of bytes. + /// Writes the current 32-bit unsigned integer into a span of bytes, as big endian. /// /// The value. - /// When this method returns, the bytes representing the converted . + /// The span of bytes where the value is to be written, as big endian. /// if the conversion was successful; otherwise, . - public static bool TryWriteBytes(this uint value, Span destination) + public static bool TryWriteBigEndian(this uint value, Span destination) { - return BitConverter.TryWriteBytes(destination, value); + return BinaryPrimitives.TryWriteUInt32BigEndian(destination, value); } /// - /// Converts the current 32-bit unsigned integer into a span of bytes. + /// Writes the current 32-bit unsigned integer into a span of bytes, as little endian. /// /// The value. - /// When this method returns, the bytes representing the converted . - /// The endianness with which to write the bytes. + /// The span of bytes where the value is to be written, as little endian. /// if the conversion was successful; otherwise, . - public static bool TryWriteBytes(this uint value, Span destination, Endianness endianness) + public static bool TryWriteLittleEndian(this uint value, Span destination) { - return endianness == Endianness.BigEndian - ? BinaryPrimitives.TryWriteUInt32BigEndian(destination, value) - : BinaryPrimitives.TryWriteUInt32LittleEndian(destination, value); + return BinaryPrimitives.TryWriteUInt32LittleEndian(destination, value); } } diff --git a/X10D/src/IO/UInt64Extensions.cs b/X10D/src/IO/UInt64Extensions.cs index 1f48869..96f78c1 100644 --- a/X10D/src/IO/UInt64Extensions.cs +++ b/X10D/src/IO/UInt64Extensions.cs @@ -10,54 +10,50 @@ namespace X10D.IO; public static class UInt64Extensions { /// - /// Returns the current 64-bit unsigned integer value as an array of bytes. + /// Converts the current 64-bit unsigned integer into an array of bytes, as big endian. /// - /// The number to convert. + /// The value. /// An array of bytes with length 8. [Pure] - public static byte[] GetBytes(this ulong value) + public static byte[] GetBigEndianBytes(this ulong value) { Span buffer = stackalloc byte[8]; - value.TryWriteBytes(buffer); + value.TryWriteBigEndian(buffer); return buffer.ToArray(); } /// - /// Returns the current 64-bit unsigned integer value as an array of bytes. + /// Converts the current 64-bit unsigned integer into an array of bytes, as big endian. /// - /// The number to convert. - /// The endianness with which to write the bytes. + /// The value. /// An array of bytes with length 8. [Pure] - public static byte[] GetBytes(this ulong value, Endianness endianness) + public static byte[] GetLittleEndianBytes(this ulong value) { Span buffer = stackalloc byte[8]; - value.TryWriteBytes(buffer, endianness); + value.TryWriteLittleEndian(buffer); return buffer.ToArray(); } /// - /// Converts the current 64-bit unsigned integer into a span of bytes. + /// Writes the current 64-bit unsigned integer into a span of bytes, as big endian. /// /// The value. - /// When this method returns, the bytes representing the converted . + /// The span of bytes where the value is to be written, as big endian. /// if the conversion was successful; otherwise, . - public static bool TryWriteBytes(this ulong value, Span destination) + public static bool TryWriteBigEndian(this ulong value, Span destination) { - return BitConverter.TryWriteBytes(destination, value); + return BinaryPrimitives.TryWriteUInt64BigEndian(destination, value); } /// - /// Converts the current 64-bit unsigned integer into a span of bytes. + /// Writes the current 64-bit unsigned integer into a span of bytes, as little endian. /// /// The value. - /// When this method returns, the bytes representing the converted . - /// The endianness with which to write the bytes. + /// The span of bytes where the value is to be written, as little endian. /// if the conversion was successful; otherwise, . - public static bool TryWriteBytes(this ulong value, Span destination, Endianness endianness) + public static bool TryWriteLittleEndian(this ulong value, Span destination) { - return endianness == Endianness.BigEndian - ? BinaryPrimitives.TryWriteUInt64BigEndian(destination, value) - : BinaryPrimitives.TryWriteUInt64LittleEndian(destination, value); + return BinaryPrimitives.TryWriteUInt64LittleEndian(destination, value); } } From 0bf89bb82a881dbb38c837e408d40ee46baace22 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Wed, 23 Aug 2023 14:17:42 +0100 Subject: [PATCH 091/102] refactor!: change exception thrown by GetHash and TryWriteHash The methods no longer throw TypeInitializationException, and instead now throw ArgumentException. --- CHANGELOG.md | 2 ++ X10D.Tests/src/IO/StreamTests.cs | 9 ++++----- X10D/src/IO/StreamExtensions.cs | 14 +++++--------- 3 files changed, 11 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1957cf2..5f31c88 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -36,6 +36,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - X10D: DateTime.Age(DateTime) and DateTimeOffset.Age(DateTimeOffset) parameter renamed from asOf to referenceDate. - X10D: Methods which accepted the `Endianness` enum as an argument have been replaced with explicit BigEndian/LittleEndian methods. +- X10D: `Stream.GetHash<>` and `Stream.TryWriteHash<>` now throw ArgumentException in lieu of +TypeInitializationException. ### Removed diff --git a/X10D.Tests/src/IO/StreamTests.cs b/X10D.Tests/src/IO/StreamTests.cs index e240990..b522265 100644 --- a/X10D.Tests/src/IO/StreamTests.cs +++ b/X10D.Tests/src/IO/StreamTests.cs @@ -86,16 +86,15 @@ internal partial class StreamTests [Test] public void NullCreateMethodShouldThrow() { - Assert.Throws(() => Stream.Null.GetHash()); - Assert.Throws(() => - Stream.Null.TryWriteHash(Span.Empty, out _)); + Assert.Throws(() => Stream.Null.GetHash()); + Assert.Throws(() => Stream.Null.TryWriteHash(Span.Empty, out _)); } [Test] public void NoCreateMethodShouldThrow() { - Assert.Throws(() => Stream.Null.GetHash()); - Assert.Throws(() => + Assert.Throws(() => Stream.Null.GetHash()); + Assert.Throws(() => Stream.Null.TryWriteHash(Span.Empty, out _)); } diff --git a/X10D/src/IO/StreamExtensions.cs b/X10D/src/IO/StreamExtensions.cs index 9bc7243..ceb34c8 100644 --- a/X10D/src/IO/StreamExtensions.cs +++ b/X10D/src/IO/StreamExtensions.cs @@ -1,4 +1,4 @@ -using System.Buffers.Binary; +using System.Buffers.Binary; using System.Reflection; using System.Runtime.InteropServices; using System.Security.Cryptography; @@ -45,15 +45,13 @@ public static class StreamExtensions .FirstOrDefault(c => c.Name == "Create" && c.GetParameters().Length == 0); if (createMethod is null) { - throw new TypeInitializationException(type.FullName, - new ArgumentException(ExceptionMessages.HashAlgorithmNoCreateMethod)); + throw new ArgumentException(ExceptionMessages.HashAlgorithmNoCreateMethod); } using var crypt = createMethod.Invoke(null, null) as T; if (crypt is null) { - throw new TypeInitializationException(type.FullName, - new ArgumentException(ExceptionMessages.HashAlgorithmCreateReturnedNull)); + throw new ArgumentException(ExceptionMessages.HashAlgorithmCreateReturnedNull); } return crypt.ComputeHash(stream); @@ -617,15 +615,13 @@ public static class StreamExtensions .FirstOrDefault(c => c.Name == "Create" && c.GetParameters().Length == 0); if (createMethod is null) { - throw new TypeInitializationException(type.FullName, - new ArgumentException(ExceptionMessages.HashAlgorithmNoCreateMethod)); + throw new ArgumentException(ExceptionMessages.HashAlgorithmNoCreateMethod); } using var crypt = createMethod.Invoke(null, null) as T; if (crypt is null) { - throw new TypeInitializationException(type.FullName, - new ArgumentException(ExceptionMessages.HashAlgorithmCreateReturnedNull)); + throw new ArgumentException(ExceptionMessages.HashAlgorithmCreateReturnedNull); } if (stream.Length > int.MaxValue) From 28d7bee2623335a481a8a5d007156fe402a43be5 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Wed, 23 Aug 2023 14:18:04 +0100 Subject: [PATCH 092/102] fix(tests): add support for trace logging during tests --- X10D.Tests/src/SetUpTrace.cs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 X10D.Tests/src/SetUpTrace.cs diff --git a/X10D.Tests/src/SetUpTrace.cs b/X10D.Tests/src/SetUpTrace.cs new file mode 100644 index 0000000..4d22848 --- /dev/null +++ b/X10D.Tests/src/SetUpTrace.cs @@ -0,0 +1,20 @@ +using System.Diagnostics; +using NUnit.Framework; + +namespace X10D.Tests; + +[SetUpFixture] +internal sealed class SetupTrace +{ + [OneTimeSetUp] + public void StartTest() + { + Trace.Listeners.Add(new ConsoleTraceListener()); + } + + [OneTimeTearDown] + public void EndTest() + { + Trace.Flush(); + } +} From d90e949212d6668a1285e7dbbc559c8b1724cfd4 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Wed, 23 Aug 2023 16:14:56 +0100 Subject: [PATCH 093/102] fix(ci): build on subdir branch push --- .github/workflows/dotnet.yml | 2 ++ .github/workflows/unity.yml | 2 ++ 2 files changed, 4 insertions(+) diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml index 28a3441..7d3fc24 100644 --- a/.github/workflows/dotnet.yml +++ b/.github/workflows/dotnet.yml @@ -4,9 +4,11 @@ on: push: branches: - '*' + - '*/*' pull_request: branches: - '*' + - '*/*' jobs: build: diff --git a/.github/workflows/unity.yml b/.github/workflows/unity.yml index 61d7c51..2418e06 100644 --- a/.github/workflows/unity.yml +++ b/.github/workflows/unity.yml @@ -4,9 +4,11 @@ on: push: branches: - '*' + - '*/*' pull_request: branches: - '*' + - '*/*' jobs: build: From 3e338eb2f50e63cda4dfc3cd259618d7f4816523 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Wed, 23 Aug 2023 16:14:56 +0100 Subject: [PATCH 094/102] fix(ci): build on subdir branch push --- .github/workflows/dotnet.yml | 2 ++ .github/workflows/unity.yml | 2 ++ 2 files changed, 4 insertions(+) diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml index 28a3441..7d3fc24 100644 --- a/.github/workflows/dotnet.yml +++ b/.github/workflows/dotnet.yml @@ -4,9 +4,11 @@ on: push: branches: - '*' + - '*/*' pull_request: branches: - '*' + - '*/*' jobs: build: diff --git a/.github/workflows/unity.yml b/.github/workflows/unity.yml index 61d7c51..2418e06 100644 --- a/.github/workflows/unity.yml +++ b/.github/workflows/unity.yml @@ -4,9 +4,11 @@ on: push: branches: - '*' + - '*/*' pull_request: branches: - '*' + - '*/*' jobs: build: From caa0070458d656e989008621e8ebd13b70ab25dd Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Wed, 23 Aug 2023 16:43:33 +0100 Subject: [PATCH 095/102] fix: fix incorrect endian swap --- X10D/src/IO/DoubleExtensions.cs | 8 ++++---- X10D/src/IO/SingleExtensions.cs | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/X10D/src/IO/DoubleExtensions.cs b/X10D/src/IO/DoubleExtensions.cs index 728cada..c42a7ef 100644 --- a/X10D/src/IO/DoubleExtensions.cs +++ b/X10D/src/IO/DoubleExtensions.cs @@ -48,11 +48,11 @@ public static class DoubleExtensions #else if (BitConverter.IsLittleEndian) { - return MemoryMarshal.TryWrite(destination, ref value); + long tmp = BinaryPrimitives.ReverseEndianness(BitConverter.DoubleToInt64Bits(value)); + return MemoryMarshal.TryWrite(destination, ref tmp); } - long tmp = BinaryPrimitives.ReverseEndianness(BitConverter.DoubleToInt64Bits(value)); - return MemoryMarshal.TryWrite(destination, ref tmp); + return MemoryMarshal.TryWrite(destination, ref value); #endif } @@ -67,7 +67,7 @@ public static class DoubleExtensions #if NET5_0_OR_GREATER return BinaryPrimitives.TryWriteDoubleLittleEndian(destination, value); #else - if (!BitConverter.IsLittleEndian) + if (BitConverter.IsLittleEndian) { return MemoryMarshal.TryWrite(destination, ref value); } diff --git a/X10D/src/IO/SingleExtensions.cs b/X10D/src/IO/SingleExtensions.cs index d799261..539e919 100644 --- a/X10D/src/IO/SingleExtensions.cs +++ b/X10D/src/IO/SingleExtensions.cs @@ -50,11 +50,11 @@ public static class SingleExtensions #else if (BitConverter.IsLittleEndian) { - return MemoryMarshal.TryWrite(destination, ref value); + int tmp = BinaryPrimitives.ReverseEndianness(BitConverter.SingleToInt32Bits(value)); + return MemoryMarshal.TryWrite(destination, ref tmp); } - int tmp = BinaryPrimitives.ReverseEndianness(BitConverter.SingleToInt32Bits(value)); - return MemoryMarshal.TryWrite(destination, ref tmp); + return MemoryMarshal.TryWrite(destination, ref value); #endif } @@ -69,7 +69,7 @@ public static class SingleExtensions #if NET5_0_OR_GREATER return BinaryPrimitives.TryWriteSingleLittleEndian(destination, value); #else - if (!BitConverter.IsLittleEndian) + if (BitConverter.IsLittleEndian) { return MemoryMarshal.TryWrite(destination, ref value); } From 30b7a465a7c1ed9bb2cfb3f9bf1550f60d9d210a Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Wed, 23 Aug 2023 16:54:20 +0100 Subject: [PATCH 096/102] fix: fix marshal of decimal for netstandard 2.1 --- X10D/src/IO/DecimalExtensions.cs | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/X10D/src/IO/DecimalExtensions.cs b/X10D/src/IO/DecimalExtensions.cs index 8058f70..5b82682 100644 --- a/X10D/src/IO/DecimalExtensions.cs +++ b/X10D/src/IO/DecimalExtensions.cs @@ -1,4 +1,4 @@ -using System.Diagnostics.Contracts; +using System.Diagnostics.Contracts; using System.Runtime.InteropServices; namespace X10D.IO; @@ -97,15 +97,22 @@ public static class DecimalExtensions #else Span buffer = stackalloc byte[16]; MemoryMarshal.Write(buffer, ref value); + WriteBits(destination, buffer); +#endif + } + private static void WriteBits(Span destination, Span buffer) + { var flags = MemoryMarshal.Read(buffer[..4]); var hi = MemoryMarshal.Read(buffer[4..8]); var lo = MemoryMarshal.Read(buffer[8..]); - destination[0] = flags; - destination[1] = hi; - destination[2] = (int)(lo & 0xFFFFFFFF); - destination[3] = (int)(lo >> 32); -#endif + var low = (uint)lo; + var mid = (uint)(lo >> 32); + + destination[0] = (int)low; + destination[1] = (int)mid; + destination[2] = hi; + destination[3] = flags; } } From 1157e36eff8beaa6f6a8aea0fbd18b0a868d4e96 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Wed, 23 Aug 2023 17:00:55 +0100 Subject: [PATCH 097/102] refactor: separate stream Read/Write methods to partials --- X10D/src/IO/StreamExtensions.Reading.cs | 523 +++++++++++++ X10D/src/IO/StreamExtensions.Writing.cs | 473 ++++++++++++ X10D/src/IO/StreamExtensions.cs | 989 +----------------------- 3 files changed, 998 insertions(+), 987 deletions(-) create mode 100644 X10D/src/IO/StreamExtensions.Reading.cs create mode 100644 X10D/src/IO/StreamExtensions.Writing.cs diff --git a/X10D/src/IO/StreamExtensions.Reading.cs b/X10D/src/IO/StreamExtensions.Reading.cs new file mode 100644 index 0000000..b3bc317 --- /dev/null +++ b/X10D/src/IO/StreamExtensions.Reading.cs @@ -0,0 +1,523 @@ +using System.Buffers.Binary; +using System.Runtime.InteropServices; + +namespace X10D.IO; + +public static partial class StreamExtensions +{ + /// + /// Reads an from the current stream as big endian, and advances the stream position by sixteen + /// bytes. + /// + /// The stream from which the value should be read. + /// The big endian value. + /// is + /// does not support reading. + public static decimal ReadDecimalBigEndian(this Stream stream) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanRead) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); + } + + const int decimalSize = sizeof(decimal); + const int int32Size = sizeof(int); + const int partitionSize = decimalSize / int32Size; + + Span buffer = stackalloc int[partitionSize]; + for (var index = 0; index < partitionSize; index++) + { + buffer[index] = stream.ReadInt32BigEndian(); + } + + if (BitConverter.IsLittleEndian) + { + buffer.Reverse(); + } + +#if NET5_0_OR_GREATER + return new decimal(buffer); +#else + return new decimal(buffer.ToArray()); +#endif + } + + /// + /// Reads an from the current stream as big endian, and advances the stream position by sixteen + /// bytes. + /// + /// The stream from which the value should be read. + /// The big endian value. + /// is + /// does not support reading. + public static decimal ReadDecimalLittleEndian(this Stream stream) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanRead) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); + } + + const int decimalSize = sizeof(decimal); + const int int32Size = sizeof(int); + const int partitionSize = decimalSize / int32Size; + + Span buffer = stackalloc int[partitionSize]; + for (var index = 0; index < partitionSize; index++) + { + buffer[index] = stream.ReadInt32LittleEndian(); + } + + if (!BitConverter.IsLittleEndian) + { + buffer.Reverse(); + } + +#if NET5_0_OR_GREATER + return new decimal(buffer); +#else + return new decimal(buffer.ToArray()); +#endif + } + + /// + /// Reads an from the current stream as big endian, and advances the stream position by eight bytes. + /// + /// The stream from which the value should be read. + /// The big endian value. + /// is + /// does not support reading. + public static double ReadDoubleBigEndian(this Stream stream) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanRead) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); + } + + Span buffer = stackalloc byte[8]; + _ = stream.Read(buffer); +#if NET5_0_OR_GREATER + return BinaryPrimitives.ReadDoubleBigEndian(buffer); +#else + if (BitConverter.IsLittleEndian) + { + buffer.Reverse(); + } + + return MemoryMarshal.Read(buffer); +#endif + } + + /// + /// Reads an from the current stream as little endian, and advances the stream position by eight + /// bytes. + /// + /// The stream from which the value should be read. + /// The little endian value. + /// is + /// does not support reading. + public static double ReadDoubleLittleEndian(this Stream stream) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanRead) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); + } + + Span buffer = stackalloc byte[8]; + _ = stream.Read(buffer); +#if NET5_0_OR_GREATER + return BinaryPrimitives.ReadDoubleLittleEndian(buffer); +#else + if (!BitConverter.IsLittleEndian) + { + buffer.Reverse(); + } + + return MemoryMarshal.Read(buffer); +#endif + } + + /// + /// Reads an from the current stream as big endian, and advances the stream position by two bytes. + /// + /// The stream from which the value should be read. + /// The big endian value. + /// is + /// does not support reading. + public static short ReadInt16BigEndian(this Stream stream) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanRead) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); + } + + Span buffer = stackalloc byte[2]; + _ = stream.Read(buffer); + return BinaryPrimitives.ReadInt16BigEndian(buffer); + } + + /// + /// Reads an from the current stream as little endian, and advances the stream position by two bytes. + /// + /// The stream from which the value should be read. + /// The little endian value. + /// is + /// does not support reading. + public static short ReadInt16LittleEndian(this Stream stream) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanRead) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); + } + + Span buffer = stackalloc byte[2]; + _ = stream.Read(buffer); + return BinaryPrimitives.ReadInt16LittleEndian(buffer); + } + + /// + /// Reads an from the current stream as big endian, and advances the stream position by four bytes. + /// + /// The stream from which the value should be read. + /// The big endian value. + /// is + /// does not support reading. + public static int ReadInt32BigEndian(this Stream stream) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanRead) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); + } + + Span buffer = stackalloc byte[4]; + _ = stream.Read(buffer); + return BinaryPrimitives.ReadInt32BigEndian(buffer); + } + + /// + /// Reads an from the current stream as little endian, and advances the stream position by four bytes. + /// + /// The stream from which the value should be read. + /// The little endian value. + /// is + /// does not support reading. + public static int ReadInt32LittleEndian(this Stream stream) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanRead) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); + } + + Span buffer = stackalloc byte[4]; + _ = stream.Read(buffer); + return BinaryPrimitives.ReadInt32LittleEndian(buffer); + } + + /// + /// Reads an from the current stream as big endian, and advances the stream position by eight bytes. + /// + /// The stream from which the value should be read. + /// The big endian value. + /// is + /// does not support reading. + public static long ReadInt64BigEndian(this Stream stream) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanRead) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); + } + + Span buffer = stackalloc byte[8]; + _ = stream.Read(buffer); + return BinaryPrimitives.ReadInt64BigEndian(buffer); + } + + /// + /// Reads an from the current stream as little endian, and advances the stream position by eight + /// bytes. + /// + /// The stream from which the value should be read. + /// The little endian value. + /// is + /// does not support reading. + public static long ReadInt64LittleEndian(this Stream stream) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanRead) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); + } + + Span buffer = stackalloc byte[8]; + _ = stream.Read(buffer); + return BinaryPrimitives.ReadInt64LittleEndian(buffer); + } + + /// + /// Reads an from the current stream as big endian, and advances the stream position by four bytes. + /// + /// The stream from which the value should be read. + /// The big endian value. + /// is + /// does not support reading. + [CLSCompliant(false)] + public static float ReadSingleBigEndian(this Stream stream) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanRead) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); + } + + Span buffer = stackalloc byte[4]; + _ = stream.Read(buffer); +#if NET5_0_OR_GREATER + return BinaryPrimitives.ReadSingleBigEndian(buffer); +#else + if (BitConverter.IsLittleEndian) + { + buffer.Reverse(); + } + + return MemoryMarshal.Read(buffer); +#endif + } + + /// + /// Reads an from the current stream as little endian, and advances the stream position by four + /// bytes. + /// + /// The stream from which the value should be read. + /// The little endian value. + /// is + /// does not support reading. + [CLSCompliant(false)] + public static float ReadSingleLittleEndian(this Stream stream) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanRead) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); + } + + Span buffer = stackalloc byte[4]; + _ = stream.Read(buffer); +#if NET5_0_OR_GREATER + return BinaryPrimitives.ReadSingleLittleEndian(buffer); +#else + if (!BitConverter.IsLittleEndian) + { + buffer.Reverse(); + } + + return MemoryMarshal.Read(buffer); +#endif + } + + /// + /// Reads an from the current stream as big endian, and advances the stream position by two bytes. + /// + /// The stream from which the value should be read. + /// The big endian value. + /// is + /// does not support reading. + [CLSCompliant(false)] + public static ushort ReadUInt16BigEndian(this Stream stream) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanRead) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); + } + + Span buffer = stackalloc byte[2]; + _ = stream.Read(buffer); + return BinaryPrimitives.ReadUInt16BigEndian(buffer); + } + + /// + /// Reads an from the current stream as little endian, and advances the stream position by two bytes. + /// + /// The stream from which the value should be read. + /// The little endian value. + /// is + /// does not support reading. + [CLSCompliant(false)] + public static ushort ReadUInt16LittleEndian(this Stream stream) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanRead) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); + } + + Span buffer = stackalloc byte[2]; + _ = stream.Read(buffer); + return BinaryPrimitives.ReadUInt16LittleEndian(buffer); + } + + /// + /// Reads an from the current stream as big endian, and advances the stream position by four bytes. + /// + /// The stream from which the value should be read. + /// The big endian value. + /// is + /// does not support reading. + [CLSCompliant(false)] + public static uint ReadUInt32BigEndian(this Stream stream) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanRead) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); + } + + Span buffer = stackalloc byte[4]; + _ = stream.Read(buffer); + return BinaryPrimitives.ReadUInt32BigEndian(buffer); + } + + /// + /// Reads an from the current stream as little endian, and advances the stream position by four bytes. + /// + /// The stream from which the value should be read. + /// The little endian value. + /// is + /// does not support reading. + [CLSCompliant(false)] + public static uint ReadUInt32LittleEndian(this Stream stream) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanRead) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); + } + + Span buffer = stackalloc byte[4]; + _ = stream.Read(buffer); + return BinaryPrimitives.ReadUInt32LittleEndian(buffer); + } + + /// + /// Reads an from the current stream as big endian, and advances the stream position by eight bytes. + /// + /// The stream from which the value should be read. + /// The big endian value. + /// is + /// does not support reading. + [CLSCompliant(false)] + public static ulong ReadUInt64BigEndian(this Stream stream) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanRead) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); + } + + Span buffer = stackalloc byte[8]; + _ = stream.Read(buffer); + return BinaryPrimitives.ReadUInt64BigEndian(buffer); + } + + /// + /// Reads an from the current stream as little endian, and advances the stream position by eight + /// bytes. + /// + /// The stream from which the value should be read. + /// The little endian value. + /// is + /// does not support reading. + [CLSCompliant(false)] + public static ulong ReadUInt64LittleEndian(this Stream stream) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanRead) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); + } + + Span buffer = stackalloc byte[8]; + _ = stream.Read(buffer); + return BinaryPrimitives.ReadUInt64LittleEndian(buffer); + } +} diff --git a/X10D/src/IO/StreamExtensions.Writing.cs b/X10D/src/IO/StreamExtensions.Writing.cs new file mode 100644 index 0000000..787108e --- /dev/null +++ b/X10D/src/IO/StreamExtensions.Writing.cs @@ -0,0 +1,473 @@ +using System.Buffers.Binary; + +namespace X10D.IO; + +public static partial class StreamExtensions +{ + /// + /// Writes a to the current stream as big endian, and advances the stream position by two bytes. + /// + /// The stream to which the value should be written. + /// The to write. + /// The number of bytes written to the stream. + /// is . + /// does not support writing. + public static int WriteBigEndian(this Stream stream, short value) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanWrite) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); + } + + Span buffer = stackalloc byte[2]; + value.TryWriteBigEndian(buffer); + return stream.WriteInternal(buffer); + } + + /// + /// Writes a to the current stream as big endian, and advances the stream position by four bytes. + /// + /// The stream to which the value should be written. + /// The to write. + /// The number of bytes written to the stream. + /// is . + /// does not support writing. + public static int WriteBigEndian(this Stream stream, int value) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanWrite) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); + } + + Span buffer = stackalloc byte[4]; + value.TryWriteBigEndian(buffer); + return stream.WriteInternal(buffer); + } + + /// + /// Writes a to the current stream as big endian, and advances the stream position by eight bytes. + /// + /// The stream to which the value should be written. + /// The to write. + /// The number of bytes written to the stream. + /// is . + /// does not support writing. + public static int WriteBigEndian(this Stream stream, long value) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanWrite) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); + } + + Span buffer = stackalloc byte[8]; + value.TryWriteBigEndian(buffer); + return stream.WriteInternal(buffer); + } + + /// + /// Writes a to the current stream as big endian, and advances the stream position by two bytes. + /// + /// The stream to which the value should be written. + /// The to write. + /// The number of bytes written to the stream. + /// is . + /// does not support writing. + [CLSCompliant(false)] + public static int WriteBigEndian(this Stream stream, ushort value) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanWrite) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); + } + + Span buffer = stackalloc byte[2]; + value.TryWriteBigEndian(buffer); + return stream.WriteInternal(buffer); + } + + /// + /// Writes a to the current stream as big endian, and advances the stream position by four bytes. + /// + /// The stream to which the value should be written. + /// The to write. + /// The number of bytes written to the stream. + /// is . + /// does not support writing. + [CLSCompliant(false)] + public static int WriteBigEndian(this Stream stream, uint value) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanWrite) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); + } + + Span buffer = stackalloc byte[4]; + value.TryWriteBigEndian(buffer); + return stream.WriteInternal(buffer); + } + + /// + /// Writes a to the current stream as big endian, and advances the stream position by eight bytes. + /// + /// The stream to which the value should be written. + /// The to write. + /// The number of bytes written to the stream. + /// is . + /// does not support writing. + [CLSCompliant(false)] + public static int WriteBigEndian(this Stream stream, ulong value) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanWrite) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); + } + + Span buffer = stackalloc byte[8]; + value.TryWriteBigEndian(buffer); + return stream.WriteInternal(buffer); + } + + /// + /// Writes a to the current stream as little endian, and advances the stream position by four bytes. + /// + /// The stream to which the value should be written. + /// The to write. + /// The number of bytes written to the stream. + /// is . + /// does not support writing. + public static int WriteBigEndian(this Stream stream, float value) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanWrite) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); + } + + Span buffer = stackalloc byte[4]; + value.TryWriteBigEndian(buffer); + return stream.WriteInternal(buffer); + } + + /// + /// Writes a to the current stream as little endian, and advances the stream position by eight + /// bytes. + /// + /// The stream to which the value should be written. + /// The to write. + /// The number of bytes written to the stream. + /// is . + /// does not support writing. + public static int WriteBigEndian(this Stream stream, double value) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanWrite) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); + } + + Span buffer = stackalloc byte[8]; + value.TryWriteBigEndian(buffer); + return stream.WriteInternal(buffer); + } + + /// + /// Writes a to the current stream as little endian, and advances the stream position by sixteen + /// bytes. + /// + /// The stream to which the value should be written. + /// The to write. + /// The number of bytes written to the stream. + /// is . + /// does not support writing. + public static int WriteBigEndian(this Stream stream, decimal value) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanWrite) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); + } + + Span buffer = stackalloc byte[16]; + value.TryWriteBigEndian(buffer); + return stream.WriteInternal(buffer); + } + + /// + /// Writes a to the current stream as little endian, and advances the stream position by two bytes. + /// + /// The stream to which the value should be written. + /// The to write. + /// The number of bytes written to the stream. + /// is . + /// does not support writing. + public static int WriteLittleEndian(this Stream stream, short value) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanWrite) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); + } + + Span buffer = stackalloc byte[2]; + value.TryWriteLittleEndian(buffer); + return stream.WriteInternal(buffer); + } + + /// + /// Writes an to the current stream as little endian, and advances the stream position by four bytes. + /// + /// The stream to which the value should be written. + /// The to write. + /// The number of bytes written to the stream. + /// is . + /// does not support writing. + public static int WriteLittleEndian(this Stream stream, int value) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanWrite) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); + } + + Span buffer = stackalloc byte[4]; + value.TryWriteLittleEndian(buffer); + return stream.WriteInternal(buffer); + } + + /// + /// Writes a to the current stream as little endian, and advances the stream position by eight bytes. + /// + /// The stream to which the value should be written. + /// The to write. + /// The number of bytes written to the stream. + /// is . + /// does not support writing. + public static int WriteLittleEndian(this Stream stream, long value) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanWrite) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); + } + + Span buffer = stackalloc byte[8]; + value.TryWriteLittleEndian(buffer); + return stream.WriteInternal(buffer); + } + + /// + /// Writes a to the current stream as little endian, and advances the stream position by four bytes. + /// + /// The stream to which the value should be written. + /// The to write. + /// The number of bytes written to the stream. + /// is . + /// does not support writing. + public static int WriteLittleEndian(this Stream stream, float value) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanWrite) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); + } + + Span buffer = stackalloc byte[4]; + value.TryWriteLittleEndian(buffer); + return stream.WriteInternal(buffer); + } + + /// + /// Writes a to the current stream as little endian, and advances the stream position by eight + /// bytes. + /// + /// The stream to which the value should be written. + /// The to write. + /// The number of bytes written to the stream. + /// is . + /// does not support writing. + public static int WriteLittleEndian(this Stream stream, double value) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanWrite) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); + } + + Span buffer = stackalloc byte[8]; + value.TryWriteLittleEndian(buffer); + return stream.WriteInternal(buffer); + } + + /// + /// Writes a to the current stream as little endian, and advances the stream position by sixteen + /// bytes. + /// + /// The stream to which the value should be written. + /// The to write. + /// The number of bytes written to the stream. + /// is . + /// does not support writing. + public static int WriteLittleEndian(this Stream stream, decimal value) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanWrite) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); + } + + Span buffer = stackalloc byte[16]; + value.TryWriteLittleEndian(buffer); + return stream.WriteInternal(buffer); + } + + /// + /// Writes a to the current stream as little endian, and advances the stream position by two bytes. + /// + /// The stream to which the value should be written. + /// The two-byte signed integer to write. + /// The number of bytes written to the stream. + /// is . + /// does not support writing. + [CLSCompliant(false)] + public static int WriteLittleEndian(this Stream stream, ushort value) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanWrite) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); + } + + Span buffer = stackalloc byte[2]; + BinaryPrimitives.WriteUInt16LittleEndian(buffer, value); + return stream.WriteInternal(buffer); + } + + /// + /// Writes a to the current stream as little endian, and advances the stream position by four bytes. + /// + /// The stream to which the value should be written. + /// The two-byte signed integer to write. + /// The number of bytes written to the stream. + /// is . + /// does not support writing. + [CLSCompliant(false)] + public static int WriteLittleEndian(this Stream stream, uint value) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanWrite) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); + } + + Span buffer = stackalloc byte[4]; + BinaryPrimitives.WriteUInt32LittleEndian(buffer, value); + return stream.WriteInternal(buffer); + } + + /// + /// Writes a to the current stream as little endian, and advances the stream position by eight bytes. + /// + /// The stream to which the value should be written. + /// The two-byte signed integer to write. + /// The number of bytes written to the stream. + /// is . + /// does not support writing. + [CLSCompliant(false)] + public static int WriteLittleEndian(this Stream stream, ulong value) + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + if (!stream.CanWrite) + { + throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); + } + + Span buffer = stackalloc byte[8]; + BinaryPrimitives.WriteUInt64LittleEndian(buffer, value); + return stream.WriteInternal(buffer); + } + + private static int WriteInternal(this Stream stream, ReadOnlySpan value) + { + long preWritePosition = stream.Position; + stream.Write(value); + return (int)(stream.Position - preWritePosition); + } +} diff --git a/X10D/src/IO/StreamExtensions.cs b/X10D/src/IO/StreamExtensions.cs index ceb34c8..15e50e0 100644 --- a/X10D/src/IO/StreamExtensions.cs +++ b/X10D/src/IO/StreamExtensions.cs @@ -1,6 +1,4 @@ -using System.Buffers.Binary; -using System.Reflection; -using System.Runtime.InteropServices; +using System.Reflection; using System.Security.Cryptography; namespace X10D.IO; @@ -8,7 +6,7 @@ namespace X10D.IO; /// /// IO-related extension methods for . /// -public static class StreamExtensions +public static partial class StreamExtensions { /// /// Returns the hash of the current stream as an array of bytes using the specified hash algorithm. @@ -57,522 +55,6 @@ public static class StreamExtensions return crypt.ComputeHash(stream); } - /// - /// Reads an from the current stream as big endian, and advances the stream position by sixteen - /// bytes. - /// - /// The stream from which the value should be read. - /// The big endian value. - /// is - /// does not support reading. - public static decimal ReadDecimalBigEndian(this Stream stream) - { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (!stream.CanRead) - { - throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); - } - - const int decimalSize = sizeof(decimal); - const int int32Size = sizeof(int); - const int partitionSize = decimalSize / int32Size; - - Span buffer = stackalloc int[partitionSize]; - for (var index = 0; index < partitionSize; index++) - { - buffer[index] = stream.ReadInt32BigEndian(); - } - - if (BitConverter.IsLittleEndian) - { - buffer.Reverse(); - } - -#if NET5_0_OR_GREATER - return new decimal(buffer); -#else - return new decimal(buffer.ToArray()); -#endif - } - - /// - /// Reads an from the current stream as big endian, and advances the stream position by sixteen - /// bytes. - /// - /// The stream from which the value should be read. - /// The big endian value. - /// is - /// does not support reading. - public static decimal ReadDecimalLittleEndian(this Stream stream) - { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (!stream.CanRead) - { - throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); - } - - const int decimalSize = sizeof(decimal); - const int int32Size = sizeof(int); - const int partitionSize = decimalSize / int32Size; - - Span buffer = stackalloc int[partitionSize]; - for (var index = 0; index < partitionSize; index++) - { - buffer[index] = stream.ReadInt32LittleEndian(); - } - - if (!BitConverter.IsLittleEndian) - { - buffer.Reverse(); - } - -#if NET5_0_OR_GREATER - return new decimal(buffer); -#else - return new decimal(buffer.ToArray()); -#endif - } - - /// - /// Reads an from the current stream as big endian, and advances the stream position by eight bytes. - /// - /// The stream from which the value should be read. - /// The big endian value. - /// is - /// does not support reading. - public static double ReadDoubleBigEndian(this Stream stream) - { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (!stream.CanRead) - { - throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); - } - - Span buffer = stackalloc byte[8]; - _ = stream.Read(buffer); -#if NET5_0_OR_GREATER - return BinaryPrimitives.ReadDoubleBigEndian(buffer); -#else - if (BitConverter.IsLittleEndian) - { - buffer.Reverse(); - } - - return MemoryMarshal.Read(buffer); -#endif - } - - /// - /// Reads an from the current stream as little endian, and advances the stream position by eight - /// bytes. - /// - /// The stream from which the value should be read. - /// The little endian value. - /// is - /// does not support reading. - public static double ReadDoubleLittleEndian(this Stream stream) - { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (!stream.CanRead) - { - throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); - } - - Span buffer = stackalloc byte[8]; - _ = stream.Read(buffer); -#if NET5_0_OR_GREATER - return BinaryPrimitives.ReadDoubleLittleEndian(buffer); -#else - if (!BitConverter.IsLittleEndian) - { - buffer.Reverse(); - } - - return MemoryMarshal.Read(buffer); -#endif - } - - /// - /// Reads an from the current stream as big endian, and advances the stream position by two bytes. - /// - /// The stream from which the value should be read. - /// The big endian value. - /// is - /// does not support reading. - public static short ReadInt16BigEndian(this Stream stream) - { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (!stream.CanRead) - { - throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); - } - - Span buffer = stackalloc byte[2]; - _ = stream.Read(buffer); - return BinaryPrimitives.ReadInt16BigEndian(buffer); - } - - /// - /// Reads an from the current stream as little endian, and advances the stream position by two bytes. - /// - /// The stream from which the value should be read. - /// The little endian value. - /// is - /// does not support reading. - public static short ReadInt16LittleEndian(this Stream stream) - { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (!stream.CanRead) - { - throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); - } - - Span buffer = stackalloc byte[2]; - _ = stream.Read(buffer); - return BinaryPrimitives.ReadInt16LittleEndian(buffer); - } - - /// - /// Reads an from the current stream as big endian, and advances the stream position by four bytes. - /// - /// The stream from which the value should be read. - /// The big endian value. - /// is - /// does not support reading. - public static int ReadInt32BigEndian(this Stream stream) - { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (!stream.CanRead) - { - throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); - } - - Span buffer = stackalloc byte[4]; - _ = stream.Read(buffer); - return BinaryPrimitives.ReadInt32BigEndian(buffer); - } - - /// - /// Reads an from the current stream as little endian, and advances the stream position by four bytes. - /// - /// The stream from which the value should be read. - /// The little endian value. - /// is - /// does not support reading. - public static int ReadInt32LittleEndian(this Stream stream) - { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (!stream.CanRead) - { - throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); - } - - Span buffer = stackalloc byte[4]; - _ = stream.Read(buffer); - return BinaryPrimitives.ReadInt32LittleEndian(buffer); - } - - /// - /// Reads an from the current stream as big endian, and advances the stream position by eight bytes. - /// - /// The stream from which the value should be read. - /// The big endian value. - /// is - /// does not support reading. - public static long ReadInt64BigEndian(this Stream stream) - { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (!stream.CanRead) - { - throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); - } - - Span buffer = stackalloc byte[8]; - _ = stream.Read(buffer); - return BinaryPrimitives.ReadInt64BigEndian(buffer); - } - - /// - /// Reads an from the current stream as little endian, and advances the stream position by eight - /// bytes. - /// - /// The stream from which the value should be read. - /// The little endian value. - /// is - /// does not support reading. - public static long ReadInt64LittleEndian(this Stream stream) - { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (!stream.CanRead) - { - throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); - } - - Span buffer = stackalloc byte[8]; - _ = stream.Read(buffer); - return BinaryPrimitives.ReadInt64LittleEndian(buffer); - } - - /// - /// Reads an from the current stream as big endian, and advances the stream position by four bytes. - /// - /// The stream from which the value should be read. - /// The big endian value. - /// is - /// does not support reading. - [CLSCompliant(false)] - public static float ReadSingleBigEndian(this Stream stream) - { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (!stream.CanRead) - { - throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); - } - - Span buffer = stackalloc byte[4]; - _ = stream.Read(buffer); -#if NET5_0_OR_GREATER - return BinaryPrimitives.ReadSingleBigEndian(buffer); -#else - if (BitConverter.IsLittleEndian) - { - buffer.Reverse(); - } - - return MemoryMarshal.Read(buffer); -#endif - } - - /// - /// Reads an from the current stream as little endian, and advances the stream position by four - /// bytes. - /// - /// The stream from which the value should be read. - /// The little endian value. - /// is - /// does not support reading. - [CLSCompliant(false)] - public static float ReadSingleLittleEndian(this Stream stream) - { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (!stream.CanRead) - { - throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); - } - - Span buffer = stackalloc byte[4]; - _ = stream.Read(buffer); -#if NET5_0_OR_GREATER - return BinaryPrimitives.ReadSingleLittleEndian(buffer); -#else - if (!BitConverter.IsLittleEndian) - { - buffer.Reverse(); - } - - return MemoryMarshal.Read(buffer); -#endif - } - - /// - /// Reads an from the current stream as big endian, and advances the stream position by two bytes. - /// - /// The stream from which the value should be read. - /// The big endian value. - /// is - /// does not support reading. - [CLSCompliant(false)] - public static ushort ReadUInt16BigEndian(this Stream stream) - { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (!stream.CanRead) - { - throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); - } - - Span buffer = stackalloc byte[2]; - _ = stream.Read(buffer); - return BinaryPrimitives.ReadUInt16BigEndian(buffer); - } - - /// - /// Reads an from the current stream as little endian, and advances the stream position by two bytes. - /// - /// The stream from which the value should be read. - /// The little endian value. - /// is - /// does not support reading. - [CLSCompliant(false)] - public static ushort ReadUInt16LittleEndian(this Stream stream) - { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (!stream.CanRead) - { - throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); - } - - Span buffer = stackalloc byte[2]; - _ = stream.Read(buffer); - return BinaryPrimitives.ReadUInt16LittleEndian(buffer); - } - - /// - /// Reads an from the current stream as big endian, and advances the stream position by four bytes. - /// - /// The stream from which the value should be read. - /// The big endian value. - /// is - /// does not support reading. - [CLSCompliant(false)] - public static uint ReadUInt32BigEndian(this Stream stream) - { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (!stream.CanRead) - { - throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); - } - - Span buffer = stackalloc byte[4]; - _ = stream.Read(buffer); - return BinaryPrimitives.ReadUInt32BigEndian(buffer); - } - - /// - /// Reads an from the current stream as little endian, and advances the stream position by four bytes. - /// - /// The stream from which the value should be read. - /// The little endian value. - /// is - /// does not support reading. - [CLSCompliant(false)] - public static uint ReadUInt32LittleEndian(this Stream stream) - { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (!stream.CanRead) - { - throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); - } - - Span buffer = stackalloc byte[4]; - _ = stream.Read(buffer); - return BinaryPrimitives.ReadUInt32LittleEndian(buffer); - } - - /// - /// Reads an from the current stream as big endian, and advances the stream position by eight bytes. - /// - /// The stream from which the value should be read. - /// The big endian value. - /// is - /// does not support reading. - [CLSCompliant(false)] - public static ulong ReadUInt64BigEndian(this Stream stream) - { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (!stream.CanRead) - { - throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); - } - - Span buffer = stackalloc byte[8]; - _ = stream.Read(buffer); - return BinaryPrimitives.ReadUInt64BigEndian(buffer); - } - - /// - /// Reads an from the current stream as little endian, and advances the stream position by eight - /// bytes. - /// - /// The stream from which the value should be read. - /// The little endian value. - /// is - /// does not support reading. - [CLSCompliant(false)] - public static ulong ReadUInt64LittleEndian(this Stream stream) - { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (!stream.CanRead) - { - throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportReading); - } - - Span buffer = stackalloc byte[8]; - _ = stream.Read(buffer); - return BinaryPrimitives.ReadUInt64LittleEndian(buffer); - } - /// /// Returns the hash of the current stream as an array of bytes using the specified hash algorithm. /// @@ -633,471 +115,4 @@ public static class StreamExtensions _ = stream.Read(buffer); // we don't care about the number of bytes read. we can ignore MustUseReturnValue return crypt.TryComputeHash(buffer, destination, out bytesWritten); } - - /// - /// Writes a to the current stream as big endian, and advances the stream position by two bytes. - /// - /// The stream to which the value should be written. - /// The to write. - /// The number of bytes written to the stream. - /// is . - /// does not support writing. - public static int WriteBigEndian(this Stream stream, short value) - { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (!stream.CanWrite) - { - throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); - } - - Span buffer = stackalloc byte[2]; - value.TryWriteBigEndian(buffer); - return stream.WriteInternal(buffer); - } - - /// - /// Writes a to the current stream as big endian, and advances the stream position by four bytes. - /// - /// The stream to which the value should be written. - /// The to write. - /// The number of bytes written to the stream. - /// is . - /// does not support writing. - public static int WriteBigEndian(this Stream stream, int value) - { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (!stream.CanWrite) - { - throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); - } - - Span buffer = stackalloc byte[4]; - value.TryWriteBigEndian(buffer); - return stream.WriteInternal(buffer); - } - - /// - /// Writes a to the current stream as big endian, and advances the stream position by eight bytes. - /// - /// The stream to which the value should be written. - /// The to write. - /// The number of bytes written to the stream. - /// is . - /// does not support writing. - public static int WriteBigEndian(this Stream stream, long value) - { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (!stream.CanWrite) - { - throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); - } - - Span buffer = stackalloc byte[8]; - value.TryWriteBigEndian(buffer); - return stream.WriteInternal(buffer); - } - - /// - /// Writes a to the current stream as big endian, and advances the stream position by two bytes. - /// - /// The stream to which the value should be written. - /// The to write. - /// The number of bytes written to the stream. - /// is . - /// does not support writing. - [CLSCompliant(false)] - public static int WriteBigEndian(this Stream stream, ushort value) - { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (!stream.CanWrite) - { - throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); - } - - Span buffer = stackalloc byte[2]; - value.TryWriteBigEndian(buffer); - return stream.WriteInternal(buffer); - } - - /// - /// Writes a to the current stream as big endian, and advances the stream position by four bytes. - /// - /// The stream to which the value should be written. - /// The to write. - /// The number of bytes written to the stream. - /// is . - /// does not support writing. - [CLSCompliant(false)] - public static int WriteBigEndian(this Stream stream, uint value) - { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (!stream.CanWrite) - { - throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); - } - - Span buffer = stackalloc byte[4]; - value.TryWriteBigEndian(buffer); - return stream.WriteInternal(buffer); - } - - /// - /// Writes a to the current stream as big endian, and advances the stream position by eight bytes. - /// - /// The stream to which the value should be written. - /// The to write. - /// The number of bytes written to the stream. - /// is . - /// does not support writing. - [CLSCompliant(false)] - public static int WriteBigEndian(this Stream stream, ulong value) - { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (!stream.CanWrite) - { - throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); - } - - Span buffer = stackalloc byte[8]; - value.TryWriteBigEndian(buffer); - return stream.WriteInternal(buffer); - } - - /// - /// Writes a to the current stream as little endian, and advances the stream position by four bytes. - /// - /// The stream to which the value should be written. - /// The to write. - /// The number of bytes written to the stream. - /// is . - /// does not support writing. - public static int WriteBigEndian(this Stream stream, float value) - { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (!stream.CanWrite) - { - throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); - } - - Span buffer = stackalloc byte[4]; - value.TryWriteBigEndian(buffer); - return stream.WriteInternal(buffer); - } - - /// - /// Writes a to the current stream as little endian, and advances the stream position by eight - /// bytes. - /// - /// The stream to which the value should be written. - /// The to write. - /// The number of bytes written to the stream. - /// is . - /// does not support writing. - public static int WriteBigEndian(this Stream stream, double value) - { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (!stream.CanWrite) - { - throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); - } - - Span buffer = stackalloc byte[8]; - value.TryWriteBigEndian(buffer); - return stream.WriteInternal(buffer); - } - - /// - /// Writes a to the current stream as little endian, and advances the stream position by sixteen - /// bytes. - /// - /// The stream to which the value should be written. - /// The to write. - /// The number of bytes written to the stream. - /// is . - /// does not support writing. - public static int WriteBigEndian(this Stream stream, decimal value) - { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (!stream.CanWrite) - { - throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); - } - - Span buffer = stackalloc byte[16]; - value.TryWriteBigEndian(buffer); - return stream.WriteInternal(buffer); - } - - /// - /// Writes a to the current stream as little endian, and advances the stream position by two bytes. - /// - /// The stream to which the value should be written. - /// The to write. - /// The number of bytes written to the stream. - /// is . - /// does not support writing. - public static int WriteLittleEndian(this Stream stream, short value) - { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (!stream.CanWrite) - { - throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); - } - - Span buffer = stackalloc byte[2]; - value.TryWriteLittleEndian(buffer); - return stream.WriteInternal(buffer); - } - - /// - /// Writes an to the current stream as little endian, and advances the stream position by four bytes. - /// - /// The stream to which the value should be written. - /// The to write. - /// The number of bytes written to the stream. - /// is . - /// does not support writing. - public static int WriteLittleEndian(this Stream stream, int value) - { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (!stream.CanWrite) - { - throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); - } - - Span buffer = stackalloc byte[4]; - value.TryWriteLittleEndian(buffer); - return stream.WriteInternal(buffer); - } - - /// - /// Writes a to the current stream as little endian, and advances the stream position by eight bytes. - /// - /// The stream to which the value should be written. - /// The to write. - /// The number of bytes written to the stream. - /// is . - /// does not support writing. - public static int WriteLittleEndian(this Stream stream, long value) - { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (!stream.CanWrite) - { - throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); - } - - Span buffer = stackalloc byte[8]; - value.TryWriteLittleEndian(buffer); - return stream.WriteInternal(buffer); - } - - /// - /// Writes a to the current stream as little endian, and advances the stream position by four bytes. - /// - /// The stream to which the value should be written. - /// The to write. - /// The number of bytes written to the stream. - /// is . - /// does not support writing. - public static int WriteLittleEndian(this Stream stream, float value) - { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (!stream.CanWrite) - { - throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); - } - - Span buffer = stackalloc byte[4]; - value.TryWriteLittleEndian(buffer); - return stream.WriteInternal(buffer); - } - - /// - /// Writes a to the current stream as little endian, and advances the stream position by eight - /// bytes. - /// - /// The stream to which the value should be written. - /// The to write. - /// The number of bytes written to the stream. - /// is . - /// does not support writing. - public static int WriteLittleEndian(this Stream stream, double value) - { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (!stream.CanWrite) - { - throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); - } - - Span buffer = stackalloc byte[8]; - value.TryWriteLittleEndian(buffer); - return stream.WriteInternal(buffer); - } - - /// - /// Writes a to the current stream as little endian, and advances the stream position by sixteen - /// bytes. - /// - /// The stream to which the value should be written. - /// The to write. - /// The number of bytes written to the stream. - /// is . - /// does not support writing. - public static int WriteLittleEndian(this Stream stream, decimal value) - { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (!stream.CanWrite) - { - throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); - } - - Span buffer = stackalloc byte[16]; - value.TryWriteLittleEndian(buffer); - return stream.WriteInternal(buffer); - } - - /// - /// Writes a to the current stream as little endian, and advances the stream position by two bytes. - /// - /// The stream to which the value should be written. - /// The two-byte signed integer to write. - /// The number of bytes written to the stream. - /// is . - /// does not support writing. - [CLSCompliant(false)] - public static int WriteLittleEndian(this Stream stream, ushort value) - { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (!stream.CanWrite) - { - throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); - } - - Span buffer = stackalloc byte[2]; - BinaryPrimitives.WriteUInt16LittleEndian(buffer, value); - return stream.WriteInternal(buffer); - } - - /// - /// Writes a to the current stream as little endian, and advances the stream position by four bytes. - /// - /// The stream to which the value should be written. - /// The two-byte signed integer to write. - /// The number of bytes written to the stream. - /// is . - /// does not support writing. - [CLSCompliant(false)] - public static int WriteLittleEndian(this Stream stream, uint value) - { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (!stream.CanWrite) - { - throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); - } - - Span buffer = stackalloc byte[4]; - BinaryPrimitives.WriteUInt32LittleEndian(buffer, value); - return stream.WriteInternal(buffer); - } - - /// - /// Writes a to the current stream as little endian, and advances the stream position by eight bytes. - /// - /// The stream to which the value should be written. - /// The two-byte signed integer to write. - /// The number of bytes written to the stream. - /// is . - /// does not support writing. - [CLSCompliant(false)] - public static int WriteLittleEndian(this Stream stream, ulong value) - { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (!stream.CanWrite) - { - throw new ArgumentException(ExceptionMessages.StreamDoesNotSupportWriting); - } - - Span buffer = stackalloc byte[8]; - BinaryPrimitives.WriteUInt64LittleEndian(buffer, value); - return stream.WriteInternal(buffer); - } - - private static int WriteInternal(this Stream stream, ReadOnlySpan value) - { - long preWritePosition = stream.Position; - stream.Write(value); - return (int)(stream.Position - preWritePosition); - } } From 50d9cad2f3225d1155e2a91d9e7110aee6ac8006 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Wed, 23 Aug 2023 17:06:44 +0100 Subject: [PATCH 098/102] perf: optimise subsequent GetHash and TryWriteHash calls --- CHANGELOG.md | 1 + X10D/src/IO/StreamExtensions.cs | 20 ++++++++++++++++++-- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5f31c88..65394b2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,6 +38,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 BigEndian/LittleEndian methods. - X10D: `Stream.GetHash<>` and `Stream.TryWriteHash<>` now throw ArgumentException in lieu of TypeInitializationException. +- X10D: `Stream.GetHash<>` and `Stream.TryWriteHash<>` are now more efficient on second and subsequent calls. ### Removed diff --git a/X10D/src/IO/StreamExtensions.cs b/X10D/src/IO/StreamExtensions.cs index 15e50e0..4bf3df8 100644 --- a/X10D/src/IO/StreamExtensions.cs +++ b/X10D/src/IO/StreamExtensions.cs @@ -1,4 +1,5 @@ -using System.Reflection; +using System.Collections.Concurrent; +using System.Reflection; using System.Security.Cryptography; namespace X10D.IO; @@ -8,6 +9,8 @@ namespace X10D.IO; /// public static partial class StreamExtensions { + private static readonly ConcurrentDictionary HashAlgorithmCache = new(); + /// /// Returns the hash of the current stream as an array of bytes using the specified hash algorithm. /// @@ -37,6 +40,11 @@ public static partial class StreamExtensions throw new IOException(ExceptionMessages.StreamDoesNotSupportReading); } + if (HashAlgorithmCache.TryGetValue(typeof(T), out HashAlgorithm? cachedHashAlgorithm)) + { + return cachedHashAlgorithm.ComputeHash(stream); + } + Type type = typeof(T); MethodInfo? createMethod = type.GetMethods(BindingFlags.Public | BindingFlags.Static) @@ -52,6 +60,7 @@ public static partial class StreamExtensions throw new ArgumentException(ExceptionMessages.HashAlgorithmCreateReturnedNull); } + HashAlgorithmCache.TryAdd(type, crypt); return crypt.ComputeHash(stream); } @@ -91,6 +100,13 @@ public static partial class StreamExtensions throw new IOException(ExceptionMessages.StreamDoesNotSupportReading); } + Span buffer = stackalloc byte[(int)stream.Length]; + if (HashAlgorithmCache.TryGetValue(typeof(T), out HashAlgorithm? cachedHashAlgorithm)) + { + _ = stream.Read(buffer); // we don't care about the number of bytes read. we can ignore MustUseReturnValue + return cachedHashAlgorithm.TryComputeHash(buffer, destination, out bytesWritten); + } + Type type = typeof(T); MethodInfo? createMethod = type.GetMethods(BindingFlags.Public | BindingFlags.Static) @@ -111,7 +127,7 @@ public static partial class StreamExtensions throw new ArgumentException(ExceptionMessages.StreamTooLarge); } - Span buffer = stackalloc byte[(int)stream.Length]; + HashAlgorithmCache.TryAdd(type, crypt); _ = stream.Read(buffer); // we don't care about the number of bytes read. we can ignore MustUseReturnValue return crypt.TryComputeHash(buffer, destination, out bytesWritten); } From 71b0bec85c286bdbee2bd33dac719ba97c1ebe78 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Thu, 24 Aug 2023 01:53:24 +0100 Subject: [PATCH 099/102] style(test): format span tests --- X10D.Tests/src/Linq/ReadOnlySpanTests.cs | 8 ++++---- X10D.Tests/src/Linq/SpanTests.cs | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/X10D.Tests/src/Linq/ReadOnlySpanTests.cs b/X10D.Tests/src/Linq/ReadOnlySpanTests.cs index da74e71..942e646 100644 --- a/X10D.Tests/src/Linq/ReadOnlySpanTests.cs +++ b/X10D.Tests/src/Linq/ReadOnlySpanTests.cs @@ -1,4 +1,4 @@ -using NUnit.Framework; +using NUnit.Framework; using X10D.Linq; namespace X10D.Tests.Linq; @@ -16,7 +16,7 @@ internal class ReadOnlySpanTests [Test] public void AllShouldBeCorrect() { - var span = new ReadOnlySpan(new[] {2, 4, 6, 8, 10}); + var span = new ReadOnlySpan(new[] { 2, 4, 6, 8, 10 }); Assert.That(span.All(x => x % 2 == 0)); Assert.That(span.All(x => x % 2 == 1), Is.False); } @@ -31,7 +31,7 @@ internal class ReadOnlySpanTests [Test] public void AnyShouldBeCorrect() { - var span = new ReadOnlySpan(new[] {2, 4, 6, 8, 10}); + var span = new ReadOnlySpan(new[] { 2, 4, 6, 8, 10 }); Assert.That(span.Any(x => x % 2 == 0)); Assert.That(span.Any(x => x % 2 == 1), Is.False); } @@ -66,7 +66,7 @@ internal class ReadOnlySpanTests [Test] public void Count_ShouldReturn5_ForEvenNumbers_GivenNumbers1To10() { - var span = new ReadOnlySpan(new[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}); + var span = new ReadOnlySpan(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); Assert.That(span.Count(i => i % 2 == 0), Is.EqualTo(5)); } diff --git a/X10D.Tests/src/Linq/SpanTests.cs b/X10D.Tests/src/Linq/SpanTests.cs index 05d60f5..313dea1 100644 --- a/X10D.Tests/src/Linq/SpanTests.cs +++ b/X10D.Tests/src/Linq/SpanTests.cs @@ -1,4 +1,4 @@ -using NUnit.Framework; +using NUnit.Framework; using X10D.Linq; namespace X10D.Tests.Linq; @@ -16,7 +16,7 @@ internal class SpanTests [Test] public void AllShouldBeCorrect() { - var span = new Span(new[] {2, 4, 6, 8, 10}); + var span = new Span(new[] { 2, 4, 6, 8, 10 }); Assert.That(span.All(x => x % 2 == 0)); Assert.That(span.All(x => x % 2 == 1), Is.False); } @@ -31,7 +31,7 @@ internal class SpanTests [Test] public void AnyShouldBeCorrect() { - var span = new Span(new[] {2, 4, 6, 8, 10}); + var span = new Span(new[] { 2, 4, 6, 8, 10 }); Assert.That(span.Any(x => x % 2 == 0)); Assert.That(span.Any(x => x % 2 == 1), Is.False); } @@ -66,7 +66,7 @@ internal class SpanTests [Test] public void Count_ShouldReturn5_ForEvenNumbers_GivenNumbers1To10() { - var span = new Span(new[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}); + var span = new Span(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); Assert.That(span.Count(i => i % 2 == 0), Is.EqualTo(5)); } From 9aed06b5335ae9e02f9ef74834cb7351ddd4e366 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Thu, 24 Aug 2023 01:53:50 +0100 Subject: [PATCH 100/102] [ci skip] docs: add X10D.Hosting to docfx project --- docfx_project/docfx.json | 1 + 1 file changed, 1 insertion(+) diff --git a/docfx_project/docfx.json b/docfx_project/docfx.json index 4cc5662..fd59db2 100644 --- a/docfx_project/docfx.json +++ b/docfx_project/docfx.json @@ -6,6 +6,7 @@ "src": "../", "files": [ "X10D/**/**.csproj", + "X10D.Hosting/**/**.csproj", "X10D.Unity/**/**.csproj" ] } From 5ff7b68b37fe025f9d9492fa2105eaae65fc8ee7 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Thu, 24 Aug 2023 01:54:25 +0100 Subject: [PATCH 101/102] [ci skip] ci: add workflow_dispatch trigger to docfx workflow --- .github/workflows/docfx.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/docfx.yml b/.github/workflows/docfx.yml index e460ace..e922032 100644 --- a/.github/workflows/docfx.yml +++ b/.github/workflows/docfx.yml @@ -3,6 +3,7 @@ name: DocFX on: push: branches: [ main ] + workflow_dispatch: jobs: docfx: From 129cbfb51f1ff8e0bf2b052263442ed534d19098 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Thu, 24 Aug 2023 02:29:59 +0100 Subject: [PATCH 102/102] refactor: revert 50d9cad2f3225d1155e2a91d9e7110aee6ac8006 --- CHANGELOG.md | 1 - X10D/src/IO/StreamExtensions.cs | 20 ++------------------ 2 files changed, 2 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 65394b2..5f31c88 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,7 +38,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 BigEndian/LittleEndian methods. - X10D: `Stream.GetHash<>` and `Stream.TryWriteHash<>` now throw ArgumentException in lieu of TypeInitializationException. -- X10D: `Stream.GetHash<>` and `Stream.TryWriteHash<>` are now more efficient on second and subsequent calls. ### Removed diff --git a/X10D/src/IO/StreamExtensions.cs b/X10D/src/IO/StreamExtensions.cs index 4bf3df8..15e50e0 100644 --- a/X10D/src/IO/StreamExtensions.cs +++ b/X10D/src/IO/StreamExtensions.cs @@ -1,5 +1,4 @@ -using System.Collections.Concurrent; -using System.Reflection; +using System.Reflection; using System.Security.Cryptography; namespace X10D.IO; @@ -9,8 +8,6 @@ namespace X10D.IO; /// public static partial class StreamExtensions { - private static readonly ConcurrentDictionary HashAlgorithmCache = new(); - /// /// Returns the hash of the current stream as an array of bytes using the specified hash algorithm. /// @@ -40,11 +37,6 @@ public static partial class StreamExtensions throw new IOException(ExceptionMessages.StreamDoesNotSupportReading); } - if (HashAlgorithmCache.TryGetValue(typeof(T), out HashAlgorithm? cachedHashAlgorithm)) - { - return cachedHashAlgorithm.ComputeHash(stream); - } - Type type = typeof(T); MethodInfo? createMethod = type.GetMethods(BindingFlags.Public | BindingFlags.Static) @@ -60,7 +52,6 @@ public static partial class StreamExtensions throw new ArgumentException(ExceptionMessages.HashAlgorithmCreateReturnedNull); } - HashAlgorithmCache.TryAdd(type, crypt); return crypt.ComputeHash(stream); } @@ -100,13 +91,6 @@ public static partial class StreamExtensions throw new IOException(ExceptionMessages.StreamDoesNotSupportReading); } - Span buffer = stackalloc byte[(int)stream.Length]; - if (HashAlgorithmCache.TryGetValue(typeof(T), out HashAlgorithm? cachedHashAlgorithm)) - { - _ = stream.Read(buffer); // we don't care about the number of bytes read. we can ignore MustUseReturnValue - return cachedHashAlgorithm.TryComputeHash(buffer, destination, out bytesWritten); - } - Type type = typeof(T); MethodInfo? createMethod = type.GetMethods(BindingFlags.Public | BindingFlags.Static) @@ -127,7 +111,7 @@ public static partial class StreamExtensions throw new ArgumentException(ExceptionMessages.StreamTooLarge); } - HashAlgorithmCache.TryAdd(type, crypt); + Span buffer = stackalloc byte[(int)stream.Length]; _ = stream.Read(buffer); // we don't care about the number of bytes read. we can ignore MustUseReturnValue return crypt.TryComputeHash(buffer, destination, out bytesWritten); }