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: diff --git a/.github/workflows/docfx.yml b/.github/workflows/docfx.yml index 556f434..e922032 100644 --- a/.github/workflows/docfx.yml +++ b/.github/workflows/docfx.yml @@ -3,20 +3,29 @@ name: DocFX on: push: branches: [ main ] + workflow_dispatch: jobs: docfx: 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: | + mkdir docfx_project/images + cp branding_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/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml index 1a43ce2..7d3fc24 100644 --- a/.github/workflows/dotnet.yml +++ b/.github/workflows/dotnet.yml @@ -3,12 +3,12 @@ name: .NET on: push: branches: - - main - - develop + - '*' + - '*/*' pull_request: branches: - - main - - develop + - '*' + - '*/*' jobs: build: diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 22d4a81..9f1a02d 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -4,6 +4,7 @@ on: push: branches: - main + workflow_dispatch: jobs: nightly: @@ -32,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/.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: 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..2418e06 100644 --- a/.github/workflows/unity.yml +++ b/.github/workflows/unity.yml @@ -3,12 +3,12 @@ name: Unity Test Runner on: push: branches: - - main - - develop + - '*' + - '*/*' pull_request: branches: - - main - - develop + - '*' + - '*/*' jobs: build: diff --git a/CHANGELOG.md b/CHANGELOG.md index c978814..5f31c88 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,11 +8,64 @@ 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 `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: Added `string.ConcatIf`. +- 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`. + +- 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 + +- 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 + +### Fixed + +- X10D.Hosting: Fixed `AddHostedSingleton` not accepting an interface as the service type. + +## [3.3.0] - 2023-08-21 + +### Added + +- X10D.Hosting: Added support for service/implementation registration with `AddHostedSingleton`. + +## [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 @@ -576,7 +629,10 @@ 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.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 [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/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: diff --git a/X10D.DSharpPlus/X10D.DSharpPlus.csproj b/Directory.Build.props similarity index 89% rename from X10D.DSharpPlus/X10D.DSharpPlus.csproj rename to Directory.Build.props index 79b26aa..3250f61 100644 --- a/X10D.DSharpPlus/X10D.DSharpPlus.csproj +++ b/Directory.Build.props @@ -1,11 +1,17 @@ - - + net7.0;net6.0;netstandard2.1 11.0 true true + true + true + true + pdbonly + true + 4.0.0 Oliver Booth + enable en https://github.com/oliverbooth/X10D git @@ -14,16 +20,9 @@ branding_Icon.png dotnet extension-methods - $([System.IO.File]::ReadAllText("$(MSBuildProjectDirectory)/../CHANGELOG.md")) + README.md + $([System.IO.File]::ReadAllText("$(SolutionDir)/CHANGELOG.md")) true - 4.0.0 - enable - true - true - true - true - pdbonly - true @@ -48,10 +47,6 @@ $(VersionPrefix).0 - - - - True @@ -61,10 +56,13 @@ True + + True + + True - - + \ No newline at end of file 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 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 2734af9..0000000 --- a/X10D.DSharpPlus/src/DiscordChannelExtensions.cs +++ /dev/null @@ -1,80 +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 NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(channel); -#else - if (channel is null) - { - throw new ArgumentNullException(nameof(channel)); - } -#endif - - 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 NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(channel); - ArgumentNullException.ThrowIfNull(client); -#else - if (channel is null) - { - throw new ArgumentNullException(nameof(channel)); - } - - if (client is null) - { - 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 deleted file mode 100644 index f3d8964..0000000 --- a/X10D.DSharpPlus/src/DiscordClientExtensions.cs +++ /dev/null @@ -1,79 +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 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(); - - 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 NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(client); -#else - if (client is null) - { - throw new ArgumentNullException(nameof(client)); - } -#endif - - 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 4a23a34..0000000 --- a/X10D.DSharpPlus/src/DiscordEmbedBuilderExtensions.cs +++ /dev/null @@ -1,239 +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 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); - } - - /// - /// 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 NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(builder); -#else - if (builder is null) - { - throw new ArgumentNullException(nameof(builder)); - } -#endif - - 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 NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(builder); - ArgumentNullException.ThrowIfNull(predicate); -#else - if (builder is null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (predicate is null) - { - throw new ArgumentNullException(nameof(predicate)); - } -#endif - - 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 NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(builder); - ArgumentNullException.ThrowIfNull(predicate); - ArgumentNullException.ThrowIfNull(valueFactory); -#else - 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)); - } -#endif - - 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 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) - { - 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 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 deleted file mode 100644 index c03016b..0000000 --- a/X10D.DSharpPlus/src/DiscordGuildExtensions.cs +++ /dev/null @@ -1,97 +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 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); - } - - /// - /// 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 NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(guild); -#else - if (guild is null) - { - throw new ArgumentNullException(nameof(guild)); - } -#endif - - 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 NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(guild); - ArgumentNullException.ThrowIfNull(client); -#else - if (guild is null) - { - throw new ArgumentNullException(nameof(guild)); - } - - if (client is null) - { - 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 deleted file mode 100644 index 3fd2020..0000000 --- a/X10D.DSharpPlus/src/DiscordMemberExtensions.cs +++ /dev/null @@ -1,73 +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 NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(member); - ArgumentNullException.ThrowIfNull(role); -#else - if (member is null) - { - throw new ArgumentNullException(nameof(member)); - } - - if (role is null) - { - throw new ArgumentNullException(nameof(role)); - } -#endif - - 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 NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(member); - ArgumentNullException.ThrowIfNull(client); -#else - if (member is null) - { - throw new ArgumentNullException(nameof(member)); - } - - if (client is null) - { - 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 deleted file mode 100644 index f8317c7..0000000 --- a/X10D.DSharpPlus/src/DiscordMessageExtensions.cs +++ /dev/null @@ -1,89 +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 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); - } - - /// - /// 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 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); - } - - /// - /// 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 NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(message); - ArgumentNullException.ThrowIfNull(client); -#else - if (message is null) - { - throw new ArgumentNullException(nameof(message)); - } - - if (client is null) - { - 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 deleted file mode 100644 index 6ab8314..0000000 --- a/X10D.DSharpPlus/src/DiscordUserExtensions.cs +++ /dev/null @@ -1,158 +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 NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(user); - ArgumentNullException.ThrowIfNull(guild); -#else - if (user is null) - { - throw new ArgumentNullException(nameof(user)); - } - - if (guild is null) - { - throw new ArgumentNullException(nameof(guild)); - } -#endif - - 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 NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(user); -#else - if (user is null) - { - throw new ArgumentNullException(nameof(user)); - } -#endif - - 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 NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(user); - ArgumentNullException.ThrowIfNull(guild); -#else - if (user is null) - { - throw new ArgumentNullException(nameof(user)); - } - - if (guild is null) - { - throw new ArgumentNullException(nameof(guild)); - } -#endif - - 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 NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(user); - ArgumentNullException.ThrowIfNull(client); -#else - if (user is null) - { - throw new ArgumentNullException(nameof(user)); - } - - if (client is null) - { - throw new ArgumentNullException(nameof(client)); - } -#endif - - 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.Hosting/X10D.Hosting.csproj b/X10D.Hosting/X10D.Hosting.csproj index b8e4296..0d99bec 100644 --- a/X10D.Hosting/X10D.Hosting.csproj +++ b/X10D.Hosting/X10D.Hosting.csproj @@ -1,69 +1,7 @@ - - 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.Hosting/src/DependencyInjection/ServiceCollectionExtensions.cs b/X10D.Hosting/src/DependencyInjection/ServiceCollectionExtensions.cs index 9a0bafe..ea0d3a4 100644 --- a/X10D.Hosting/src/DependencyInjection/ServiceCollectionExtensions.cs +++ b/X10D.Hosting/src/DependencyInjection/ServiceCollectionExtensions.cs @@ -21,6 +21,22 @@ 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 + where TImplementation : class, TService, IHostedService + { + services.AddSingleton(); + return services.AddSingleton(provider => + (TImplementation)provider.GetRequiredService()); + } + /// /// Adds an registration for the given type, while simultaneously adding it as a singleton. /// @@ -32,4 +48,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)); + } } diff --git a/X10D.Tests/X10D.Tests.csproj b/X10D.Tests/X10D.Tests.csproj index 41d2e68..4af78b2 100644 --- a/X10D.Tests/X10D.Tests.csproj +++ b/X10D.Tests/X10D.Tests.csproj @@ -2,24 +2,25 @@ net7.0;net6.0;netcoreapp3.1 - 11.0 false - enable - true json,cobertura true + false + + + + true - + - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - + + + + + + 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 ed46847..e1d010d 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 +internal static partial class ArrayTests { - [TestClass] - public class AsReadOnlyTests + [TestFixture] + internal 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..5608952 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 +internal static 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..53c46f5 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] -public partial class ArrayTests +[TestFixture] +internal static partial class ArrayTests { } diff --git a/X10D.Tests/src/Collections/BoolListTests.cs b/X10D.Tests/src/Collections/BoolListTests.cs index 0cd5259..c90bc16 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] -public class BoolListTests +[TestFixture] +internal 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..4f35f86 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] -public class ByteTests +[TestFixture] +internal 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.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]); + 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..24c542f 100644 --- a/X10D.Tests/src/Collections/CollectionTests.ClearAndDisposeAll.cs +++ b/X10D.Tests/src/Collections/CollectionTests.ClearAndDisposeAll.cs @@ -1,45 +1,46 @@ using System.Collections.ObjectModel; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; +using NSubstitute; +using NUnit.Framework; using X10D.Collections; namespace X10D.Tests.Collections; -public partial class CollectionTests +internal partial class CollectionTests { - [TestClass] + [TestFixture] public class ClearAndDisposeAllTests { - [TestMethod] + [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); - Assert.AreEqual(0, list.Count); + substitute1.Received(1).Dispose(); + substitute2.Received(1).Dispose(); + substitute3.Received(1).Dispose(); + + 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}); + var substitute = Substitute.For(); + var list = new ReadOnlyCollection(new List {substitute}); - 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..e176fa0 100644 --- a/X10D.Tests/src/Collections/CollectionTests.ClearAndDisposeAllAsync.cs +++ b/X10D.Tests/src/Collections/CollectionTests.ClearAndDisposeAllAsync.cs @@ -1,45 +1,46 @@ using System.Collections.ObjectModel; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; +using NSubstitute; +using NUnit.Framework; using X10D.Collections; namespace X10D.Tests.Collections; -public partial class CollectionTests +internal partial class CollectionTests { - [TestClass] + [TestFixture] public class ClearAndDisposeAllAsyncTests { - [TestMethod] + [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); - Assert.AreEqual(0, list.Count); + await substitute1.Received(1).DisposeAsync(); + await substitute2.Received(1).DisposeAsync(); + await substitute3.Received(1).DisposeAsync(); + + 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}); + var substitute = Substitute.For(); + var list = new ReadOnlyCollection(new List {substitute}); - 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..8452830 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] -public partial class CollectionTests +[TestFixture] +internal partial class CollectionTests { } diff --git a/X10D.Tests/src/Collections/DictionaryTests.cs b/X10D.Tests/src/Collections/DictionaryTests.cs index 907b1f9..c420375 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] -public class DictionaryTests +[TestFixture] +internal 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..6f8519b 100644 --- a/X10D.Tests/src/Collections/EnumerableTests.DisposeAll.cs +++ b/X10D.Tests/src/Collections/EnumerableTests.DisposeAll.cs @@ -1,34 +1,34 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; +using NSubstitute; +using NUnit.Framework; using X10D.Collections; namespace X10D.Tests.Collections; -public partial class EnumerableTests +internal partial class EnumerableTests { - [TestClass] + [TestFixture] public class DisposeAllTests { - [TestMethod] + [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(); } - [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..9cd238f 100644 --- a/X10D.Tests/src/Collections/EnumerableTests.DisposeAllAsync.cs +++ b/X10D.Tests/src/Collections/EnumerableTests.DisposeAllAsync.cs @@ -1,34 +1,34 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; +using NSubstitute; +using NUnit.Framework; using X10D.Collections; namespace X10D.Tests.Collections; -public partial class EnumerableTests +internal partial class EnumerableTests { - [TestClass] + [TestFixture] public class DisposeAllAsyncTests { - [TestMethod] + [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(); } - [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..df6442c 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] -public partial class EnumerableTests +[TestFixture] +internal 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..8672a0a 100644 --- a/X10D.Tests/src/Collections/Int16Tests.cs +++ b/X10D.Tests/src/Collections/Int16Tests.cs @@ -1,119 +1,133 @@ -using System.Runtime.Intrinsics.X86; -using Microsoft.VisualStudio.TestTools.UnitTesting; +#if NET5_0_OR_GREATER +using System.Runtime.Intrinsics.X86; +#endif +using NUnit.Framework; using X10D.Collections; namespace X10D.Tests.Collections; -[TestClass] -public class Int16Tests +[TestFixture] +internal 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..97485e1 100644 --- a/X10D.Tests/src/Collections/Int32Tests.cs +++ b/X10D.Tests/src/Collections/Int32Tests.cs @@ -1,81 +1,92 @@ -using System.Runtime.Intrinsics.X86; -using Microsoft.VisualStudio.TestTools.UnitTesting; +#if NET5_0_OR_GREATER +using System.Runtime.Intrinsics.X86; +#endif +using NUnit.Framework; using X10D.Collections; namespace X10D.Tests.Collections; -[TestClass] -public class Int32Tests +[TestFixture] +internal 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 +95,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 +125,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..1cfee79 100644 --- a/X10D.Tests/src/Collections/Int64Tests.cs +++ b/X10D.Tests/src/Collections/Int64Tests.cs @@ -1,68 +1,74 @@ using System.Diagnostics; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Globalization; +using NUnit.Framework; using X10D.Collections; namespace X10D.Tests.Collections; -[TestClass] -public class Int64Tests +[TestFixture] +internal 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(CultureInfo.InvariantCulture)); + } + }); } - [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(CultureInfo.InvariantCulture)); + } + }); } - [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..bd62f8c 100644 --- a/X10D.Tests/src/Collections/ListTests.cs +++ b/X10D.Tests/src/Collections/ListTests.cs @@ -1,16 +1,15 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Collections; namespace X10D.Tests.Collections; -[TestClass] -public class ListTests +[TestFixture] +internal 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(); @@ -26,155 +25,169 @@ public class ListTests CollectionAssert.AreEqual(all42, list); } - [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 +204,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 +224,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 +252,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 +311,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..04f263a 100644 --- a/X10D.Tests/src/Collections/SpanTest.cs +++ b/X10D.Tests/src/Collections/SpanTest.cs @@ -1,52 +1,76 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Collections; namespace X10D.Tests.Collections; -[TestClass] -public class SpanTest +[TestFixture] +internal 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 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() { ReadOnlySpan span = ReadOnlySpan.Empty; @@ -57,10 +81,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 +95,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 +109,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 +123,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 +136,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 +157,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 +176,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 +197,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 +216,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 +237,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 +256,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 +277,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 +297,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 +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_GivenReadOnlySpan() { ReadOnlySpan span = "Hello World ".AsSpan(); @@ -323,20 +347,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 +373,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 +397,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 +426,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 +453,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 +482,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..fea360d 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] -public class CoreTests +[TestFixture] +internal 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..c335b9a 100644 --- a/X10D.Tests/src/Core/EnumTests.cs +++ b/X10D.Tests/src/Core/EnumTests.cs @@ -1,10 +1,10 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Core; namespace X10D.Tests.Core; -[TestClass] -public class EnumTests +[TestFixture] +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. @@ -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..da5fd8e 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] -public class IntrinsicTests +[TestFixture] +internal 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..db4c8ef 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] -public class NullableTests +[TestFixture] +internal 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..5e1022d 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] -public class RandomTests +[TestFixture] +internal 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..85fb460 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] -public class SpanTest +[TestFixture] +internal 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..06a4de8 100644 --- a/X10D.Tests/src/Drawing/CircleFTests.cs +++ b/X10D.Tests/src/Drawing/CircleFTests.cs @@ -1,167 +1,193 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Drawing; +using NUnit.Framework; using X10D.Drawing; namespace X10D.Tests.Drawing; -[TestClass] -public class CircleFTests +[TestFixture] +internal 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)); + + Assert.That(CircleF.Empty != CircleF.Unit); + Assert.That(CircleF.Unit != 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)); + Assert.That(CircleF.Empty.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 = 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 == (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)); + + Assert.That(CircleF.Unit > CircleF.Empty); + Assert.That(CircleF.Unit >= 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 == 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)); + + Assert.That(CircleF.Empty < CircleF.Unit); + Assert.That(CircleF.Empty <= 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..e03fb0c 100644 --- a/X10D.Tests/src/Drawing/CircleTests.cs +++ b/X10D.Tests/src/Drawing/CircleTests.cs @@ -1,145 +1,161 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Drawing; namespace X10D.Tests.Drawing; -[TestClass] -public class CircleTests +[TestFixture] +internal 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)); + + Assert.That(Circle.Empty != Circle.Unit); + Assert.That(Circle.Unit != 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)); + Assert.That(Circle.Empty.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 = 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.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); + }); } - [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.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); + }); } - [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..7868484 100644 --- a/X10D.Tests/src/Drawing/ColorTests.cs +++ b/X10D.Tests/src/Drawing/ColorTests.cs @@ -1,11 +1,11 @@ using System.Drawing; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Drawing; namespace X10D.Tests.Drawing; -[TestClass] -public class ColorTests +[TestFixture] +internal class ColorTests { private static readonly Color Black = Color.FromArgb(0, 0, 0); private static readonly Color White = Color.FromArgb(255, 255, 255); @@ -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..37d006f 100644 --- a/X10D.Tests/src/Drawing/CuboidTests.cs +++ b/X10D.Tests/src/Drawing/CuboidTests.cs @@ -1,82 +1,82 @@ using System.Numerics; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Drawing; namespace X10D.Tests.Drawing; -[TestClass] -public class CuboidTests +[TestFixture] +internal 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)); + Assert.That(cube1 == cube2); + Assert.That(cube2 == 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)); + Assert.That(Cuboid.Empty != 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..aecdcdc 100644 --- a/X10D.Tests/src/Drawing/EllipseFTests.cs +++ b/X10D.Tests/src/Drawing/EllipseFTests.cs @@ -1,156 +1,171 @@ using System.Drawing; using System.Numerics; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Drawing; namespace X10D.Tests.Drawing; -[TestClass] -public class EllipseFTests +[TestFixture] +internal 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)); + Assert.That(unitEllipse2 == unitEllipse1); + Assert.That(unitEllipse1 == 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)); + Assert.That(EllipseF.Empty != EllipseF.Unit); } - [TestMethod] + [Test] public void Equals_ShouldBeFalse_GivenDifferentObjects() { - Assert.IsFalse(EllipseF.Unit.Equals(null)); + Assert.That(EllipseF.Unit, Is.Not.EqualTo(null)); + Assert.That(EllipseF.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 = 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 == 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 == 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..6f938cd 100644 --- a/X10D.Tests/src/Drawing/EllipseTests.cs +++ b/X10D.Tests/src/Drawing/EllipseTests.cs @@ -1,111 +1,128 @@ using System.Drawing; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Drawing; namespace X10D.Tests.Drawing; -[TestClass] -public class EllipseTests +[TestFixture] +internal 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)); + Assert.That(unitEllipse2 == unitEllipse1); + Assert.That(unitEllipse1 == 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)); + Assert.That(Ellipse.Empty != Ellipse.Unit); + Assert.That(Ellipse.Unit != 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..1182a5b 100644 --- a/X10D.Tests/src/Drawing/Line3DTests.cs +++ b/X10D.Tests/src/Drawing/Line3DTests.cs @@ -1,116 +1,115 @@ using System.Drawing; using System.Numerics; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Drawing; namespace X10D.Tests.Drawing; -[TestClass] -public class Line3DTests +[TestFixture] +internal 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)); + Assert.That(second == 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)); + Assert.That(Line3D.Empty != Line3D.One); } - [TestMethod] + [Test] public void Equals_ShouldBeFalse_GivenDifferentObjects() { - Assert.IsFalse(Line3D.One.Equals(null)); + Assert.That(Line3D.One, Is.Not.EqualTo(null)); + Assert.That(Line3D.One.Equals(null), Is.False); } - [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 +118,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 +135,25 @@ 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)); + + Assert.That(Line3D.One > Line3D.Empty); + Assert.That(Line3D.One >= Line3D.Empty); } - [TestMethod] + [Test] public void op_Implicit_ShouldReturnEquivalentLine_GivenLine() { Line oneLine = Line.One; @@ -156,13 +162,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 +180,22 @@ 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 == 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)); + 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 582bde3..412fff2 100644 --- a/X10D.Tests/src/Drawing/LineFTests.cs +++ b/X10D.Tests/src/Drawing/LineFTests.cs @@ -1,146 +1,163 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Drawing; +using NUnit.Framework; using X10D.Drawing; namespace X10D.Tests.Drawing; -[TestClass] -public class LineFTests +[TestFixture] +internal 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)); + Assert.That(second == first); + Assert.That(first == 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)); + Assert.That(LineF.Empty != LineF.One); + Assert.That(LineF.One != LineF.Empty); + }); } - [TestMethod] + [Test] public void Equals_ShouldBeFalse_GivenDifferentObjects() { - Assert.IsFalse(LineF.One.Equals(null)); + Assert.That(LineF.One, Is.Not.EqualTo(null)); + Assert.That(LineF.One.Equals(null), Is.False); } - [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 == 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)); + Assert.That(LineF.One > LineF.Empty); + Assert.That(LineF.One >= 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 == 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)); + 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 2a690e8..24a985d 100644 --- a/X10D.Tests/src/Drawing/LineTests.cs +++ b/X10D.Tests/src/Drawing/LineTests.cs @@ -1,122 +1,131 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Drawing; namespace X10D.Tests.Drawing; -[TestClass] -public class LineTests +[TestFixture] +internal 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)); + Assert.That(second == first); + Assert.That(first == 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)); + Assert.That(Line.Empty != Line.One); + Assert.That(Line.One != Line.Empty); + }); } - [TestMethod] + [Test] public void Equals_ShouldBeFalse_GivenDifferentObjects() { - Assert.IsFalse(Line.One.Equals(null)); + Assert.That(Line.One, Is.Not.EqualTo(null)); + Assert.That(Line.One.Equals(null), Is.False); } - [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)); + Assert.That(Line.One > Line.Empty); + Assert.That(Line.One >= 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)); + Assert.That(Line.Empty < Line.One); + Assert.That(Line.Empty <= Line.One); } } diff --git a/X10D.Tests/src/Drawing/PointFTests.cs b/X10D.Tests/src/Drawing/PointFTests.cs index 87b6f63..aace160 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] -public class PointFTests +[TestFixture] +internal 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..ae07657 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] -public class PointTests +[TestFixture] +internal 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..f6a09de 100644 --- a/X10D.Tests/src/Drawing/PolygonFTests.cs +++ b/X10D.Tests/src/Drawing/PolygonFTests.cs @@ -1,228 +1,230 @@ using System.Drawing; using System.Numerics; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Drawing; namespace X10D.Tests.Drawing; -[TestClass] -public class PolygonFTests +[TestFixture] +internal 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)); + Assert.That(second == first); + Assert.That(first == 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)); + Assert.That(second == first); + Assert.That(first == 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)); + Assert.That(second != first); + Assert.That(first != 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 == 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 +236,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..4d73cd8 100644 --- a/X10D.Tests/src/Drawing/PolygonTests.cs +++ b/X10D.Tests/src/Drawing/PolygonTests.cs @@ -1,136 +1,131 @@ using System.Drawing; -using System.Numerics; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Drawing; namespace X10D.Tests.Drawing; -[TestClass] -public class PolygonTests +[TestFixture] +internal 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.Multiple(() => + { + Assert.That(second, Is.EqualTo(first)); + Assert.That(first, Is.EqualTo(second)); + Assert.That(second == first); + Assert.That(first == second); + }); } - [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.Multiple(() => + { + Assert.That(second, Is.EqualTo(first)); + Assert.That(first, Is.EqualTo(second)); + Assert.That(second == first); + Assert.That(first == second); + }); } - [TestMethod] + [Test] public void Equals_ShouldBeFalse_GivenHexagonAndEmptyPolygon() { Polygon first = CreateHexagon(); Polygon second = Polygon.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)); + Assert.That(second != first); + Assert.That(first != second); + }); } - [TestMethod] + [Test] public void FromPolygonF_ShouldReturnEquivalentPolygon_GivenPolygon() { PolygonF hexagon = CreateHexagonF(); @@ -138,57 +133,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..8e85423 100644 --- a/X10D.Tests/src/Drawing/PolyhedronTests.cs +++ b/X10D.Tests/src/Drawing/PolyhedronTests.cs @@ -1,196 +1,221 @@ using System.Numerics; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Drawing; namespace X10D.Tests.Drawing; -[TestClass] -public class PolyhedronTests +[TestFixture] +internal 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)); + Assert.That(second == first); + Assert.That(first == 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)); + Assert.That(second != first); + Assert.That(first != 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 +227,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..349ca33 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] -public class RandomTests +[TestFixture] +internal 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..47a2a42 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] -public class SizeTests +[TestFixture] +internal 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..dcbf8ce 100644 --- a/X10D.Tests/src/Drawing/SphereTests.cs +++ b/X10D.Tests/src/Drawing/SphereTests.cs @@ -1,135 +1,142 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Drawing; namespace X10D.Tests.Drawing; -[TestClass] -public class SphereTests +[TestFixture] +internal 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)); + Assert.That(unitCircle2 == unitCircle1); + Assert.That(unitCircle1 == unitCircle2); + }); } - [TestMethod] + [Test] public void Equals_ShouldBeFalse_GivenDifferentObjects() { - Assert.IsFalse(Sphere.Unit.Equals(null)); + Assert.That(Sphere.Unit, Is.Not.EqualTo(null)); + Assert.That(Sphere.Unit.Equals(null), Is.False); } - [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)); + Assert.That(Sphere.Empty != Sphere.Unit); + Assert.That(Sphere.Unit != 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)); + Assert.That(Sphere.Unit > Sphere.Empty); + Assert.That(Sphere.Unit >= 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)); + Assert.That(Sphere.Empty < Sphere.Unit); + Assert.That(Sphere.Empty <= 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..0691914 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] -public class ServiceCollectionTests +[TestFixture] +internal class ServiceCollectionTests { - [TestMethod] + [Test] public void AddHostedSingleton_ShouldRegisterServiceAsSingletonAndAsHostedService() { var services = new ServiceCollection(); @@ -19,14 +19,38 @@ 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_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() { var services = new ServiceCollection(); @@ -37,15 +61,48 @@ 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 + [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; diff --git a/X10D.Tests/src/IO/BooleanTests.cs b/X10D.Tests/src/IO/BooleanTests.cs index 8b4701d..2994e03 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] -public class BooleanTests +[TestFixture] +internal 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..433cc09 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] -public class ByteTests +[TestFixture] +internal 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..925902a 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] -public class DirectoryInfoTests +[TestFixture] +internal 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..9b8a43a 100644 --- a/X10D.Tests/src/IO/DoubleTests.cs +++ b/X10D.Tests/src/IO/DoubleTests.cs @@ -1,66 +1,66 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; -[TestClass] -public class DoubleTests +[TestFixture] +internal class DoubleTests { - [TestMethod] - public void GetBytes_ReturnsCorrectValue() + [Test] + 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); } - [TestMethod] - public void GetBytes_ReturnsCorrectValue_WithEndianness() + [Test] + 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); } - [TestMethod] - public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan() + [Test] + 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.IsTrue(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()); } - [TestMethod] - public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan_WithEndianness() + [Test] + 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.IsTrue(value.TryWriteBytes(buffer, Endianness.LittleEndian)); - CollectionAssert.AreEqual(littleEndian, buffer.ToArray()); - - Assert.IsTrue(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()); } - [TestMethod] - public void TryWriteBytes_ReturnsFalse_GivenSmallSpan() + [Test] + public void TryWriteBigEndian_ReturnsFalse_GivenSmallSpan() { const double value = 42.5; Span buffer = stackalloc byte[0]; - Assert.IsFalse(value.TryWriteBytes(buffer)); + 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/FileInfoTests.cs b/X10D.Tests/src/IO/FileInfoTests.cs index a1047ba..319e864 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] -public class FileInfoTests +[TestFixture] +internal 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..8d64f97 100644 --- a/X10D.Tests/src/IO/Int16Tests.cs +++ b/X10D.Tests/src/IO/Int16Tests.cs @@ -1,62 +1,66 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; -[TestClass] -public class Int16Tests +[TestFixture] +internal class Int16Tests { - [TestMethod] - public void GetBytes_ReturnsCorrectValue() + [Test] + 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); } - [TestMethod] - public void GetBytes_ReturnsCorrectValue_WithEndianness() + [Test] + 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); } - [TestMethod] - public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan() + [Test] + 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.IsTrue(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()); } - [TestMethod] - public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan_WithEndianness() + [Test] + public void TryWriteBigEndian_ReturnsTrue_FillsSpanCorrectly() { const short value = 0x0F; - byte[] littleEndian = {0x0F, 0}; - byte[] bigEndian = {0, 0x0F}; - Span buffer = stackalloc byte[2]; - - Assert.IsTrue(value.TryWriteBytes(buffer, Endianness.LittleEndian)); - CollectionAssert.AreEqual(littleEndian, buffer.ToArray()); - - Assert.IsTrue(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()); } - [TestMethod] - public void TryWriteBytes_ReturnsFalse_GivenSmallSpan() + [Test] + public void TryWriteLittleEndian_RReturnsFalse_GivenSmallSpan() { const short value = 0x0F; Span buffer = stackalloc byte[0]; - Assert.IsFalse(value.TryWriteBytes(buffer)); + 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 7135b7c..31898a0 100644 --- a/X10D.Tests/src/IO/Int32Tests.cs +++ b/X10D.Tests/src/IO/Int32Tests.cs @@ -1,62 +1,66 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; -[TestClass] -public class Int32Tests +[TestFixture] +internal class Int32Tests { - [TestMethod] - public void GetBytes_ReturnsCorrectValue() + [Test] + 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); } - [TestMethod] - public void GetBytes_ReturnsCorrectValue_WithEndianness() + [Test] + 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); } - [TestMethod] - public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan() + [Test] + 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.IsTrue(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()); } - [TestMethod] - public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan_WithEndianness() + [Test] + 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.IsTrue(value.TryWriteBytes(buffer, Endianness.LittleEndian)); - CollectionAssert.AreEqual(littleEndian, buffer.ToArray()); - - Assert.IsTrue(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()); } - [TestMethod] - public void TryWriteBytes_ReturnsFalse_GivenSmallSpan() + [Test] + public void TryWriteBigEndian_ReturnsFalse_GivenSmallSpan() { const int value = 0x0F; Span buffer = stackalloc byte[0]; - Assert.IsFalse(value.TryWriteBytes(buffer)); + 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 1f7623b..393b9e0 100644 --- a/X10D.Tests/src/IO/Int64Tests.cs +++ b/X10D.Tests/src/IO/Int64Tests.cs @@ -1,66 +1,66 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; -[TestClass] -public class Int64Tests +[TestFixture] +internal class Int64Tests { - [TestMethod] - public void GetBytes_ReturnsCorrectValue() + [Test] + 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); } - [TestMethod] - public void GetBytes_ReturnsCorrectValue_WithEndianness() + [Test] + 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); } - [TestMethod] - public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan() + [Test] + 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.IsTrue(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()); } - [TestMethod] - public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan_WithEndianness() + [Test] + 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.IsTrue(value.TryWriteBytes(buffer, Endianness.LittleEndian)); - CollectionAssert.AreEqual(littleEndian, buffer.ToArray()); - - Assert.IsTrue(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()); } - [TestMethod] - public void TryWriteBytes_ReturnsFalse_GivenSmallSpan() + [Test] + public void TryWriteLittleEndian_RReturnsFalse_GivenSmallSpan() { const long value = 0x0F; Span buffer = stackalloc byte[0]; - Assert.IsFalse(value.TryWriteBytes(buffer)); + 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/ListOfByteTests.cs b/X10D.Tests/src/IO/ListOfByteTests.cs index 9fe2056..998344d 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] -public class ListOfByteTests +[TestFixture] +internal 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..c9486e2 100644 --- a/X10D.Tests/src/IO/SByteTests.cs +++ b/X10D.Tests/src/IO/SByteTests.cs @@ -1,33 +1,32 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; -[TestClass] -[CLSCompliant(false)] -public class SByteTests +[TestFixture] +internal 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..e7de74d 100644 --- a/X10D.Tests/src/IO/SingleTests.cs +++ b/X10D.Tests/src/IO/SingleTests.cs @@ -1,66 +1,66 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; -[TestClass] -public class SingleTests +[TestFixture] +internal class SingleTests { - [TestMethod] - public void GetBytes_ReturnsCorrectValue() + [Test] + 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); } - [TestMethod] - public void GetBytes_ReturnsCorrectValue_WithEndianness() + [Test] + 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); } - [TestMethod] - public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan() + [Test] + 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.IsTrue(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()); } - [TestMethod] - public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan_WithEndianness() + [Test] + 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.IsTrue(value.TryWriteBytes(buffer, Endianness.LittleEndian)); - CollectionAssert.AreEqual(littleEndian, buffer.ToArray()); - - Assert.IsTrue(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()); } - [TestMethod] - public void TryWriteBytes_ReturnsFalse_GivenSmallSpan() + [Test] + public void TryWriteBigEndian_ReturnsFalse_GivenSmallSpan() { const float value = 42.5f; Span buffer = stackalloc byte[0]; - Assert.IsFalse(value.TryWriteBytes(buffer)); + 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 0c65320..c7fcdb5 100644 --- a/X10D.Tests/src/IO/StreamTests.ReadDecimal.cs +++ b/X10D.Tests/src/IO/StreamTests.ReadDecimal.cs @@ -1,42 +1,43 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Diagnostics.CodeAnalysis; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; -public partial class StreamTests +internal partial class StreamTests { - [TestMethod] - 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)); - } - - [TestMethod] - public void ReadDecimal_ShouldThrowArgumentNullException_GivenNullStream() + [Test] + public void ReadDecimalBigEndian_ShouldThrowArgumentNullException_GivenNullStream() { Stream stream = null!; - Assert.ThrowsException(() => stream.ReadDecimal()); - Assert.ThrowsException(() => stream.ReadDecimal(Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.ReadDecimal(Endianness.BigEndian)); + Assert.Throws(() => stream.ReadDecimalBigEndian()); } - [TestMethod] - public void ReadDecimal_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() + [Test] + 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.ThrowsException(() => stream.ReadDecimal((Endianness)(-1))); + Stream stream = null!; + Assert.Throws(() => stream.ReadDecimalLittleEndian()); } - [TestMethod] - public void ReadDecimal_ShouldReadBigEndian_GivenBigEndian() + [Test] + [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,14 +48,17 @@ public partial class StreamTests stream.Position = 0; const decimal expected = 420.0m; - decimal actual = stream.ReadDecimal(Endianness.BigEndian); + decimal actual = stream.ReadDecimalBigEndian(); - 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] - public void ReadDecimal_ShouldWriteLittleEndian_GivenLittleEndian() + [Test] + public void ReadDecimalLittleEndian_ShouldWriteLittleEndian() { using var stream = new MemoryStream(); ReadOnlySpan bytes = stackalloc byte[] @@ -65,9 +69,12 @@ public partial class StreamTests stream.Position = 0; const decimal expected = 420.0m; - decimal actual = stream.ReadDecimal(Endianness.LittleEndian); + decimal actual = stream.ReadDecimalLittleEndian(); - 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..02f7991 100644 --- a/X10D.Tests/src/IO/StreamTests.ReadDouble.cs +++ b/X10D.Tests/src/IO/StreamTests.ReadDouble.cs @@ -1,67 +1,68 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Diagnostics.CodeAnalysis; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; -public partial class StreamTests +internal partial class StreamTests { - [TestMethod] - 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)); - } - - [TestMethod] - public void ReadDouble_ShouldThrowArgumentNullException_GivenNullStream() + [Test] + public void ReadDoubleBigEndian_ShouldThrowArgumentNullException_GivenNullStream() { Stream stream = null!; - Assert.ThrowsException(() => stream.ReadDouble()); - Assert.ThrowsException(() => stream.ReadDouble(Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.ReadDouble(Endianness.BigEndian)); + Assert.Throws(() => stream.ReadDoubleBigEndian()); } - [TestMethod] - public void ReadDouble_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() + [Test] + 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.ThrowsException(() => stream.ReadDouble((Endianness)(-1))); + Stream stream = null!; + Assert.Throws(() => stream.ReadDoubleLittleEndian()); } - [TestMethod] - public void ReadDouble_ShouldReadBigEndian_GivenBigEndian() + [Test] + [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.AreEqual(8, stream.Position); - Assert.AreEqual(expected, actual); + Assert.That(stream.Position, Is.EqualTo(8)); + Assert.That(actual, Is.EqualTo(expected)); } - [TestMethod] - public void ReadDouble_ShouldWriteLittleEndian_GivenLittleEndian() + [Test] + 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.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..a71d4bd 100644 --- a/X10D.Tests/src/IO/StreamTests.ReadInt16.cs +++ b/X10D.Tests/src/IO/StreamTests.ReadInt16.cs @@ -1,67 +1,68 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Diagnostics.CodeAnalysis; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; -public partial class StreamTests +internal partial class StreamTests { - [TestMethod] - 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)); - } - - [TestMethod] - public void ReadInt16_ShouldThrowArgumentNullException_GivenNullStream() + [Test] + public void ReadInt16BigEndian_ShouldThrowArgumentNullException_GivenNullStream() { Stream stream = null!; - Assert.ThrowsException(() => stream.ReadInt16()); - Assert.ThrowsException(() => stream.ReadInt16(Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.ReadInt16(Endianness.BigEndian)); + Assert.Throws(() => stream.ReadInt16BigEndian()); } - [TestMethod] - public void ReadInt16_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() + [Test] + 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.ThrowsException(() => stream.ReadInt16((Endianness)(-1))); + Stream stream = null!; + Assert.Throws(() => stream.ReadInt16LittleEndian()); } - [TestMethod] - public void ReadInt16_ShouldReadBigEndian_GivenBigEndian() + [Test] + [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.AreEqual(2, stream.Position); - Assert.AreEqual(expected, actual); + Assert.That(stream.Position, Is.EqualTo(2)); + Assert.That(actual, Is.EqualTo(expected)); } - [TestMethod] - public void ReadInt16_ShouldReadLittleEndian_GivenLittleEndian() + [Test] + 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.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..e51ef95 100644 --- a/X10D.Tests/src/IO/StreamTests.ReadInt32.cs +++ b/X10D.Tests/src/IO/StreamTests.ReadInt32.cs @@ -1,67 +1,68 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Diagnostics.CodeAnalysis; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; -public partial class StreamTests +internal partial class StreamTests { - [TestMethod] - 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)); - } - - [TestMethod] - public void ReadInt32_ShouldThrowArgumentNullException_GivenNullStream() + [Test] + public void ReadInt32BigEndian_ShouldThrowArgumentNullException_GivenNullStream() { Stream stream = null!; - Assert.ThrowsException(() => stream.ReadInt32()); - Assert.ThrowsException(() => stream.ReadInt32(Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.ReadInt32(Endianness.BigEndian)); + Assert.Throws(() => stream.ReadInt32BigEndian()); } - [TestMethod] - public void ReadInt32_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() + [Test] + 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.ThrowsException(() => stream.ReadInt32((Endianness)(-1))); + Stream stream = null!; + Assert.Throws(() => stream.ReadInt32LittleEndian()); } - [TestMethod] - public void ReadInt32_ShouldReadBigEndian_GivenBigEndian() + [Test] + [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.AreEqual(4, stream.Position); - Assert.AreEqual(expected, actual); + Assert.That(stream.Position, Is.EqualTo(4)); + Assert.That(actual, Is.EqualTo(expected)); } - [TestMethod] - public void ReadInt32_ShouldReadLittleEndian_GivenLittleEndian() + [Test] + 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.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..faebfda 100644 --- a/X10D.Tests/src/IO/StreamTests.ReadInt64.cs +++ b/X10D.Tests/src/IO/StreamTests.ReadInt64.cs @@ -1,67 +1,65 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; -public partial class StreamTests +internal partial class StreamTests { - [TestMethod] - 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)); - } - - [TestMethod] - public void ReadInt64_ShouldThrowArgumentNullException_GivenNullStream() + [Test] + public void ReadInt64BigEndian_ShouldThrowArgumentNullException_GivenNullStream() { Stream stream = null!; - Assert.ThrowsException(() => stream.ReadInt64()); - Assert.ThrowsException(() => stream.ReadInt64(Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.ReadInt64(Endianness.BigEndian)); + Assert.Throws(() => stream.ReadInt64BigEndian()); } - [TestMethod] - public void ReadInt64_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() + [Test] + 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.ThrowsException(() => stream.ReadInt64((Endianness)(-1))); + Stream stream = null!; + Assert.Throws(() => stream.ReadInt64LittleEndian()); } - [TestMethod] - public void ReadInt64_ShouldReadBigEndian_GivenBigEndian() + [Test] + 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.AreEqual(8, stream.Position); - Assert.AreEqual(expected, actual); + Assert.That(stream.Position, Is.EqualTo(8)); + Assert.That(actual, Is.EqualTo(expected)); } - [TestMethod] - public void ReadInt64_ShouldWriteLittleEndian_GivenLittleEndian() + [Test] + 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.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..ff2336b 100644 --- a/X10D.Tests/src/IO/StreamTests.ReadSingle.cs +++ b/X10D.Tests/src/IO/StreamTests.ReadSingle.cs @@ -1,67 +1,68 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Diagnostics.CodeAnalysis; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; -public partial class StreamTests +internal partial class StreamTests { - [TestMethod] - 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)); - } - - [TestMethod] - public void ReadSingle_ShouldThrowArgumentNullException_GivenNullStream() + [Test] + public void ReadSingleBigEndian_ShouldThrowArgumentNullException_GivenNullStream() { Stream stream = null!; - Assert.ThrowsException(() => stream.ReadSingle()); - Assert.ThrowsException(() => stream.ReadSingle(Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.ReadSingle(Endianness.BigEndian)); + Assert.Throws(() => stream.ReadSingleBigEndian()); } - [TestMethod] - public void ReadSingle_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() + [Test] + 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.ThrowsException(() => stream.ReadSingle((Endianness)(-1))); + Stream stream = null!; + Assert.Throws(() => stream.ReadSingleLittleEndian()); } - [TestMethod] - public void ReadSingle_ShouldReadBigEndian_GivenBigEndian() + [Test] + [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.AreEqual(4, stream.Position); - Assert.AreEqual(expected, actual); + Assert.That(stream.Position, Is.EqualTo(4)); + Assert.That(actual, Is.EqualTo(expected)); } - [TestMethod] - public void ReadSingle_ShouldReadLittleEndian_GivenLittleEndian() + [Test] + 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.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..0cd249d 100644 --- a/X10D.Tests/src/IO/StreamTests.ReadUInt16.cs +++ b/X10D.Tests/src/IO/StreamTests.ReadUInt16.cs @@ -1,72 +1,68 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Diagnostics.CodeAnalysis; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; -public partial class StreamTests +internal partial class StreamTests { - [TestMethod] - [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)); - } - - [TestMethod] - [CLSCompliant(false)] - public void ReadUInt16_ShouldThrowArgumentNullException_GivenNullStream() + [Test] + public void ReadUInt16BigEndian_ShouldThrowArgumentNullException_GivenNullStream() { Stream stream = null!; - Assert.ThrowsException(() => stream.ReadUInt16()); - Assert.ThrowsException(() => stream.ReadUInt16(Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.ReadUInt16(Endianness.BigEndian)); + Assert.Throws(() => stream.ReadUInt16BigEndian()); } - [TestMethod] - [CLSCompliant(false)] - public void ReadUInt16_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() + [Test] + 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.ThrowsException(() => stream.ReadUInt16((Endianness)(-1))); + Stream stream = null!; + Assert.Throws(() => stream.ReadUInt16LittleEndian()); } - [TestMethod] - [CLSCompliant(false)] - public void ReadUInt16_ShouldReadBigEndian_GivenBigEndian() + [Test] + [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.AreEqual(2, stream.Position); - Assert.AreEqual(expected, actual); + Assert.That(stream.Position, Is.EqualTo(2)); + Assert.That(actual, Is.EqualTo(expected)); } - [TestMethod] - [CLSCompliant(false)] - public void ReadUInt16_ShouldReadLittleEndian_GivenLittleEndian() + [Test] + 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.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..3164afe 100644 --- a/X10D.Tests/src/IO/StreamTests.ReadUInt32.cs +++ b/X10D.Tests/src/IO/StreamTests.ReadUInt32.cs @@ -1,72 +1,68 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Diagnostics.CodeAnalysis; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; -public partial class StreamTests +internal partial class StreamTests { - [TestMethod] - [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)); - } - - [TestMethod] - [CLSCompliant(false)] - public void ReadUInt32_ShouldThrowArgumentNullException_GivenNullStream() + [Test] + public void ReadUInt32BigEndian_ShouldThrowArgumentNullException_GivenNullStream() { Stream stream = null!; - Assert.ThrowsException(() => stream.ReadUInt32()); - Assert.ThrowsException(() => stream.ReadUInt32(Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.ReadUInt32(Endianness.BigEndian)); + Assert.Throws(() => stream.ReadUInt32BigEndian()); } - [TestMethod] - [CLSCompliant(false)] - public void ReadUInt32_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() + [Test] + 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.ThrowsException(() => stream.ReadUInt32((Endianness)(-1))); + Stream stream = null!; + Assert.Throws(() => stream.ReadUInt32LittleEndian()); } - [TestMethod] - [CLSCompliant(false)] - public void ReadUInt32_ShouldReadBigEndian_GivenBigEndian() + [Test] + [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.AreEqual(4, stream.Position); - Assert.AreEqual(expected, actual); + Assert.That(stream.Position, Is.EqualTo(4)); + Assert.That(actual, Is.EqualTo(expected)); } - [TestMethod] - [CLSCompliant(false)] - public void ReadUInt32_ShouldReadLittleEndian_GivenLittleEndian() + [Test] + 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.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..ca33b01 100644 --- a/X10D.Tests/src/IO/StreamTests.ReadUInt64.cs +++ b/X10D.Tests/src/IO/StreamTests.ReadUInt64.cs @@ -1,72 +1,68 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Diagnostics.CodeAnalysis; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; -public partial class StreamTests +internal partial class StreamTests { - [TestMethod] - [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)); - } - - [TestMethod] - [CLSCompliant(false)] - public void ReadUInt64_ShouldThrowArgumentNullException_GivenNullStream() + [Test] + public void ReadUInt64BigEndian_ShouldThrowArgumentNullException_GivenNullStream() { Stream stream = null!; - Assert.ThrowsException(() => stream.ReadUInt64()); - Assert.ThrowsException(() => stream.ReadUInt64(Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.ReadUInt64(Endianness.BigEndian)); + Assert.Throws(() => stream.ReadUInt64BigEndian()); } - [TestMethod] - [CLSCompliant(false)] - public void ReadUInt64_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() + [Test] + 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.ThrowsException(() => stream.ReadUInt64((Endianness)(-1))); + Stream stream = null!; + Assert.Throws(() => stream.ReadUInt64LittleEndian()); } - [TestMethod] - [CLSCompliant(false)] - public void ReadUInt64_ShouldReadBigEndian_GivenBigEndian() + [Test] + [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.AreEqual(8, stream.Position); - Assert.AreEqual(expected, actual); + Assert.That(stream.Position, Is.EqualTo(8)); + Assert.That(actual, Is.EqualTo(expected)); } - [TestMethod] - [CLSCompliant(false)] - public void ReadUInt64_ShouldWriteLittleEndian_GivenLittleEndian() + [Test] + 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.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..911dd5d 100644 --- a/X10D.Tests/src/IO/StreamTests.WriteDecimal.cs +++ b/X10D.Tests/src/IO/StreamTests.WriteDecimal.cs @@ -1,65 +1,67 @@ using System.Diagnostics; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Diagnostics.CodeAnalysis; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; -public partial class StreamTests +internal partial class StreamTests { - [TestMethod] - 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)); - } - - [TestMethod] - public void WriteDecimal_ShouldThrowArgumentNullException_GivenNullStream() + [Test] + public void WriteBigEndian_ShouldThrowArgumentNullException_GivenNullStream_AndDecimalArgument() { Stream stream = null!; - Assert.ThrowsException(() => stream.Write(420.0m, Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.Write(420.0m, Endianness.BigEndian)); + Assert.Throws(() => stream.WriteBigEndian(420.0m)); } - [TestMethod] - public void WriteDecimal_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() + [Test] + [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.ThrowsException(() => stream.Write(420.0m, (Endianness)(-1))); - Assert.ThrowsException(() => stream.Write(420.0m, (Endianness)(-1))); + Stream stream = new DummyStream(); + Assert.Throws(() => stream.WriteBigEndian(420.0m)); } - [TestMethod] - public void WriteDecimal_ShouldWriteBigEndian_GivenBigEndian() + [Test] + 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); - Assert.AreEqual(16, stream.Position); + 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); - Assert.AreEqual(16, read); + Assert.That(read, Is.EqualTo(16)); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); } - [TestMethod] - public void WriteDecimal_ShouldWriteLittleEndian_GivenLittleEndian() + [Test] + public void WriteLittleEndian_ShouldWriteLittleEndian_GivenDecimalArgument() { using var stream = new MemoryStream(); - stream.Write(420.0m, Endianness.LittleEndian); - Assert.AreEqual(16, stream.Position); + stream.WriteLittleEndian(420.0m); + Assert.That(stream.Position, Is.EqualTo(16)); stream.Position = 0; Span actual = stackalloc byte[16]; @@ -71,7 +73,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..8828325 100644 --- a/X10D.Tests/src/IO/StreamTests.WriteDouble.cs +++ b/X10D.Tests/src/IO/StreamTests.WriteDouble.cs @@ -1,68 +1,70 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Diagnostics.CodeAnalysis; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; -public partial class StreamTests +internal partial class StreamTests { - [TestMethod] - 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)); - } - - [TestMethod] - public void WriteDouble_ShouldThrowArgumentNullException_GivenNullStream() + [Test] + public void WriteBigEndian_ShouldThrowArgumentNullException_GivenNullStream_AndDoubleArgument() { Stream stream = null!; - Assert.ThrowsException(() => stream.Write(420.0, Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.Write(420.0, Endianness.BigEndian)); + Assert.Throws(() => stream.WriteBigEndian(420.0)); } - [TestMethod] - public void WriteDouble_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() + [Test] + [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.ThrowsException(() => stream.Write(420.0, (Endianness)(-1))); - Assert.ThrowsException(() => stream.Write(420.0, (Endianness)(-1))); + Stream stream = new DummyStream(); + Assert.Throws(() => stream.WriteBigEndian(420.0)); } - [TestMethod] - public void WriteDouble_ShouldWriteBigEndian_GivenBigEndian() + [Test] + 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); - Assert.AreEqual(8, stream.Position); + 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.AreEqual(8, read); + Assert.That(read, Is.EqualTo(8)); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); } - [TestMethod] - public void WriteDouble_ShouldWriteLittleEndian_GivenLittleEndian() + [Test] + public void WriteLittleEndian_ShouldWriteLittleEndian_GivenDoubleArgument() { using var stream = new MemoryStream(); - stream.Write(420.0, Endianness.LittleEndian); - Assert.AreEqual(8, stream.Position); + 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.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..bc38dd8 100644 --- a/X10D.Tests/src/IO/StreamTests.WriteInt16.cs +++ b/X10D.Tests/src/IO/StreamTests.WriteInt16.cs @@ -1,68 +1,70 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Diagnostics.CodeAnalysis; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; -public partial class StreamTests +internal partial class StreamTests { - [TestMethod] - 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)); - } - - [TestMethod] - public void WriteInt16_ShouldThrowArgumentNullException_GivenNullStream() + [Test] + public void WriteBigEndian_ShouldThrowArgumentNullException_GivenNullStream_AndInt16Argument() { Stream stream = null!; - Assert.ThrowsException(() => stream.Write((short)420, Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.Write((short)420, Endianness.BigEndian)); + Assert.Throws(() => stream.WriteBigEndian((short)420)); } - [TestMethod] - public void WriteInt16_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() + [Test] + [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.ThrowsException(() => stream.Write((short)420, (Endianness)(-1))); - Assert.ThrowsException(() => stream.Write((short)420, (Endianness)(-1))); + Stream stream = new DummyStream(); + Assert.Throws(() => stream.WriteBigEndian((short)420)); } - [TestMethod] - public void WriteInt16_ShouldWriteBigEndian_GivenBigEndian() + [Test] + 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); - Assert.AreEqual(2, stream.Position); + 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.AreEqual(2, read); + Assert.That(read, Is.EqualTo(2)); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); } - [TestMethod] - public void WriteInt16_ShouldWriteLittleEndian_GivenLittleEndian() + [Test] + public void WriteLittleEndian_ShouldWriteLittleEndian_GivenInt16Argument() { using var stream = new MemoryStream(); - stream.Write((short)420, Endianness.LittleEndian); - Assert.AreEqual(2, stream.Position); + 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.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..75688f9 100644 --- a/X10D.Tests/src/IO/StreamTests.WriteInt32.cs +++ b/X10D.Tests/src/IO/StreamTests.WriteInt32.cs @@ -1,68 +1,70 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Diagnostics.CodeAnalysis; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; -public partial class StreamTests +internal partial class StreamTests { - [TestMethod] - public void WriteInt32_ShouldThrowArgumentException_GivenNonWriteableStream() - { - Stream stream = new DummyStream(); - Assert.ThrowsException(() => stream.Write(420, Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.Write(420, Endianness.BigEndian)); - } - - [TestMethod] - public void WriteInt32_ShouldThrowArgumentNullException_GivenNullStream() + [Test] + public void WriteBigEndian_ShouldThrowArgumentNullException_GivenNullStream_AndInt32Argument() { Stream stream = null!; - Assert.ThrowsException(() => stream.Write(420, Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.Write(420, Endianness.BigEndian)); + Assert.Throws(() => stream.WriteBigEndian(420)); } - [TestMethod] - public void WriteInt32_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() + [Test] + [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.ThrowsException(() => stream.Write(420, (Endianness)(-1))); - Assert.ThrowsException(() => stream.Write(420, (Endianness)(-1))); + Stream stream = new DummyStream(); + Assert.Throws(() => stream.WriteBigEndian(420)); } - [TestMethod] - public void WriteInt32_ShouldWriteBigEndian_GivenBigEndian() + [Test] + 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); - Assert.AreEqual(4, stream.Position); + 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.AreEqual(4, read); + Assert.That(read, Is.EqualTo(4)); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); } - [TestMethod] - public void WriteInt32_ShouldWriteLittleEndian_GivenLittleEndian() + [Test] + public void WriteLittleEndian_ShouldWriteLittleEndian_GivenInt32Argument() { using var stream = new MemoryStream(); - stream.Write(420, Endianness.LittleEndian); - Assert.AreEqual(4, stream.Position); + 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.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..feeb677 100644 --- a/X10D.Tests/src/IO/StreamTests.WriteInt64.cs +++ b/X10D.Tests/src/IO/StreamTests.WriteInt64.cs @@ -1,68 +1,70 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Diagnostics.CodeAnalysis; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; -public partial class StreamTests +internal partial class StreamTests { - [TestMethod] - public void WriteInt64_ShouldThrowArgumentException_GivenNonWriteableStream() - { - Stream stream = new DummyStream(); - Assert.ThrowsException(() => stream.Write(420L, Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.Write(420L, Endianness.BigEndian)); - } - - [TestMethod] - public void WriteInt64_ShouldThrowArgumentNullException_GivenNullStream() + [Test] + public void WriteBigEndian_ShouldThrowArgumentNullException_GivenNullStream_AndInt64Argument() { Stream stream = null!; - Assert.ThrowsException(() => stream.Write(420L, Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.Write(420L, Endianness.BigEndian)); + Assert.Throws(() => stream.WriteBigEndian(420L)); } - [TestMethod] - public void WriteInt64_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() + [Test] + [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.ThrowsException(() => stream.Write(420L, (Endianness)(-1))); - Assert.ThrowsException(() => stream.Write(420L, (Endianness)(-1))); + Stream stream = new DummyStream(); + Assert.Throws(() => stream.WriteBigEndian(420L)); } - [TestMethod] - public void WriteInt64_ShouldWriteBigEndian_GivenBigEndian() + [Test] + 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); - Assert.AreEqual(8, stream.Position); + 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.AreEqual(8, read); + Assert.That(read, Is.EqualTo(8)); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); } - [TestMethod] - public void WriteInt64_ShouldWriteLittleEndian_GivenLittleEndian() + [Test] + public void WriteLittleEndian_ShouldWriteLittleEndian_GivenLittleEndian() { using var stream = new MemoryStream(); - stream.Write(420L, Endianness.LittleEndian); - Assert.AreEqual(8, stream.Position); + 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.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..7df8eb8 100644 --- a/X10D.Tests/src/IO/StreamTests.WriteSingle.cs +++ b/X10D.Tests/src/IO/StreamTests.WriteSingle.cs @@ -1,68 +1,70 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Diagnostics.CodeAnalysis; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; -public partial class StreamTests +internal partial class StreamTests { - [TestMethod] - 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)); - } - - [TestMethod] - public void WriteSingle_ShouldThrowArgumentNullException_GivenNullStream() + [Test] + public void WriteBigEndian_ShouldThrowArgumentNullException_GivenNullStream_AndSingleArgument() { Stream stream = null!; - Assert.ThrowsException(() => stream.Write(420.0f, Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.Write(420.0f, Endianness.BigEndian)); + Assert.Throws(() => stream.WriteBigEndian(420.0f)); } - [TestMethod] - public void WriteSingle_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() + [Test] + [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.ThrowsException(() => stream.Write(420.0f, (Endianness)(-1))); - Assert.ThrowsException(() => stream.Write(420.0f, (Endianness)(-1))); + Stream stream = new DummyStream(); + Assert.Throws(() => stream.WriteBigEndian(420.0f)); } - [TestMethod] - public void WriteSingle_ShouldWriteBigEndian_GivenBigEndian() + [Test] + 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); - Assert.AreEqual(4, stream.Position); + 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.AreEqual(4, read); + Assert.That(read, Is.EqualTo(4)); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); } - [TestMethod] - public void WriteSingle_ShouldWriteLittleEndian_GivenLittleEndian() + [Test] + public void WriteLittleEndian_ShouldWriteLittleEndian_GivenSingleArgument() { using var stream = new MemoryStream(); - stream.Write(420.0f, Endianness.LittleEndian); - Assert.AreEqual(4, stream.Position); + 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.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..7fde9f2 100644 --- a/X10D.Tests/src/IO/StreamTests.WriteUInt16.cs +++ b/X10D.Tests/src/IO/StreamTests.WriteUInt16.cs @@ -1,73 +1,70 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Diagnostics.CodeAnalysis; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; -public partial class StreamTests +internal partial class StreamTests { - [TestMethod] - [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)); - } - - [TestMethod] - [CLSCompliant(false)] - public void WriteUInt16_ShouldThrowArgumentNullException_GivenNullStream() + [Test] + public void WriteBigEndian_ShouldThrowArgumentNullException_GivenNullStream_AndUInt16Argument() { Stream stream = null!; - Assert.ThrowsException(() => stream.Write((ushort)420, Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.Write((ushort)420, Endianness.BigEndian)); + Assert.Throws(() => stream.WriteBigEndian((ushort)420)); } - [TestMethod] - [CLSCompliant(false)] - public void WriteUInt16_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() + [Test] + [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.ThrowsException(() => stream.Write((ushort)420, (Endianness)(-1))); - Assert.ThrowsException(() => stream.Write((ushort)420, (Endianness)(-1))); + Stream stream = new DummyStream(); + Assert.Throws(() => stream.WriteBigEndian((ushort)420)); } - [TestMethod] - [CLSCompliant(false)] - public void WriteUInt16_ShouldWriteBigEndian_GivenBigEndian() + [Test] + 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); - Assert.AreEqual(2, stream.Position); + 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.AreEqual(2, read); + Assert.That(read, Is.EqualTo(2)); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); } - [TestMethod] - [CLSCompliant(false)] - public void WriteUInt16_ShouldWriteLittleEndian_GivenLittleEndian() + [Test] + public void WriteLittleEndian_ShouldWriteLittleEndian_GivenUInt16tleEndian() { using var stream = new MemoryStream(); - stream.Write((ushort)420, Endianness.LittleEndian); - Assert.AreEqual(2, stream.Position); + 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.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..e5eafb7 100644 --- a/X10D.Tests/src/IO/StreamTests.WriteUInt32.cs +++ b/X10D.Tests/src/IO/StreamTests.WriteUInt32.cs @@ -1,73 +1,70 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Diagnostics.CodeAnalysis; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; -public partial class StreamTests +internal partial class StreamTests { - [TestMethod] - [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)); - } - - [TestMethod] - [CLSCompliant(false)] - public void WriteUInt32_ShouldThrowArgumentNullException_GivenNullStream() + [Test] + public void WriteBigEndian_ShouldThrowArgumentNullException_GivenNullStream_AndUInt32Argument() { Stream stream = null!; - Assert.ThrowsException(() => stream.Write(420U, Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.Write(420U, Endianness.BigEndian)); + Assert.Throws(() => stream.WriteBigEndian(420U)); } - [TestMethod] - [CLSCompliant(false)] - public void WriteUInt32_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() + [Test] + [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.ThrowsException(() => stream.Write(420U, (Endianness)(-1))); - Assert.ThrowsException(() => stream.Write(420U, (Endianness)(-1))); + Stream stream = new DummyStream(); + Assert.Throws(() => stream.WriteBigEndian(420U)); } - [TestMethod] - [CLSCompliant(false)] - public void WriteUInt32_ShouldWriteBigEndian_GivenBigEndian() + [Test] + 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); - Assert.AreEqual(4, stream.Position); + 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.AreEqual(4, read); + Assert.That(read, Is.EqualTo(4)); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); } - [TestMethod] - [CLSCompliant(false)] - public void WriteUInt32_ShouldWriteLittleEndian_GivenLittleEndian() + [Test] + public void WriteLittleEndian_ShouldWriteLittleEndian_GivenUInt32Argument() { using var stream = new MemoryStream(); - stream.Write(420U, Endianness.LittleEndian); - Assert.AreEqual(4, stream.Position); + 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.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..1bf8464 100644 --- a/X10D.Tests/src/IO/StreamTests.WriteUInt64.cs +++ b/X10D.Tests/src/IO/StreamTests.WriteUInt64.cs @@ -1,73 +1,70 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Diagnostics.CodeAnalysis; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; -public partial class StreamTests +internal partial class StreamTests { - [TestMethod] - [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)); - } - - [TestMethod] - [CLSCompliant(false)] - public void WriteUInt64_ShouldThrowArgumentNullException_GivenNullStream() + [Test] + public void WriteBigEndian_ShouldThrowArgumentNullException_GivenNullStream_AndUInt64Argument() { Stream stream = null!; - Assert.ThrowsException(() => stream.Write(420UL, Endianness.LittleEndian)); - Assert.ThrowsException(() => stream.Write(420UL, Endianness.BigEndian)); + Assert.Throws(() => stream.WriteBigEndian(420UL)); } - [TestMethod] - [CLSCompliant(false)] - public void WriteUInt64_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() + [Test] + [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.ThrowsException(() => stream.Write(420UL, (Endianness)(-1))); - Assert.ThrowsException(() => stream.Write(420UL, (Endianness)(-1))); + Stream stream = new DummyStream(); + Assert.Throws(() => stream.WriteBigEndian(420UL)); } - [TestMethod] - [CLSCompliant(false)] - public void WriteUInt64_ShouldWriteBigEndian_GivenBigEndian() + [Test] + 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); - Assert.AreEqual(8, stream.Position); + 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.AreEqual(8, read); + Assert.That(read, Is.EqualTo(8)); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); } - [TestMethod] - [CLSCompliant(false)] - public void WriteUInt64_ShouldWriteLittleEndian_GivenLittleEndian() + [Test] + public void WriteLittleEndian_ShouldWriteLittleEndian_GivenUInt64Argument() { using var stream = new MemoryStream(); - stream.Write(420UL, Endianness.LittleEndian); - Assert.AreEqual(8, stream.Position); + 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.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..b522265 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] -public partial class StreamTests +[TestFixture] +internal 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,48 @@ 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(() => - Stream.Null.TryWriteHash(Span.Empty, out _)); + 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..a6ff77e 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] -public class TextReaderTests +[TestFixture] +internal 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/TextWriterTests.Double.cs b/X10D.Tests/src/IO/TextWriterTests.Double.cs new file mode 100644 index 0000000..0eb9361 --- /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; + +internal 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.Int32.cs b/X10D.Tests/src/IO/TextWriterTests.Int32.cs new file mode 100644 index 0000000..46d13b6 --- /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; + +internal 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..f9b10b4 --- /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; + +internal 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.Single.cs b/X10D.Tests/src/IO/TextWriterTests.Single.cs new file mode 100644 index 0000000..35629b3 --- /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; + +internal 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.Tests/src/IO/TextWriterTests.UInt32.cs b/X10D.Tests/src/IO/TextWriterTests.UInt32.cs new file mode 100644 index 0000000..5b35c99 --- /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; + +internal 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..a7b4551 --- /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; + +internal 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..6c0945b --- /dev/null +++ b/X10D.Tests/src/IO/TextWriterTests.cs @@ -0,0 +1,59 @@ +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Text; +using NUnit.Framework; + +namespace X10D.Tests.IO; + +[TestFixture] +[SuppressMessage("Design", "CA1001:Types that own disposable fields should be disposable")] +internal partial class TextWriterTests +{ + private MemoryStream _stream = null!; + private StreamWriter _writer = null!; + + [OneTimeSetUp] + public void OneTimeSetup() + { + _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); + _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.Tests/src/IO/UInt16Tests.cs b/X10D.Tests/src/IO/UInt16Tests.cs index 08c0e61..4ce858d 100644 --- a/X10D.Tests/src/IO/UInt16Tests.cs +++ b/X10D.Tests/src/IO/UInt16Tests.cs @@ -1,63 +1,68 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; -[TestClass] -[CLSCompliant(false)] -public class UInt16Tests +[TestFixture] +internal class UInt16Tests { - [TestMethod] - public void GetBytes_ReturnsCorrectValue() + [Test] + 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); } - [TestMethod] - public void GetBytes_ReturnsCorrectValue_WithEndianness() + [Test] + 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); } - [TestMethod] - public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan() + [Test] + 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.IsTrue(value.TryWriteBytes(buffer)); - CollectionAssert.AreEqual(bytes, buffer.ToArray()); + Span actual = stackalloc byte[2]; + Assert.That(value.TryWriteLittleEndian(actual)); + + CollectionAssert.AreEqual(expected, actual.ToArray()); } - [TestMethod] - public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan_WithEndianness() + [Test] + 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.IsTrue(value.TryWriteBytes(buffer, Endianness.LittleEndian)); - CollectionAssert.AreEqual(littleEndian, buffer.ToArray()); - - Assert.IsTrue(value.TryWriteBytes(buffer, Endianness.BigEndian)); - CollectionAssert.AreEqual(bigEndian, buffer.ToArray()); + CollectionAssert.AreEqual(expected, actual.ToArray()); } - [TestMethod] - public void TryWriteBytes_ReturnsFalse_GivenSmallSpan() + [Test] + public void TryWriteLittleEndian_RReturnsFalse_GivenSmallSpan() { const ushort value = 0x0F; Span buffer = stackalloc byte[0]; - Assert.IsFalse(value.TryWriteBytes(buffer)); + 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 a9b3cc9..eada9aa 100644 --- a/X10D.Tests/src/IO/UInt32Tests.cs +++ b/X10D.Tests/src/IO/UInt32Tests.cs @@ -1,63 +1,68 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; -[TestClass] -[CLSCompliant(false)] -public class UInt32Tests +[TestFixture] +internal class UInt32Tests { - [TestMethod] - public void GetBytes_ReturnsCorrectValue() + [Test] + 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); } - [TestMethod] - public void GetBytes_ReturnsCorrectValue_WithEndianness() + [Test] + 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); } - [TestMethod] - public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan() + [Test] + 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.IsTrue(value.TryWriteBytes(buffer)); - CollectionAssert.AreEqual(bytes, buffer.ToArray()); + Span actual = stackalloc byte[4]; + Assert.That(value.TryWriteLittleEndian(actual)); + + CollectionAssert.AreEqual(expected, actual.ToArray()); } - [TestMethod] - public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan_WithEndianness() + [Test] + 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.IsTrue(value.TryWriteBytes(buffer, Endianness.LittleEndian)); - CollectionAssert.AreEqual(littleEndian, buffer.ToArray()); - - Assert.IsTrue(value.TryWriteBytes(buffer, Endianness.BigEndian)); - CollectionAssert.AreEqual(bigEndian, buffer.ToArray()); + CollectionAssert.AreEqual(expected, actual.ToArray()); } - [TestMethod] - public void TryWriteBytes_ReturnsFalse_GivenSmallSpan() + [Test] + public void TryWriteLittleEndian_RReturnsFalse_GivenSmallSpan() { const uint value = 0x0F; Span buffer = stackalloc byte[0]; - Assert.IsFalse(value.TryWriteBytes(buffer)); + 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 d31a209..6ed1be8 100644 --- a/X10D.Tests/src/IO/UInt64Tests.cs +++ b/X10D.Tests/src/IO/UInt64Tests.cs @@ -1,67 +1,68 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.IO; namespace X10D.Tests.IO; -[TestClass] -[CLSCompliant(false)] -public class UInt64Tests +[TestFixture] +internal class UInt64Tests { - [TestMethod] - public void GetBytes_ReturnsCorrectValue() + [Test] + 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); } - [TestMethod] - public void GetBytes_ReturnsCorrectValue_WithEndianness() + [Test] + 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); } - [TestMethod] - public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan() + [Test] + 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.IsTrue(value.TryWriteBytes(buffer)); - CollectionAssert.AreEqual(bytes, buffer.ToArray()); + Span actual = stackalloc byte[8]; + Assert.That(value.TryWriteLittleEndian(actual)); + + CollectionAssert.AreEqual(expected, actual.ToArray()); } - [TestMethod] - public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan_WithEndianness() + [Test] + 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.IsTrue(value.TryWriteBytes(buffer, Endianness.LittleEndian)); - CollectionAssert.AreEqual(littleEndian, buffer.ToArray()); - - Assert.IsTrue(value.TryWriteBytes(buffer, Endianness.BigEndian)); - CollectionAssert.AreEqual(bigEndian, buffer.ToArray()); + CollectionAssert.AreEqual(expected, actual.ToArray()); } - [TestMethod] - public void TryWriteBytes_ReturnsFalse_GivenSmallSpan() + [Test] + public void TryWriteLittleEndian_RReturnsFalse_GivenSmallSpan() { const ulong value = 0x0F; Span buffer = stackalloc byte[0]; - Assert.IsFalse(value.TryWriteBytes(buffer)); + 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.Tests/src/Linq/ByteTests.cs b/X10D.Tests/src/Linq/ByteTests.cs index e98fe31..0ece8b6 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] -public class ByteTests +[TestFixture] +internal 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(current, Is.EqualTo(end)); } - [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(current, Is.EqualTo(end)); } - [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(current, Is.EqualTo(end)); } - [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(current, Is.EqualTo(end)); } } diff --git a/X10D.Tests/src/Linq/DecimalTests.cs b/X10D.Tests/src/Linq/DecimalTests.cs index 6fd9da4..db0e66b 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] -public class DecimalTests +[TestFixture] +internal 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..01399ea 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] -public class DoubleTests +[TestFixture] +internal 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..253690a 100644 --- a/X10D.Tests/src/Linq/EnumerableTests.cs +++ b/X10D.Tests/src/Linq/EnumerableTests.cs @@ -1,184 +1,214 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Linq; namespace X10D.Tests.Linq; -[TestClass] -public class EnumerableTests +[TestFixture] +internal class EnumerableTests { - [TestMethod] - public void ConcatOne_ShouldReturnConcatenatedSequence_GivenValidSequenceAndValue() + [Test] + public void Except_ShouldFilterElements_GivenMatchingElements() { - IEnumerable source = new[] {"Hello"}; - string[] expected = {"Hello", "World"}; + int[] source = Enumerable.Range(1, 10).ToArray(); + int[] result = source.Except(5).ToArray(); - string[] actual = source.ConcatOne("World").ToArray(); - - Assert.AreEqual(2, actual.Length); - CollectionAssert.AreEqual(expected, actual); + Assert.That(result, Is.EquivalentTo(new[] {1, 2, 3, 4, 6, 7, 8, 9, 10})); } - [TestMethod] - public void ConcatOne_ShouldReturnSingletonSequence_GivenEmptySequenceAndValidValue() + [Test] + public void Except_ShouldReturnSameElements_GivenNoMatchingElements() { - IEnumerable source = Enumerable.Empty(); - string[] expected = {"Foobar"}; + int[] source = Enumerable.Range(1, 10).ToArray(); + int[] result = source.Except(11).ToArray(); - string[] actual = source.ConcatOne("Foobar").ToArray(); - - Assert.AreEqual(1, actual.Length); - CollectionAssert.AreEqual(expected, actual); + Assert.That(result, Is.EquivalentTo(source)); } - [TestMethod] - public void ConcatOne_ShouldThrowArgumentNullException_GivenNullSource() + [Test] + public void Except_ShouldThrowArgumentNullException_GivenNullSource() { - IEnumerable? source = null; - Assert.ThrowsException(() => source!.ConcatOne("Foobar").ToArray()); + IEnumerable source = null!; + Assert.Throws(() => source.Except(42)); } - [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..76a6a48 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] -public class Int16Tests +[TestFixture] +internal 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..5f8422a 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] -public class Int32Tests +[TestFixture] +internal 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(current, Is.EqualTo(end)); } - [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(current, Is.EqualTo(end)); } } diff --git a/X10D.Tests/src/Linq/Int64Tests.cs b/X10D.Tests/src/Linq/Int64Tests.cs index ebbb1fa..aad0738 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] -public class Int64Tests +[TestFixture] +internal 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(current, Is.EqualTo(end)); } } diff --git a/X10D.Tests/src/Linq/ReadOnlySpanTests.cs b/X10D.Tests/src/Linq/ReadOnlySpanTests.cs index 4f2cbd9..942e646 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] -public class ReadOnlySpanTests +[TestFixture] +internal 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)); + 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); } - [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)); + 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); } - [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)); + 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)); } - [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..a859279 100644 --- a/X10D.Tests/src/Linq/SByteTests.cs +++ b/X10D.Tests/src/Linq/SByteTests.cs @@ -1,45 +1,44 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Linq; namespace X10D.Tests.Linq; -[TestClass] -[CLSCompliant(false)] -public class SByteTests +[TestFixture] +internal 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..0bac265 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] -public class SingleTests +[TestFixture] +internal 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..313dea1 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] -public class SpanTests +[TestFixture] +internal 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)); + 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); } - [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)); + 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); } - [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)); + 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)); } - [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..8abfc97 100644 --- a/X10D.Tests/src/Linq/UInt16Tests.cs +++ b/X10D.Tests/src/Linq/UInt16Tests.cs @@ -1,51 +1,50 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Linq; namespace X10D.Tests.Linq; -[TestClass] -[CLSCompliant(false)] -public class UInt16Tests +[TestFixture] +internal 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..20d1217 100644 --- a/X10D.Tests/src/Linq/UInt32Tests.cs +++ b/X10D.Tests/src/Linq/UInt32Tests.cs @@ -1,53 +1,52 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Linq; namespace X10D.Tests.Linq; -[TestClass] -[CLSCompliant(false)] -public class UInt32Tests +[TestFixture] +internal 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..64710d3 100644 --- a/X10D.Tests/src/Linq/UInt64Tests.cs +++ b/X10D.Tests/src/Linq/UInt64Tests.cs @@ -1,53 +1,52 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Linq; namespace X10D.Tests.Linq; -[TestClass] -[CLSCompliant(false)] -public class UInt64Tests +[TestFixture] +internal 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..ecff3df 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 +internal 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..80c0cec 100644 --- a/X10D.Tests/src/Math/BigIntegerTests.cs +++ b/X10D.Tests/src/Math/BigIntegerTests.cs @@ -1,69 +1,129 @@ using System.Numerics; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Math; namespace X10D.Tests.Math; -[TestClass] -public partial class BigIntegerTests +[TestFixture] +internal partial class BigIntegerTests { - [TestMethod] + [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() { 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 +132,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 +144,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 +157,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 +170,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 +182,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..91c214f 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 +internal 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..0d80790 100644 --- a/X10D.Tests/src/Math/ByteTests.cs +++ b/X10D.Tests/src/Math/ByteTests.cs @@ -1,36 +1,80 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Math; namespace X10D.Tests.Math; -[TestClass] -public partial class ByteTests +[TestFixture] +internal partial class ByteTests { - [TestMethod] + [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() { 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 +82,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 +93,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 +125,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 +137,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 +150,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 +163,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..cb90266 100644 --- a/X10D.Tests/src/Math/ComparableTests.cs +++ b/X10D.Tests/src/Math/ComparableTests.cs @@ -1,10 +1,10 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Math; namespace X10D.Tests.Math; -[TestClass] -public class ComparableTests +[TestFixture] +internal 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..1408043 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 +internal 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..8c4b31e 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] -public partial class DecimalTests +[TestFixture] +internal 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..fdc5ada 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 +internal 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..3929b24 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] -public partial class DoubleTests +[TestFixture] +internal 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..b5f20d7 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 +internal 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..5612e4b 100644 --- a/X10D.Tests/src/Math/Int16Tests.cs +++ b/X10D.Tests/src/Math/Int16Tests.cs @@ -1,36 +1,91 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Math; namespace X10D.Tests.Math; -[TestClass] -public partial class Int16Tests +[TestFixture] +internal partial class Int16Tests { - [TestMethod] + [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() { 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 +93,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 +104,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 +136,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 +148,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 +161,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 +174,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 +186,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..754ae48 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 +internal 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..0bfbf25 100644 --- a/X10D.Tests/src/Math/Int32Tests.cs +++ b/X10D.Tests/src/Math/Int32Tests.cs @@ -1,36 +1,91 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Math; namespace X10D.Tests.Math; -[TestClass] -public partial class Int32Tests +[TestFixture] +internal partial class Int32Tests { - [TestMethod] + [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() { 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 +93,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 +104,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 +136,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 +148,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 +160,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 +172,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 +185,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..6434295 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 +internal 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..bd5f524 100644 --- a/X10D.Tests/src/Math/Int64Tests.cs +++ b/X10D.Tests/src/Math/Int64Tests.cs @@ -1,36 +1,91 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Math; namespace X10D.Tests.Math; -[TestClass] -public partial class Int64Tests +[TestFixture] +internal partial class Int64Tests { - [TestMethod] + [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() { 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 +93,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 +104,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 +136,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 +148,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 +161,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 +174,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 +186,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..4d50e68 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] -public class IsPrimeTests +[TestFixture] +internal 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..01028a2 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] -public class MathUtilityTests +[TestFixture] +internal 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..dd7b9b9 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 +internal 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..9550cfb 100644 --- a/X10D.Tests/src/Math/SByteTests.cs +++ b/X10D.Tests/src/Math/SByteTests.cs @@ -1,37 +1,91 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Math; namespace X10D.Tests.Math; -[TestClass] -[CLSCompliant(false)] -public partial class SByteTests +[TestFixture] +internal partial class SByteTests { - [TestMethod] + [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() { 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 +93,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 +104,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 +136,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 +148,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 +160,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 +173,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 +186,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..596a40a 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 +internal 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..5e50fe7 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] -public partial class SingleTests +[TestFixture] +internal 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..e5be525 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 +internal 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..c6f38ad 100644 --- a/X10D.Tests/src/Math/UInt16Tests.cs +++ b/X10D.Tests/src/Math/UInt16Tests.cs @@ -1,37 +1,80 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Math; namespace X10D.Tests.Math; -[TestClass] -[CLSCompliant(false)] -public partial class UInt16Tests +[TestFixture] +internal partial class UInt16Tests { - [TestMethod] + [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() { 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 +82,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 +93,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 +125,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 +137,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 +150,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 +163,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..572f71c 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 +internal 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 0ea052b..f2db8e8 100644 --- a/X10D.Tests/src/Math/UInt32Tests.cs +++ b/X10D.Tests/src/Math/UInt32Tests.cs @@ -1,43 +1,79 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Math; namespace X10D.Tests.Math; -[TestClass] -[CLSCompliant(false)] -public partial class UInt32Tests +[TestFixture] +internal partial class UInt32Tests { - [TestMethod] + [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() { const uint value = 238; - -#if NET7_0_OR_GREATER - Assert.AreEqual(4, value.DigitalRoot()); - Assert.AreEqual(4, (-value).DigitalRoot()); -#else - Assert.AreEqual(4U, value.DigitalRoot()); - Assert.AreEqual(4U, (-value).DigitalRoot()); -#endif + 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; @@ -45,10 +81,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; @@ -56,30 +92,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; @@ -88,10 +124,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; @@ -100,10 +136,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; @@ -113,11 +149,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; @@ -126,31 +162,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..7307589 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 +internal 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 17f60f4..7391cc5 100644 --- a/X10D.Tests/src/Math/UInt64Tests.cs +++ b/X10D.Tests/src/Math/UInt64Tests.cs @@ -1,47 +1,84 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Math; namespace X10D.Tests.Math; -[TestClass] -[CLSCompliant(false)] -public partial class UInt64Tests +[TestFixture] +internal partial class UInt64Tests { - [TestMethod] + [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() { const ulong value = 238; + 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. - -#if NET7_0_OR_GREATER - Assert.AreEqual(4, (-(long)value).DigitalRoot()); - Assert.AreEqual(4, value.DigitalRoot()); -#else - Assert.AreEqual(4U, (-(long)value).DigitalRoot()); - Assert.AreEqual(4U, value.DigitalRoot()); -#endif + 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; @@ -49,10 +86,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; @@ -60,30 +97,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; @@ -92,10 +129,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; @@ -104,10 +141,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; @@ -116,10 +153,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; @@ -128,32 +165,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..7dca5cf 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] -public class EndPointTests +[TestFixture] +internal 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..ab48f24 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] -public class IPAddressTests +[TestFixture] +internal 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..310a183 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] -public class Int16Tests +[TestFixture] +internal 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..50b8899 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] -public class Int32Tests +[TestFixture] +internal 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..a2150e1 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] -public class Int64Tests +[TestFixture] +internal 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..4a191b7 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] -public class ByteTests +[TestFixture] +internal 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..73a0025 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] -public class Int16Tests +[TestFixture] +internal 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..36b3c1d 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] -public class Int32Tests +[TestFixture] +internal 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..c4c7c7b 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] -public class Int64Tests +[TestFixture] +internal 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..ce33ad2 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] -public class QuaternionTests +[TestFixture] +internal 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..38b1716 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] -public class RandomTests +[TestFixture] +internal 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..72132bc 100644 --- a/X10D.Tests/src/Numerics/SByteTests.cs +++ b/X10D.Tests/src/Numerics/SByteTests.cs @@ -1,86 +1,85 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Numerics; namespace X10D.Tests.Numerics; -[TestClass] -[CLSCompliant(false)] -public class SByteTests +[TestFixture] +internal 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..585f479 100644 --- a/X10D.Tests/src/Numerics/UInt16Tests.cs +++ b/X10D.Tests/src/Numerics/UInt16Tests.cs @@ -1,88 +1,87 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Numerics; namespace X10D.Tests.Numerics; -[TestClass] -[CLSCompliant(false)] -public class UInt16Tests +[TestFixture] +internal 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..da77d5b 100644 --- a/X10D.Tests/src/Numerics/UInt32Tests.cs +++ b/X10D.Tests/src/Numerics/UInt32Tests.cs @@ -1,86 +1,85 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Numerics; namespace X10D.Tests.Numerics; -[TestClass] -[CLSCompliant(false)] -public class UInt32Tests +[TestFixture] +internal 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..d01bd39 100644 --- a/X10D.Tests/src/Numerics/UInt64Tests.cs +++ b/X10D.Tests/src/Numerics/UInt64Tests.cs @@ -1,86 +1,85 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Numerics; namespace X10D.Tests.Numerics; -[TestClass] -[CLSCompliant(false)] -public class UInt64Tests +[TestFixture] +internal 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..e18688e 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] -public class Vector2Tests +[TestFixture] +internal 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..23c1795 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] -public class Vector3Tests +[TestFixture] +internal 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..108fb47 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] -public class Vector4Tests +[TestFixture] +internal 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/Reactive/ProgressTests.cs b/X10D.Tests/src/Reactive/ProgressTests.cs new file mode 100644 index 0000000..e18ed39 --- /dev/null +++ b/X10D.Tests/src/Reactive/ProgressTests.cs @@ -0,0 +1,67 @@ +using NUnit.Framework; +using X10D.Reactive; + +namespace X10D.Tests.Reactive; + +[TestFixture] +internal 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.Tests/src/Reflection/MemberInfoTests.cs b/X10D.Tests/src/Reflection/MemberInfoTests.cs index 1774b36..bbb0952 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] -public class MemberInfoTests +[TestFixture] +internal 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, true)); + Assert.That(typeof(short).SelectFromCustomAttribute(predicate, true)); + Assert.That(typeof(int).SelectFromCustomAttribute(predicate, true)); + Assert.That(typeof(long).SelectFromCustomAttribute(predicate, true)); + }); } - [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..f474b97 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] -public class TypeTests +[TestFixture] +internal 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/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(); + } +} diff --git a/X10D.Tests/src/Text/CharSpanTests.cs b/X10D.Tests/src/Text/CharSpanTests.cs index fd32588..683f7c0 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] -public class CharSpanTests +[TestFixture] +internal 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..cf17cdf 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] -public class CharTests +[TestFixture] +internal 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..bbd114c 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] -public class CoreTests +[TestFixture] +internal 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..8e6ecd1 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] -public class EnumerableTests +[TestFixture] +internal 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..49c13e4 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] -public class RuneTests +[TestFixture] +internal 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..07e8849 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] -public class StringBuilderReaderTests +[TestFixture] +internal 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..336cafb 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] -public class StringTests +[TestFixture] +internal 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,352 @@ 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 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")); + 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")); + 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((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!)); + } + + [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 +399,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 +408,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 +451,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 +595,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 +897,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..7c3a3ed 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] -public class ByteTests +[TestFixture] +internal 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..f420cf0 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] -public class CharSpanTests +[TestFixture] +internal 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..bae376b 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] -public class DateOnlyTests +[TestFixture] +internal 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..095f988 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] -public class DateTimeOffsetTests +[TestFixture] +internal 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..7dd437c 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] -public class DateTimeTests +[TestFixture] +internal 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..f1a2b02 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] -public class DecimalTests +[TestFixture] +internal 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..093e466 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] -public class DoubleTests +[TestFixture] +internal 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..b2f7faf 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] -public class HalfTests +[TestFixture] +internal 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..f6c40ed 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] -public class Int16Tests +[TestFixture] +internal 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..f0c258b 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] -public class Int32Tests +[TestFixture] +internal 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..bf317e8 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] -public class Int64Tests +[TestFixture] +internal 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..7a7de18 100644 --- a/X10D.Tests/src/Time/SByteTests.cs +++ b/X10D.Tests/src/Time/SByteTests.cs @@ -1,86 +1,105 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Time; namespace X10D.Tests.Time; -[TestClass] -[CLSCompliant(false)] -public class SByteTests +[TestFixture] +internal 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..52fbe24 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] -public class SingleTests +[TestFixture] +internal 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..c74658e 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] -public class StringTests +[TestFixture] +internal 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..a5a3aef 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] -public class TimeSpanParserTests +[TestFixture] +internal 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..ca68da3 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] -public class TimeSpanTests +[TestFixture] +internal 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..d93f58a 100644 --- a/X10D.Tests/src/Time/UInt16Tests.cs +++ b/X10D.Tests/src/Time/UInt16Tests.cs @@ -1,75 +1,91 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Time; namespace X10D.Tests.Time; -[TestClass] -[CLSCompliant(false)] -public class UInt16Tests +[TestFixture] +internal 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..605110f 100644 --- a/X10D.Tests/src/Time/UInt32Tests.cs +++ b/X10D.Tests/src/Time/UInt32Tests.cs @@ -1,75 +1,91 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Time; namespace X10D.Tests.Time; -[TestClass] -[CLSCompliant(false)] -public class UInt32Tests +[TestFixture] +internal 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..dcd08cd 100644 --- a/X10D.Tests/src/Time/UInt64Tests.cs +++ b/X10D.Tests/src/Time/UInt64Tests.cs @@ -1,75 +1,91 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using NUnit.Framework; using X10D.Time; namespace X10D.Tests.Time; -[TestClass] -[CLSCompliant(false)] -public class UInt64Tests +[TestFixture] +internal 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)); + }); } } diff --git a/X10D.Unity.Tests/Assets/Tests/ComponentTests.cs b/X10D.Unity.Tests/Assets/Tests/ComponentTests.cs index c77f83e..126e435 100644 --- a/X10D.Unity.Tests/Assets/Tests/ComponentTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/ComponentTests.cs @@ -4,13 +4,14 @@ 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 GetComponentsInChildrenOnly_ShouldIgnoreParent() + [Test] + public void GetComponentsInChildrenOnly_ShouldIgnoreParent() { var parent = new GameObject(); var rigidbody = parent.AddComponent(); @@ -20,10 +21,11 @@ namespace X10D.Unity.Tests child.AddComponent(); Rigidbody[] components = rigidbody.GetComponentsInChildrenOnly(); - Assert.AreEqual(1, components.Length); - Assert.AreEqual(components[0].gameObject, child); + Assert.That(components, Has.Length.EqualTo(1)); + Assert.That(child, Is.EqualTo(components[0].gameObject)); - yield break; + Object.Destroy(parent); + Object.Destroy(child); } } } 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.Tests/Assets/Tests/Drawing/Color32Tests.cs b/X10D.Unity.Tests/Assets/Tests/Drawing/Color32Tests.cs index 3667c4a..eb2e7c2 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,128 +16,108 @@ 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; (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); - - yield break; + Assert.That(a, Is.EqualTo(255)); + Assert.That(r, Is.EqualTo(255)); + Assert.That(g, Is.EqualTo(255)); + Assert.That(b, Is.EqualTo(0)); } - [UnityTest] - public IEnumerator GetClosestConsoleColor_ShouldReturnClosestColor_GivenValidColor() + [Test] + public void GetClosestConsoleColor_ShouldReturnClosestColor_GivenValidColor() { // 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()); - - yield break; + 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)); } - [UnityTest] - public IEnumerator Inverted_ShouldReturnInvertedColor() + [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()); - - yield break; + 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)); } - [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; + Assert.That(actual, Is.EqualTo(expected)); } - [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; + Assert.That(actual, Is.EqualTo(expected)); } - [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; + Assert.That(actual, Is.EqualTo(expected)); } - [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; + Assert.That(White.WithA(0), Is.EqualTo(transparent)); + Assert.That(transparent.WithA(0), Is.EqualTo(transparent)); } - [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; + Assert.That(White.WithB(0), Is.EqualTo(Yellow)); + Assert.That(Yellow.WithB(0), Is.EqualTo(Yellow)); } - [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; + Assert.That(White.WithG(0), Is.EqualTo(Magenta)); + Assert.That(Magenta.WithG(0), Is.EqualTo(Magenta)); } - [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; + 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 78031d4..c9d9182 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,126 +16,106 @@ 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; (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); - - yield break; + 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)); } - [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()); - 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()); - - yield break; + 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)); } - [UnityTest] - public IEnumerator Inverted_ShouldReturnInvertedColor() + [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()); - - yield break; + 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)); } - [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; + Assert.That(actual, Is.EqualTo(expected)); } - [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; + Assert.That(actual, Is.EqualTo(expected)); } - [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; + Assert.That(actual, Is.EqualTo(expected)); } - [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; + Assert.That(White.WithA(0), Is.EqualTo(transparent)); + Assert.That(transparent.WithA(0), Is.EqualTo(transparent)); } - [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; + Assert.That(White.WithB(0), Is.EqualTo(Yellow)); + Assert.That(Yellow.WithB(0), Is.EqualTo(Yellow)); } - [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; + Assert.That(White.WithG(0), Is.EqualTo(Magenta)); + Assert.That(Magenta.WithG(0), Is.EqualTo(Magenta)); } - [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; + 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 83d70ea..13d0b36 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,17 +8,15 @@ 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()); var vector = point.ToUnityVector2(); - Assert.AreEqual(point.X, vector.x, 1e-6f); - Assert.AreEqual(point.Y, vector.y, 1e-6f); - - yield break; + 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 36b8554..ab8a428 100644 --- a/X10D.Unity.Tests/Assets/Tests/Drawing/PointTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/Drawing/PointTests.cs @@ -1,38 +1,32 @@ 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()); var vector = point.ToUnityVector2(); - Assert.AreEqual(point.X, vector.x); - Assert.AreEqual(point.Y, vector.y); - - yield break; + Assert.That(vector.x, Is.EqualTo(point.X)); + Assert.That(vector.y, Is.EqualTo(point.Y)); } - [UnityTest] - public IEnumerator ToUnityVector2Int_ShouldReturnVector_WithEquivalentMembers() + [Test] + public void ToUnityVector2Int_ShouldReturnVector_WithEquivalentMembers() { var random = new Random(); var point = new Point(random.Next(), random.Next()); var vector = point.ToUnityVector2Int(); - Assert.AreEqual(point.X, vector.x); - Assert.AreEqual(point.Y, vector.y); - - yield break; + 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 33c69e9..5f4e842 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,76 +10,68 @@ 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(); - 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); - yield break; + 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)); } - [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; + Assert.That(random.NextColor32Argb(), Is.EqualTo(new Color32(21, 21, 229, 51))); } - [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(); - 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); - yield break; + 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)); } - [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; + Assert.That(random.NextColor32Rgb(), Is.EqualTo(new Color32(21, 21, 229, 255))); } - [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..2e5f759 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,34 +7,30 @@ 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()); 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); - - yield break; + 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)); } - [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()); 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); - - yield break; + 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 eb5a94d..9cc688e 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,19 +8,17 @@ 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()); 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); - - yield break; + 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 32676c4..fdcbaf6 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,19 +8,17 @@ 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()); 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); - - yield break; + 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 632e5d6..3f0f051 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,34 +7,30 @@ 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()); 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); - - yield break; + 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)); } - [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()); 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); - - yield break; + 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 e677867..6d871d6 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,17 +8,15 @@ 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()); var vector = size.ToUnityVector2(); - Assert.AreEqual(size.Width, vector.x, 1e-6f); - Assert.AreEqual(size.Height, vector.y, 1e-6f); - - yield break; + 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 0832375..c9619c9 100644 --- a/X10D.Unity.Tests/Assets/Tests/Drawing/SizeTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/Drawing/SizeTests.cs @@ -1,38 +1,32 @@ 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()); var vector = size.ToUnityVector2(); - Assert.AreEqual(size.Width, vector.x); - Assert.AreEqual(size.Height, vector.y); - - yield break; + Assert.That(vector.x, Is.EqualTo(size.Width)); + Assert.That(vector.y, Is.EqualTo(size.Height)); } - [UnityTest] - public IEnumerator ToUnityVector2Int_ShouldReturnVector_WithEquivalentMembers() + [Test] + public void ToUnityVector2Int_ShouldReturnVector_WithEquivalentMembers() { var random = new Random(); var size = new Size(random.Next(), random.Next()); var vector = size.ToUnityVector2Int(); - Assert.AreEqual(size.Width, vector.x); - Assert.AreEqual(size.Height, vector.y); - - yield break; + 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..565d455 100644 --- a/X10D.Unity.Tests/Assets/Tests/GameObjectTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/GameObjectTests.cs @@ -1,16 +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(); @@ -20,49 +20,52 @@ namespace X10D.Unity.Tests child.AddComponent(); Rigidbody[] components = parent.GetComponentsInChildrenOnly(); - Assert.AreEqual(1, components.Length); - Assert.AreEqual(components[0].gameObject, child); + Assert.That(components, Has.Length.EqualTo(1)); + Assert.That(child, Is.EqualTo(components[0].gameObject)); - yield break; + Object.Destroy(parent); + Object.Destroy(child); } - [UnityTest] - public IEnumerator LookAt_ShouldRotateSameAsTransform() + [Test] + [SuppressMessage("ReSharper", "Unity.InefficientPropertyAccess", Justification = "False positive.")] + 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}}; 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; + Object.Destroy(first); + Object.Destroy(second); } - [UnityTest] - public IEnumerator SetLayerRecursively_ShouldSetLayerRecursively() + [Test] + public void SetLayerRecursively_ShouldSetLayerRecursively() { var parent = new GameObject(); var child = new GameObject(); @@ -78,32 +81,36 @@ 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; + Object.Destroy(parent); + Object.Destroy(child); + Object.Destroy(grandChild); } - [UnityTest] - public IEnumerator SetParent_ShouldSetParent() + [Test] + [SuppressMessage("ReSharper", "Unity.InefficientPropertyAccess", Justification = "False positive.")] + 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}}; - 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; + Object.Destroy(first); + Object.Destroy(second); } } } diff --git a/X10D.Unity.Tests/Assets/Tests/Numerics/QuaternionTests.cs b/X10D.Unity.Tests/Assets/Tests/Numerics/QuaternionTests.cs index a486a75..c5ec037 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(); @@ -22,16 +20,14 @@ 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); - - yield break; + 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)); } - [UnityTest] - public IEnumerator ToUnityQuaternion_ShouldReturnQuaternion_WithEqualComponents() + [Test] + public void ToUnityQuaternion_ShouldReturnQuaternion_WithEqualComponents() { var random = new Random(); float x = random.NextSingle(); @@ -42,12 +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); - - yield break; + 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 4d768c2..d93744a 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; + Assert.That(vector.magnitude, Is.EqualTo(1).Within(1e-6)); } - [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; + Assert.That(vector.magnitude, Is.EqualTo(1).Within(1e-6)); } - [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..6ef0909 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; + Assert.That(x, Is.EqualTo(1)); + Assert.That(y, Is.EqualTo(2)); } - [UnityTest] - public IEnumerator ToSystemPoint_ShouldReturnPoint_WithEquivalentMembers() + [Test] + public void ToSystemPoint_ShouldReturnPoint_WithEquivalentMembers() { var random = new Random(); int x = random.Next(); @@ -31,14 +27,12 @@ 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); - - yield break; + Assert.That(point.X, Is.EqualTo(vector.x)); + Assert.That(point.Y, Is.EqualTo(vector.y)); } - [UnityTest] - public IEnumerator ToSystemSize_ShouldReturnSize_WithEquivalentMembers() + [Test] + public void ToSystemSize_ShouldReturnSize_WithEquivalentMembers() { var random = new Random(); int x = random.Next(); @@ -47,42 +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); - - yield break; + Assert.That(point.Width, Is.EqualTo(vector.x)); + Assert.That(point.Height, Is.EqualTo(vector.y)); } - [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)); - 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)); - - yield break; + 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)); } - [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)); - 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)); - - yield break; + 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 3be36d0..d6e5e0c 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; + Assert.That(x, Is.EqualTo(1)); + Assert.That(y, Is.EqualTo(2)); } - [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; + Assert.That(rounded.x, Is.EqualTo(2)); + Assert.That(rounded.y, Is.EqualTo(3)); } - [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; + Assert.That(rounded.x, Is.EqualTo(0)); + Assert.That(rounded.y, Is.EqualTo(30)); } - [UnityTest] - public IEnumerator ToSystemPointF_ShouldReturnPoint_WithEquivalentMembers() + [Test] + public void ToSystemPointF_ShouldReturnPoint_WithEquivalentMembers() { var random = new Random(); float x = random.NextSingle(); @@ -56,14 +48,12 @@ 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); - - yield break; + Assert.That(point.X, Is.EqualTo(vector.x).Within(1e-6f)); + Assert.That(point.Y, Is.EqualTo(vector.y).Within(1e-6f)); } - [UnityTest] - public IEnumerator ToSystemSizeF_ShouldReturnSize_WithEquivalentMembers() + [Test] + public void ToSystemSizeF_ShouldReturnSize_WithEquivalentMembers() { var random = new Random(); float x = random.NextSingle(); @@ -72,14 +62,12 @@ 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); - - yield break; + Assert.That(point.Width, Is.EqualTo(vector.x).Within(1e-6f)); + Assert.That(point.Height, Is.EqualTo(vector.y).Within(1e-6f)); } - [UnityTest] - public IEnumerator ToSystemVector_ShouldReturnVector_WithEqualComponents() + [Test] + public void ToSystemVector_ShouldReturnVector_WithEqualComponents() { var random = new Random(); float x = random.NextSingle(); @@ -88,15 +76,13 @@ 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); - - yield break; + 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)); } - [UnityTest] - public IEnumerator ToUnityVector_ShouldReturnVector_WithEqualComponents() + [Test] + public void ToUnityVector_ShouldReturnVector_WithEqualComponents() { var random = new Random(); float x = random.NextSingle(); @@ -105,43 +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); - - yield break; + 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)); } - [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)); - 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)); - - yield break; + 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)); } - [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)); - 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)); - - yield break; + 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 21bf438..acfac84 100644 --- a/X10D.Unity.Tests/Assets/Tests/Numerics/Vector3IntTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/Numerics/Vector3IntTests.cs @@ -1,78 +1,69 @@ -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; - Assert.AreEqual(1, x); - Assert.AreEqual(2, y); - Assert.AreEqual(3, z); - - yield break; + Assert.That(x, Is.EqualTo(1)); + Assert.That(y, Is.EqualTo(2)); + Assert.That(z, Is.EqualTo(3)); } - [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)); - 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)); - - yield break; + 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))); } - [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)); - 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)); - - yield break; + 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))); + ; } - [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)); - 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)); - - yield break; + 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 08ebed9..9d7d64a 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,47 +8,41 @@ 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; - Assert.AreEqual(1, x); - Assert.AreEqual(2, y); - Assert.AreEqual(3, z); - - yield break; + Assert.That(x, Is.EqualTo(1)); + Assert.That(y, Is.EqualTo(2)); + Assert.That(z, Is.EqualTo(3)); } - [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(); - Assert.AreEqual(2, rounded.x); - Assert.AreEqual(3, rounded.y); - Assert.AreEqual(-5, rounded.z); - - yield break; + Assert.That(rounded.x, Is.EqualTo(2)); + Assert.That(rounded.y, Is.EqualTo(3)); + Assert.That(rounded.z, Is.EqualTo(-5)); } - [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); - Assert.AreEqual(0, rounded.x); - Assert.AreEqual(30, rounded.y); - Assert.AreEqual(-10, rounded.z); - - yield break; + Assert.That(rounded.x, Is.EqualTo(0)); + Assert.That(rounded.y, Is.EqualTo(30)); + Assert.That(rounded.z, Is.EqualTo(-10)); } - [UnityTest] - public IEnumerator ToSystemVector_ShouldReturnVector_WithEqualComponents() + [Test] + public void ToSystemVector_ShouldReturnVector_WithEqualComponents() { var random = new Random(); float x = random.NextSingle(); @@ -60,16 +52,14 @@ 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); - - yield break; + 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)); } - [UnityTest] - public IEnumerator ToUnityVector_ShouldReturnVector_WithEqualComponents() + [Test] + public void ToUnityVector_ShouldReturnVector_WithEqualComponents() { var random = new Random(); float x = random.NextSingle(); @@ -79,66 +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); - - yield break; + 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)); } - [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)); - 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)); - - yield break; + 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))); } - [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)); - 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)); - - yield break; + 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))); } - [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)); - 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)); - - yield break; + 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 b943406..3848db7 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,50 +8,44 @@ 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; - Assert.AreEqual(1, x); - Assert.AreEqual(2, y); - Assert.AreEqual(3, z); - Assert.AreEqual(4, w); - - yield break; + Assert.That(x, Is.EqualTo(1)); + Assert.That(y, Is.EqualTo(2)); + Assert.That(z, Is.EqualTo(3)); + Assert.That(w, Is.EqualTo(4)); } - [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(); - Assert.AreEqual(2, rounded.x); - Assert.AreEqual(3, rounded.y); - Assert.AreEqual(-5, rounded.z); - Assert.AreEqual(0, rounded.w); - - yield break; + 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)); } - [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); - Assert.AreEqual(0, rounded.x); - Assert.AreEqual(30, rounded.y); - Assert.AreEqual(-10, rounded.z); - Assert.AreEqual(100, rounded.w); - - yield break; + 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)); } - [UnityTest] - public IEnumerator ToSystemVector_ShouldReturnVector_WithEqualComponents() + [Test] + public void ToSystemVector_ShouldReturnVector_WithEqualComponents() { var random = new Random(); float x = random.NextSingle(); @@ -64,17 +56,15 @@ 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); - - yield break; + 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)); } - [UnityTest] - public IEnumerator ToUnityVector_ShouldReturnVector_WithEqualComponents() + [Test] + public void ToUnityVector_ShouldReturnVector_WithEqualComponents() { var random = new Random(); float x = random.NextSingle(); @@ -85,93 +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); - - yield break; + 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)); } - [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)); - 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)); - - yield break; + 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))); } - [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)); - 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)); - - yield break; + 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))); } - [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)); - 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)); - - yield break; + 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))); } - [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)); - 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)); - - yield break; + 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 9bf7a24..9e77e11 100644 --- a/X10D.Unity.Tests/Assets/Tests/SingletonTests.cs +++ b/X10D.Unity.Tests/Assets/Tests/SingletonTests.cs @@ -7,38 +7,36 @@ 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.IsTrue(instance.Flag); - - yield break; + Assert.That(instance, Is.Not.Null); + Assert.That(instance.Flag); } - [UnityTest] - public IEnumerator Singleton_ShouldReturnSameInstance_WhenAccessedTwice() + [Test] + public void Singleton_ShouldReturnSameInstance_WhenAccessedTwice() { TestBehaviour instance = Singleton.Instance; - Assert.IsTrue(instance); - Assert.AreEqual(instance, Singleton.Instance); - - yield break; + Assert.That(instance, Is.Not.Null); + Assert.That(Singleton.Instance, Is.EqualTo(instance)); } [UnityTest] public IEnumerator Singleton_ShouldReturnNewInstance_WhenDestroyed() { TestBehaviour instance = Singleton.Instance; - Assert.IsTrue(instance); + Assert.That(instance, Is.Not.Null); Object.Destroy(instance); + yield return null; + Assert.IsFalse(instance); // 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 14893d0..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-2) - { - 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}"); } } } 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) diff --git a/X10D.Unity/README.md b/X10D.Unity/README.md index f0e6d4c..105de43 100644 --- a/X10D.Unity/README.md +++ b/X10D.Unity/README.md @@ -1,4 +1,4 @@ -

+

GitHub Workflow Status @@ -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.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 diff --git a/X10D.Unity/X10D.Unity.csproj b/X10D.Unity/X10D.Unity.csproj index f99bf2e..e1ac766 100644 --- a/X10D.Unity/X10D.Unity.csproj +++ b/X10D.Unity/X10D.Unity.csproj @@ -2,49 +2,7 @@ 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 + $(NoWarn);NU1701 @@ -56,18 +14,18 @@ - - True - - - - True - - - - True - - + + ResXFileCodeGenerator + ExceptionMessages.Designer.cs + + + + + + True + True + ExceptionMessages.resx + 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/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); + } + } } 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); 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/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/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..559ee39 100644 --- a/X10D.Unity/src/GameObjectExtensions.cs +++ b/X10D.Unity/src/GameObjectExtensions.cs @@ -13,8 +13,15 @@ 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()); for (var index = 0; index < components.Count; index++) @@ -26,7 +33,7 @@ public static class GameObjectExtensions continue; } - if (childComponent.transform.parent != gameObject.transform) + if (childComponent.transform == rootTransform) { components.RemoveAt(index); index--; 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; /// 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); + } +} diff --git a/X10D.sln b/X10D.sln index 6f8cb0c..d552642 100644 --- a/X10D.sln +++ b/X10D.sln @@ -16,15 +16,14 @@ 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}" 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}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "X10D.DSharpPlus", "X10D.DSharpPlus\X10D.DSharpPlus.csproj", "{675D3B25-7EA0-4FC3-B513-8DF27874F2CF}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SourceGenerator", "tools\SourceGenerator\SourceGenerator.csproj", "{077A5D33-AD55-4C55-8A67-972CEBC32C7A}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "X10D.Hosting", "X10D.Hosting\X10D.Hosting.csproj", "{B04AF429-30CF-4B69-81BA-38F560CA9126}" EndProject @@ -44,6 +43,13 @@ 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 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "X10D.MetaServices", "tools\X10D.MetaServices\X10D.MetaServices.csproj", "{F57376C4-3591-43AF-BBED-447A1DE2B1FE}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -71,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 @@ -83,6 +85,14 @@ 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 + {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 @@ -93,5 +103,8 @@ 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} + {077A5D33-AD55-4C55-8A67-972CEBC32C7A} = {4B8969E6-27D2-4357-964E-9979FF7CC805} + {F57376C4-3591-43AF-BBED-447A1DE2B1FE} = {4B8969E6-27D2-4357-964E-9979FF7CC805} EndGlobalSection EndGlobal diff --git a/X10D/X10D.csproj b/X10D/X10D.csproj index 14eb676..c288f87 100644 --- a/X10D/X10D.csproj +++ b/X10D/X10D.csproj @@ -1,72 +1,5 @@ - - 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 @@ -83,7 +16,8 @@ - + + 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 493088b..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,10 +46,11 @@ 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); + // 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)) @@ -95,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)); @@ -108,7 +101,6 @@ public static class DictionaryExtensions { throw new ArgumentNullException(nameof(updateValueFactory)); } -#endif if (dictionary.TryGetValue(key, out TValue? old)) { @@ -150,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)); @@ -169,10 +156,11 @@ 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); + // 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)) @@ -218,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)); @@ -237,7 +220,6 @@ public static class DictionaryExtensions { throw new ArgumentNullException(nameof(updateValueFactory)); } -#endif if (dictionary.TryGetValue(key, out TValue? old)) { @@ -287,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)); @@ -306,10 +283,11 @@ 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); + // 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)) @@ -361,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)); @@ -380,7 +353,6 @@ public static class DictionaryExtensions { throw new ArgumentNullException(nameof(updateValueFactory)); } -#endif if (dictionary.TryGetValue(key, out TValue? old)) { @@ -408,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) { @@ -455,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)); @@ -468,7 +432,6 @@ public static class DictionaryExtensions { throw new ArgumentNullException(nameof(selector)); } -#endif static string SanitizeValue(string? value) { @@ -514,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)); @@ -533,7 +491,6 @@ public static class DictionaryExtensions { throw new ArgumentNullException(nameof(valueSelector)); } -#endif static string SanitizeValue(string? value) { @@ -565,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) { @@ -604,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)); @@ -617,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) @@ -655,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)); @@ -674,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 78707e1..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); @@ -349,14 +302,12 @@ 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) { -#if NET6_0_OR_GREATER - ArgumentNullException.ThrowIfNull(source); - ArgumentNullException.ThrowIfNull(predicate); -#else if (source is null) { throw new ArgumentNullException(nameof(source)); @@ -366,7 +317,6 @@ public static class EnumerableExtensions { throw new ArgumentNullException(nameof(predicate)); } -#endif return source.Where(item => !predicate(item)); } @@ -381,16 +331,13 @@ 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 - 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/Collections/SpanExtensions.cs b/X10D/src/Collections/SpanExtensions.cs index 78d6c8b..ac2fd2b 100644 --- a/X10D/src/Collections/SpanExtensions.cs +++ b/X10D/src/Collections/SpanExtensions.cs @@ -53,6 +53,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. /// 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/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 { 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/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..5b82682 --- /dev/null +++ b/X10D/src/IO/DecimalExtensions.cs @@ -0,0 +1,118 @@ +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); + 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..]); + + var low = (uint)lo; + var mid = (uint)(lo >> 32); + + destination[0] = (int)low; + destination[1] = (int)mid; + destination[2] = hi; + destination[3] = flags; + } +} 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/DoubleExtensions.cs b/X10D/src/IO/DoubleExtensions.cs index f71e4be..c42a7ef 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 tmp); } return MemoryMarshal.TryWrite(destination, ref value); +#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/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/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/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/SingleExtensions.cs b/X10D/src/IO/SingleExtensions.cs index 5db19f5..539e919 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 tmp); } return MemoryMarshal.TryWrite(destination, ref value); +#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.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 c55b784..15e50e0 100644 --- a/X10D/src/IO/StreamExtensions.cs +++ b/X10D/src/IO/StreamExtensions.cs @@ -1,7 +1,4 @@ -using System.Buffers.Binary; -using System.Diagnostics.CodeAnalysis; -using System.Reflection; -using System.Runtime.InteropServices; +using System.Reflection; using System.Security.Cryptography; namespace X10D.IO; @@ -9,11 +6,8 @@ namespace X10D.IO; /// /// IO-related extension methods for . /// -public static class StreamExtensions +public static partial 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. /// @@ -33,14 +27,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) { @@ -53,534 +43,18 @@ 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); } - /// - /// 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. - /// - /// 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) - { -#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)) - { - 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); - } - - const int decimalSize = sizeof(decimal); - const int int32Size = sizeof(int); - const int partitionSize = decimalSize / int32Size; - - var bits = new int[partitionSize]; - for (var index = 0; index < partitionSize; index++) - { - bits[index] = stream.ReadInt32(endianness); - } - - if (endianness != DefaultEndianness) - { - Array.Reverse(bits); - } - - return new decimal(bits); - } - - /// - /// 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. - /// - /// 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) - { -#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)) - { - 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); - - var value = MemoryMarshal.Read(buffer); - - if (BitConverter.IsLittleEndian == (endianness == Endianness.BigEndian)) - { - long tmp = BinaryPrimitives.ReverseEndianness(BitConverter.DoubleToInt64Bits(value)); - value = BitConverter.Int64BitsToDouble(tmp); - } - - return value; - } - - /// - /// 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. - /// - /// 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) - { -#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)) - { - 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); - - return endianness == Endianness.LittleEndian - ? BinaryPrimitives.ReadInt16LittleEndian(buffer) - : BinaryPrimitives.ReadInt16BigEndian(buffer); - } - - /// - /// 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. - /// - /// 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) - { -#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)) - { - 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); - - return endianness == Endianness.LittleEndian - ? BinaryPrimitives.ReadInt32LittleEndian(buffer) - : BinaryPrimitives.ReadInt32BigEndian(buffer); - } - - /// - /// 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. - /// - /// 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) - { -#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)) - { - 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); - } - - /// - /// 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. - /// - /// 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) - { -#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)) - { - 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(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; - } - - /// - /// 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. - /// - /// The stream from which the value should be read. - /// An two-byte unsigned integer read from the stream. - [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) - { -#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)) - { - 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); - - return endianness == Endianness.LittleEndian - ? BinaryPrimitives.ReadUInt16LittleEndian(buffer) - : BinaryPrimitives.ReadUInt16BigEndian(buffer); - } - - /// - /// 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. - /// - /// The stream from which the value should be read. - /// An four-byte unsigned integer read from the stream. - [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) - { -#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)) - { - 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); - - return endianness == Endianness.LittleEndian - ? BinaryPrimitives.ReadUInt32LittleEndian(buffer) - : BinaryPrimitives.ReadUInt32BigEndian(buffer); - } - - /// - /// 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. - /// - /// The stream from which the value should be read. - /// An eight-byte unsigned integer read from the stream. - [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) - { -#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)) - { - 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(ulong)]; - stream.Read(buffer); - - return endianness == Endianness.LittleEndian - ? BinaryPrimitives.ReadUInt64LittleEndian(buffer) - : BinaryPrimitives.ReadUInt64BigEndian(buffer); - } - /// /// Returns the hash of the current stream as an array of bytes using the specified hash algorithm. /// @@ -607,14 +81,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) { @@ -627,15 +97,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) @@ -647,624 +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 two-byte signed 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 signed integer to write. - /// The number of bytes written to the stream. - [ExcludeFromCodeCoverage] - public static int Write(this Stream stream, short value) - { - return stream.Write(value, DefaultEndianness); - } - - /// - /// Writes a two-byte signed 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 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 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)) - { - 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 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)) - { - 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 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)) - { - 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 . - [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) - { -#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)) - { - 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); - } - - 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. - /// - /// The stream to which the value should be written. - /// The four-byte unsigned integer to write. - /// The number of bytes written to the stream. - /// is . - [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) - { -#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)) - { - 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); - } - - 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 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)) - { - 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 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)) - { - 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 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)) - { - 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 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)) - { - 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; - stream.Write(value); - return (int)(stream.Position - preWritePosition); - } } 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 new file mode 100644 index 0000000..1317846 --- /dev/null +++ b/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.Double.cs @@ -0,0 +1,71 @@ +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 (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + + 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 (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + + 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 (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + + 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 new file mode 100644 index 0000000..9640a6a --- /dev/null +++ b/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.Int32.cs @@ -0,0 +1,71 @@ +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 (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + + 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 (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + + 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 (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + + 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..8ca5855 --- /dev/null +++ b/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.Int64.cs @@ -0,0 +1,73 @@ +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 (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + + 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 (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + + 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 (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + + 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..9194c62 --- /dev/null +++ b/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.Single.cs @@ -0,0 +1,71 @@ +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 (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + + 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 (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + + 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 (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + + 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..b812afb --- /dev/null +++ b/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.UInt32.cs @@ -0,0 +1,76 @@ +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 (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + + 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 (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + + 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 (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + + 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..7b55571 --- /dev/null +++ b/X10D/src/IO/TextWriterExtensions.WriteLineNoAlloc.UInt64.cs @@ -0,0 +1,76 @@ +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 (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + + 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 (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + + 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 (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + + 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..a8d5bbb --- /dev/null +++ b/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.Double.cs @@ -0,0 +1,79 @@ +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 (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + + 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 (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + + 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 (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + + 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.Int32.cs b/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.Int32.cs new file mode 100644 index 0000000..2018363 --- /dev/null +++ b/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.Int32.cs @@ -0,0 +1,80 @@ +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 (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + + 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 (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + + 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 (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + + 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..c0cb32f --- /dev/null +++ b/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.Int64.cs @@ -0,0 +1,83 @@ +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 (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + + 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 (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + + 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 (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + + 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.Single.cs b/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.Single.cs new file mode 100644 index 0000000..b48a415 --- /dev/null +++ b/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.Single.cs @@ -0,0 +1,79 @@ +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 (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + + 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 (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + + 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 (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + + 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.UInt32.cs b/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.UInt32.cs new file mode 100644 index 0000000..b38fa0a --- /dev/null +++ b/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.UInt32.cs @@ -0,0 +1,86 @@ +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 (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + + 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 (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + + 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 (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + + 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..d9a48f4 --- /dev/null +++ b/X10D/src/IO/TextWriterExtensions.WriteNoAlloc.UInt64.cs @@ -0,0 +1,86 @@ +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 (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + + 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 (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + + 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 (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + + 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 new file mode 100644 index 0000000..f590205 --- /dev/null +++ b/X10D/src/IO/TextWriterExtensions.cs @@ -0,0 +1,8 @@ +namespace X10D.IO; + +/// +/// IO-related extension methods for . +/// +public static partial class TextWriterExtensions +{ +} 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); } } 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 4362dd2..39d4002 100644 --- a/X10D/src/Linq/EnumerableExtensions.cs +++ b/X10D/src/Linq/EnumerableExtensions.cs @@ -10,33 +10,24 @@ namespace X10D.Linq; public static class EnumerableExtensions { /// - /// Concatenates a single value to the end of a sequence. + /// Filters a sequence of values by omitting elements that match a specified value. /// - /// The source sequence. - /// The value to concatenate to the end of the source sequence. - /// The type of the elements in . + /// An to filter. + /// The value to omit. + /// The type of the elements of . /// - /// An that contains the concatenated elements of the input sequence, and the specified + /// An that contains elements from the input sequence that do not match the specified /// value. /// /// is . - public static IEnumerable ConcatOne(this IEnumerable source, TSource value) + 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 - foreach (TSource item in source) - { - yield return item; - } - - yield return value; + return source.Where(i => !Equals(i, item)); } /// @@ -49,14 +40,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); } @@ -72,14 +59,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; @@ -135,10 +118,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)); @@ -148,7 +127,6 @@ public static class EnumerableExtensions { throw new ArgumentNullException(nameof(selector)); } -#endif return MinMax(source, selector, Comparer.Default); } @@ -169,10 +147,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)); @@ -182,7 +156,6 @@ public static class EnumerableExtensions { throw new ArgumentNullException(nameof(selector)); } -#endif comparer ??= Comparer.Default; @@ -238,10 +211,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)); @@ -251,7 +220,6 @@ public static class EnumerableExtensions { throw new ArgumentNullException(nameof(keySelector)); } -#endif return MinMaxBy(source, keySelector, Comparer.Default); } @@ -271,10 +239,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)); @@ -284,7 +248,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/BigIntegerExtensions.cs b/X10D/src/Math/BigIntegerExtensions.cs index ead10ca..71320e1 100644 --- a/X10D/src/Math/BigIntegerExtensions.cs +++ b/X10D/src/Math/BigIntegerExtensions.cs @@ -11,6 +11,21 @@ namespace X10D.Math; public static class BigIntegerExtensions { #if !NET7_0_OR_GREATER + /// + /// 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 0d4ea56..60f59bd 100644 --- a/X10D/src/Math/ByteExtensions.cs +++ b/X10D/src/Math/ByteExtensions.cs @@ -10,6 +10,21 @@ namespace X10D.Math; public static class ByteExtensions { #if !NET7_0_OR_GREATER + /// + /// 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/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/Math/Int16Extensions.cs b/X10D/src/Math/Int16Extensions.cs index e4e57ca..ce6c468 100644 --- a/X10D/src/Math/Int16Extensions.cs +++ b/X10D/src/Math/Int16Extensions.cs @@ -10,6 +10,21 @@ namespace X10D.Math; public static class Int16Extensions { #if !NET7_0_OR_GREATER + /// + /// 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 71df5a3..19fd47a 100644 --- a/X10D/src/Math/Int32Extensions.cs +++ b/X10D/src/Math/Int32Extensions.cs @@ -10,6 +10,21 @@ namespace X10D.Math; public static class Int32Extensions { #if !NET7_0_OR_GREATER + /// + /// 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 85405fc..4fd3ab4 100644 --- a/X10D/src/Math/Int64Extensions.cs +++ b/X10D/src/Math/Int64Extensions.cs @@ -10,6 +10,21 @@ namespace X10D.Math; public static class Int64Extensions { #if !NET7_0_OR_GREATER + /// + /// 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 81b827a..45d75b9 100644 --- a/X10D/src/Math/SByteExtensions.cs +++ b/X10D/src/Math/SByteExtensions.cs @@ -11,6 +11,21 @@ namespace X10D.Math; public static class SByteExtensions { #if !NET7_0_OR_GREATER + /// + /// 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 95f60e6..77006dc 100644 --- a/X10D/src/Math/UInt16Extensions.cs +++ b/X10D/src/Math/UInt16Extensions.cs @@ -11,6 +11,21 @@ namespace X10D.Math; public static class UInt16Extensions { #if !NET7_0_OR_GREATER + /// + /// 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 5661274..9eb91b1 100644 --- a/X10D/src/Math/UInt32Extensions.cs +++ b/X10D/src/Math/UInt32Extensions.cs @@ -11,6 +11,21 @@ namespace X10D.Math; public static class UInt32Extensions { #if !NET7_0_OR_GREATER + /// + /// 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 64cb2ce..7088f84 100644 --- a/X10D/src/Math/UInt64Extensions.cs +++ b/X10D/src/Math/UInt64Extensions.cs @@ -11,6 +11,21 @@ namespace X10D.Math; public static class UInt64Extensions { #if !NET7_0_OR_GREATER + /// + /// 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. /// 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 new file mode 100644 index 0000000..b935112 --- /dev/null +++ b/X10D/src/Reactive/ObservableDisposer.cs @@ -0,0 +1,33 @@ +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) + { + _observers = observers ?? throw new ArgumentNullException(nameof(observers)); + _observer = observer ?? throw new ArgumentNullException(nameof(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..2eecdd8 --- /dev/null +++ b/X10D/src/Reactive/ProgressExtensions.cs @@ -0,0 +1,89 @@ +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 (progress is null) + { + throw new ArgumentNullException(nameof(progress)); + } + + 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 (progress is null) + { + throw new ArgumentNullException(nameof(progress)); + } + + 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..32a0870 --- /dev/null +++ b/X10D/src/Reactive/ProgressObservable.cs @@ -0,0 +1,36 @@ +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 (observer is null) + { + throw new ArgumentNullException(nameof(observer)); + } + + _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..16183f9 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,11 +121,218 @@ public static class StringExtensions { throw new ArgumentNullException(nameof(destinationEncoding)); } -#endif 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 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 . + /// + /// The current string. + /// 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) + { + 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 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 . + /// + /// 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. + /// + /// 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; + } + + /// + /// 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. /// @@ -179,14 +373,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 +401,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 +560,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 +619,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 +628,6 @@ public static class StringExtensions { throw new ArgumentNullException(nameof(encoding)); } -#endif return encoding.GetBytes(value); } @@ -464,14 +641,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 +661,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 +681,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 +764,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 +834,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 +885,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 +918,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 +959,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 +997,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 +1031,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 +1057,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 +1089,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 +1118,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 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/docfx.json b/docfx_project/docfx.json index 304c063..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" ] } @@ -51,7 +52,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" 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. diff --git a/tools/Benchmarks/Benchmarks.csproj b/tools/Benchmarks/Benchmarks.csproj new file mode 100644 index 0000000..fb326bc --- /dev/null +++ b/tools/Benchmarks/Benchmarks.csproj @@ -0,0 +1,18 @@ + + + + Release + Exe + net7.0;net6.0;netcoreapp3.1 + 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()); diff --git a/tools/Directory.Build.props b/tools/Directory.Build.props new file mode 100644 index 0000000..39e3440 --- /dev/null +++ b/tools/Directory.Build.props @@ -0,0 +1,14 @@ + + + 11.0 + enable + true + true + + + + + + + + \ No newline at end of file diff --git a/X10D.SourceGenerator/EmojiRegexGenerator.cs b/tools/SourceGenerator/EmojiRegexGenerator.cs similarity index 92% rename from X10D.SourceGenerator/EmojiRegexGenerator.cs rename to tools/SourceGenerator/EmojiRegexGenerator.cs index 2d67b1d..1ac9ca9 100644 --- a/X10D.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 @@ -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/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/X10D.SourceGenerator/X10D.SourceGenerator.csproj b/tools/SourceGenerator/SourceGenerator.csproj similarity index 69% rename from X10D.SourceGenerator/X10D.SourceGenerator.csproj rename to tools/SourceGenerator/SourceGenerator.csproj index e012f98..29d8a3c 100644 --- a/X10D.SourceGenerator/X10D.SourceGenerator.csproj +++ b/tools/SourceGenerator/SourceGenerator.csproj @@ -2,11 +2,6 @@ netstandard2.0 - 11.0 - enable - enable - true - true @@ -17,4 +12,8 @@ + + + + diff --git a/tools/SourceValidator/SourceValidator.csproj b/tools/SourceValidator/SourceValidator.csproj index 1d72f7d..5059923 100644 --- a/tools/SourceValidator/SourceValidator.csproj +++ b/tools/SourceValidator/SourceValidator.csproj @@ -3,11 +3,6 @@ Exe net7.0 - 11.0 - enable - enable - true - true diff --git a/tools/UpmPackageGenerator/UpmPackageGenerator.csproj b/tools/UpmPackageGenerator/UpmPackageGenerator.csproj index 277ab31..82cad6d 100644 --- a/tools/UpmPackageGenerator/UpmPackageGenerator.csproj +++ b/tools/UpmPackageGenerator/UpmPackageGenerator.csproj @@ -3,10 +3,6 @@ Exe net7.0 - enable - enable - true - true 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 new file mode 100644 index 0000000..382e63e --- /dev/null +++ b/tools/X10D.MetaServices/AutoOverloadAttribute.cs @@ -0,0 +1,6 @@ +namespace X10D.MetaServices; + +[AttributeUsage(AttributeTargets.Method, Inherited = false)] +internal sealed class AutoOverloadAttribute : Attribute +{ +} diff --git a/tools/X10D.MetaServices/OverloadTypeAttribute.cs b/tools/X10D.MetaServices/OverloadTypeAttribute.cs new file mode 100644 index 0000000..0fdde1a --- /dev/null +++ b/tools/X10D.MetaServices/OverloadTypeAttribute.cs @@ -0,0 +1,20 @@ +namespace X10D.MetaServices; + +[AttributeUsage(AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] +internal 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; } +} diff --git a/tools/X10D.MetaServices/X10D.MetaServices.csproj b/tools/X10D.MetaServices/X10D.MetaServices.csproj new file mode 100644 index 0000000..2756020 --- /dev/null +++ b/tools/X10D.MetaServices/X10D.MetaServices.csproj @@ -0,0 +1,7 @@ + + + + netstandard2.0 + + +