1
0
mirror of https://github.com/oliverbooth/X10D synced 2024-11-23 00:18:47 +00:00

Compare commits

..

No commits in common. "423fb90cc4cc64e1dade357c900147c3f33d9546" and "21271314af2c07748dd4c3600388d64b25127e3d" have entirely different histories.

329 changed files with 10866 additions and 13194 deletions

View File

@ -37,8 +37,6 @@ body:
label: Version label: Version
description: What version of the package are you running? description: What version of the package are you running?
options: options:
- Nightly / other
- 3.2.0
- 3.1.0 - 3.1.0
- 3.0.0 - 3.0.0
- 2.6.0 - 2.6.0
@ -49,12 +47,6 @@ body:
- 2.1.0 - 2.1.0
validations: validations:
required: true 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 - type: textarea
id: logs id: logs
attributes: attributes:

View File

@ -3,28 +3,19 @@ name: DocFX
on: on:
push: push:
branches: [ main ] branches: [ main ]
workflow_dispatch:
jobs: jobs:
docfx: docfx:
runs-on: ubuntu-latest runs-on: ubuntu-latest
name: Publish Documentation name: Publish Documentation
steps: steps:
- name: Checkout - uses: actions/checkout@v3
uses: actions/checkout@v3 - uses: nikeee/docfx-action@v1.0.0
name: Build Documentation
- 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: with:
args: docfx_project/docfx.json args: docfx_project/docfx.json
- uses: maxheld83/ghpages@master
- name: Publish documentation on GitHub Pages name: Publish Documentation on GitHub Pages
uses: maxheld83/ghpages@master
env: env:
BUILD_DIR: docfx_project/_site BUILD_DIR: docfx_project/_site
GH_PAT: ${{ secrets.GH_PAT }} GH_PAT: ${{ secrets.GH_PAT }}

View File

@ -3,12 +3,12 @@ name: .NET
on: on:
push: push:
branches: branches:
- '*' - main
- '*/*' - develop
pull_request: pull_request:
branches: branches:
- '*' - main
- '*/*' - develop
jobs: jobs:
build: build:

View File

@ -4,7 +4,6 @@ on:
push: push:
branches: branches:
- main - main
workflow_dispatch:
jobs: jobs:
nightly: nightly:
@ -33,6 +32,7 @@ jobs:
run: | run: |
mkdir build 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 --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.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 }} 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 }}

View File

@ -32,6 +32,7 @@ jobs:
run: | run: |
mkdir build 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 --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.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 }} 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 }}

View File

@ -32,6 +32,7 @@ jobs:
run: | run: |
mkdir build mkdir build
dotnet pack X10D --configuration Release --no-build -p:SymbolPackageFormat=snupkg --include-symbols --include-source -o 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.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 dotnet pack X10D.Unity --configuration Release --no-build -p:SymbolPackageFormat=snupkg --include-symbols --include-source -o build

View File

@ -3,7 +3,6 @@ on:
push: push:
branches: branches:
- main - main
workflow_dispatch:
pull_request: pull_request:
types: [opened, synchronize, reopened] types: [opened, synchronize, reopened]
jobs: jobs:

View File

@ -3,7 +3,8 @@ name: Source Validator
on: on:
push: push:
branches: branches:
- '*' - main
- develop
pull_request: pull_request:
types: [opened, synchronize, reopened] types: [opened, synchronize, reopened]

View File

@ -3,12 +3,12 @@ name: Unity Test Runner
on: on:
push: push:
branches: branches:
- '*' - main
- '*/*' - develop
pull_request: pull_request:
branches: branches:
- '*' - main
- '*/*' - develop
jobs: jobs:
build: build:

View File

@ -8,64 +8,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## 4.0.0 - [Unreleased] ## 4.0.0 - [Unreleased]
### Added ### Added
- X10D: Added extension methods for `DateOnly`, for parity with `DateTime` and `DateTimeOffset`. - X10D: Added extension methods for `DateOnly`, for parity with `DateTime` and `DateTimeOffset`.
- X10D: Added math-related extension methods for `BigInteger`. - X10D: Added math-related extension methods for `BigInteger`.
- X10D: Added `Span<T>.Replace(T, T)`.
- X10D: Added `CountDigits` for integer types.
- X10D: Added `IEnumerable<T>.Except(T)`.
- X10D: Added `Progress<T>.OnProgressChanged([T])`.
- X10D: Added `TextWriter.WriteNoAlloc(int[, ReadOnlySpan<char>[, IFormatProvider]])`.
- X10D: Added `TextWriter.WriteNoAlloc(uint[, ReadOnlySpan<char>[, IFormatProvider]])`.
- X10D: Added `TextWriter.WriteNoAlloc(long[, ReadOnlySpan<char>[, IFormatProvider]])`.
- X10D: Added `TextWriter.WriteNoAlloc(ulong[, ReadOnlySpan<char>[, IFormatProvider]])`.
- X10D: Added `TextWriter.WriteLineNoAlloc(int[, ReadOnlySpan<char>[, IFormatProvider]])`.
- X10D: Added `TextWriter.WriteLineNoAlloc(uint[, ReadOnlySpan<char>[, IFormatProvider]])`.
- X10D: Added `TextWriter.WriteLineNoAlloc(long[, ReadOnlySpan<char>[, IFormatProvider]])`.
- X10D: Added `TextWriter.WriteLineNoAlloc(ulong[, ReadOnlySpan<char>[, 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 ### 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<T>.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 ## [3.2.0] - 2023-04-03
@ -629,10 +576,7 @@ please [open an issue](https://github.com/oliverbooth/X10D/issues)!
Earlier versions of this package are undocumented and unlisted from package results. Earlier versions of this package are undocumented and unlisted from package results.
[unreleased]: https://github.com/oliverbooth/X10D/compare/v3.3.1...main [unreleased]: https://github.com/oliverbooth/X10D/compare/v3.2.0...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.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.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 [3.0.0]: https://github.com/oliverbooth/X10D/releases/tag/v3.0.0

View File

@ -9,10 +9,6 @@ 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 There is an `.editorconfig` included in this repository. For quick and painless pull requests, ensure that the analyzer does not
throw warnings. 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 ### Code style
Below are a few pointers to which you may refer, but keep in mind this is not an exhaustive list: Below are a few pointers to which you may refer, but keep in mind this is not an exhaustive list:

View File

@ -17,7 +17,7 @@ X10D (pronounced *extend*), is a .NET package that provides extension methods fo
## Installation ## Installation
### NuGet installation ### NuGet installation
```ps ```ps
Install-Package X10D -Version 4.0.0 Install-Package X10D -Version 3.2.0
``` ```
### Manual installation ### Manual installation

View File

@ -1,17 +1,11 @@
<Project> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFrameworks>net7.0;net6.0;netstandard2.1</TargetFrameworks> <TargetFrameworks>net7.0;net6.0;netstandard2.1</TargetFrameworks>
<LangVersion>11.0</LangVersion> <LangVersion>11.0</LangVersion>
<Optimize>true</Optimize> <Optimize>true</Optimize>
<ImplicitUsings>true</ImplicitUsings> <ImplicitUsings>true</ImplicitUsings>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<EnableNETAnalyzers>true</EnableNETAnalyzers>
<DebugType>pdbonly</DebugType>
<DebugSymbols>true</DebugSymbols>
<VersionPrefix>4.0.0</VersionPrefix>
<Authors>Oliver Booth</Authors> <Authors>Oliver Booth</Authors>
<Nullable>enable</Nullable>
<NeutralLanguage>en</NeutralLanguage> <NeutralLanguage>en</NeutralLanguage>
<RepositoryUrl>https://github.com/oliverbooth/X10D</RepositoryUrl> <RepositoryUrl>https://github.com/oliverbooth/X10D</RepositoryUrl>
<RepositoryType>git</RepositoryType> <RepositoryType>git</RepositoryType>
@ -20,9 +14,16 @@
<PackageIcon>branding_Icon.png</PackageIcon> <PackageIcon>branding_Icon.png</PackageIcon>
<PackageIconUrl/> <PackageIconUrl/>
<PackageTags>dotnet extension-methods</PackageTags> <PackageTags>dotnet extension-methods</PackageTags>
<PackageReadmeFile>README.md</PackageReadmeFile> <PackageReleaseNotes>$([System.IO.File]::ReadAllText("$(MSBuildProjectDirectory)/../CHANGELOG.md"))</PackageReleaseNotes>
<PackageReleaseNotes>$([System.IO.File]::ReadAllText("$(SolutionDir)/CHANGELOG.md"))</PackageReleaseNotes>
<CodeAnalysisTreatWarningsAsErrors>true</CodeAnalysisTreatWarningsAsErrors> <CodeAnalysisTreatWarningsAsErrors>true</CodeAnalysisTreatWarningsAsErrors>
<VersionPrefix>4.0.0</VersionPrefix>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<ExcludeFromCodeCoverage>true</ExcludeFromCodeCoverage>
<EnableNETAnalyzers>true</EnableNETAnalyzers>
<DebugType>pdbonly</DebugType>
<DebugSymbols>true</DebugSymbols>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(GITHUB_ACTIONS)' == 'true'"> <PropertyGroup Condition="'$(GITHUB_ACTIONS)' == 'true'">
@ -47,6 +48,10 @@
<FileVersion>$(VersionPrefix).0</FileVersion> <FileVersion>$(VersionPrefix).0</FileVersion>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="DSharpPlus" Version="4.3.0" PrivateAssets="All"/>
</ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="..\branding_Icon.png"> <None Include="..\branding_Icon.png">
<Pack>True</Pack> <Pack>True</Pack>
@ -56,13 +61,10 @@
<Pack>True</Pack> <Pack>True</Pack>
<PackagePath/> <PackagePath/>
</None> </None>
<None Include="..\README.md">
<Pack>True</Pack>
<PackagePath/>
</None>
<None Include="..\CHANGELOG.md"> <None Include="..\CHANGELOG.md">
<Pack>True</Pack> <Pack>True</Pack>
<PackagePath/> <PackagePath/>
</None> </None>
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -0,0 +1 @@
[assembly: CLSCompliant(false)]

View File

@ -0,0 +1,80 @@
using DSharpPlus;
using DSharpPlus.Entities;
namespace X10D.DSharpPlus;
/// <summary>
/// Extension methods for <see cref="DiscordChannel" />.
/// </summary>
public static class DiscordChannelExtensions
{
/// <summary>
/// Gets the category of this channel.
/// </summary>
/// <param name="channel">The channel whose category to retrieve.</param>
/// <returns>
/// The category of <paramref name="channel" />, or <paramref name="channel" /> itself if it is already a category;
/// <see langword="null" /> if this channel is not defined in a category.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="channel" /> is <see langword="null" />.</exception>
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;
}
}
/// <summary>
/// Normalizes a <see cref="DiscordChannel" /> so that the internal client is assured to be a specified value.
/// </summary>
/// <param name="channel">The <see cref="DiscordChannel" /> to normalize.</param>
/// <param name="client">The target client.</param>
/// <returns>
/// A <see cref="DiscordChannel" /> whose public values will match <paramref name="channel" />, but whose internal client
/// is <paramref name="client" />.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <para><paramref name="channel" /> is <see langword="null" /></para>
/// -or-
/// <para><paramref name="client" /> is <see langword="null" /></para>
/// </exception>
public static async Task<DiscordChannel> 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);
}
}

View File

@ -0,0 +1,79 @@
using DSharpPlus;
using DSharpPlus.Entities;
using DSharpPlus.Exceptions;
namespace X10D.DSharpPlus;
/// <summary>
/// Extension methods for <see cref="DiscordClient" />.
/// </summary>
public static class DiscordClientExtensions
{
/// <summary>
/// Instructs the client to automatically join all existing threads, and any newly-created threads.
/// </summary>
/// <param name="client">The <see cref="DiscordClient" /> whose events should be subscribed.</param>
/// <param name="rejoinIfRemoved">
/// <see langword="true" /> to automatically rejoin a thread if this client was removed; otherwise,
/// <see langword="false" />.
/// </param>
/// <exception cref="ArgumentNullException"><paramref name="client" /> is <see langword="null" />.</exception>
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;
};
}
}
/// <summary>
/// Gets a user by their ID. If the user is not found, <see langword="null" /> is returned instead of
/// <see cref="NotFoundException" /> being thrown.
/// </summary>
/// <param name="client">The Discord client.</param>
/// <param name="userId">The ID of the user to retrieve.</param>
/// <exception cref="ArgumentNullException"><paramref name="client" /> is <see langword="null" />.</exception>
public static async Task<DiscordUser?> 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;
}
}
}

View File

@ -0,0 +1,239 @@
using DSharpPlus.Entities;
namespace X10D.DSharpPlus;
/// <summary>
/// Extension methods for <see cref="DiscordEmbedBuilder" />.
/// </summary>
public static class DiscordEmbedBuilderExtensions
{
/// <summary>
/// Adds a field of any value type to the embed.
/// </summary>
/// <param name="builder">The <see cref="DiscordEmbedBuilder" /> to modify.</param>
/// <param name="name">The name of the embed field.</param>
/// <param name="value">The value of the embed field.</param>
/// <param name="inline"><see langword="true" /> to display this field inline; otherwise, <see langword="false" />.</param>
/// <typeparam name="T">The type of <paramref name="value" />.</typeparam>
/// <returns>The current instance of <see cref="DiscordEmbedBuilder" />; that is, <paramref name="builder" />.</returns>
/// <exception cref="ArgumentNullException"><paramref name="builder" /> is <see langword="null" />.</exception>
public static DiscordEmbedBuilder AddField<T>(
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);
}
/// <summary>
/// Conditionally adds a field to the embed.
/// </summary>
/// <param name="builder">The <see cref="DiscordEmbedBuilder" /> to modify.</param>
/// <param name="condition">The condition whose value is used to determine whether the field will be added.</param>
/// <param name="name">The name of the embed field.</param>
/// <param name="value">The value of the embed field.</param>
/// <param name="inline"><see langword="true" /> to display this field inline; otherwise, <see langword="false" />.</param>
/// <typeparam name="T">The type of <paramref name="value" />.</typeparam>
/// <returns>The current instance of <see cref="DiscordEmbedBuilder" />; that is, <paramref name="builder" />.</returns>
/// <exception cref="ArgumentNullException"><paramref name="builder" /> is <see langword="null" />.</exception>
public static DiscordEmbedBuilder AddFieldIf<T>(
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;
}
/// <summary>
/// Conditionally adds a field to the embed.
/// </summary>
/// <param name="builder">The <see cref="DiscordEmbedBuilder" /> to modify.</param>
/// <param name="predicate">The predicate whose return value is used to determine whether the field will be added.</param>
/// <param name="name">The name of the embed field.</param>
/// <param name="value">The value of the embed field.</param>
/// <param name="inline"><see langword="true" /> to display this field inline; otherwise, <see langword="false" />.</param>
/// <typeparam name="T">The type of <paramref name="value" />.</typeparam>
/// <returns>The current instance of <see cref="DiscordEmbedBuilder" />; that is, <paramref name="builder" />.</returns>
/// <exception cref="ArgumentNullException">
/// <para><paramref name="builder" /> is <see langword="null" />.</para>
/// -or-
/// <para><paramref name="predicate" /> is <see langword="null" />.</para>
/// </exception>
public static DiscordEmbedBuilder AddFieldIf<T>(
this DiscordEmbedBuilder builder,
Func<bool> 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;
}
/// <summary>
/// Conditionally adds a field to the embed.
/// </summary>
/// <param name="builder">The <see cref="DiscordEmbedBuilder" /> to modify.</param>
/// <param name="predicate">The predicate whose return value is used to determine whether the field will be added.</param>
/// <param name="name">The name of the embed field.</param>
/// <param name="valueFactory">The delegate whose return value will be used as the value of the embed field.</param>
/// <param name="inline"><see langword="true" /> to display this field inline; otherwise, <see langword="false" />.</param>
/// <typeparam name="T">The return type of <paramref name="valueFactory" />.</typeparam>
/// <returns>The current instance of <see cref="DiscordEmbedBuilder" />; that is, <paramref name="builder" />.</returns>
/// <exception cref="ArgumentNullException">
/// <para><paramref name="builder" /> is <see langword="null" />.</para>
/// -or-
/// <para><paramref name="predicate" /> is <see langword="null" />.</para>
/// -or-
/// <para><paramref name="valueFactory" /> is <see langword="null" />.</para>
/// </exception>
public static DiscordEmbedBuilder AddFieldIf<T>(
this DiscordEmbedBuilder builder,
Func<bool> predicate,
string name,
Func<T?> 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;
}
/// <summary>
/// Conditionally adds a field to the embed.
/// </summary>
/// <param name="builder">The <see cref="DiscordEmbedBuilder" /> to modify.</param>
/// <param name="condition">The condition whose value is used to determine whether the field will be added.</param>
/// <param name="name">The name of the embed field.</param>
/// <param name="valueFactory">The delegate whose return value will be used as the value of the embed field.</param>
/// <param name="inline"><see langword="true" /> to display this field inline; otherwise, <see langword="false" />.</param>
/// <typeparam name="T">The return type of <paramref name="valueFactory" />.</typeparam>
/// <returns>The current instance of <see cref="DiscordEmbedBuilder" />; that is, <paramref name="builder" />.</returns>
/// <exception cref="ArgumentNullException">
/// <para><paramref name="builder" /> is <see langword="null" />.</para>
/// -or-
/// <para><paramref name="valueFactory" /> is <see langword="null" />.</para>
/// </exception>
public static DiscordEmbedBuilder AddFieldIf<T>(
this DiscordEmbedBuilder builder,
bool condition,
string name,
Func<T?> 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;
}
/// <summary>
/// Sets the embed's author.
/// </summary>
/// <param name="builder">The embed builder to modify.</param>
/// <param name="user">The author.</param>
/// <returns>The current instance of <see cref="DiscordEmbedBuilder" />.</returns>
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);
}
}

View File

@ -0,0 +1,97 @@
using DSharpPlus;
using DSharpPlus.Entities;
using DSharpPlus.Exceptions;
namespace X10D.DSharpPlus;
/// <summary>
/// Extension methods for <see cref="DiscordGuild" />.
/// </summary>
public static class DiscordGuildExtensions
{
/// <summary>
/// Joins all active threads in the guild that this client has permission to view.
/// </summary>
/// <param name="guild">The guild whose active threads to join.</param>
/// <exception cref="ArgumentNullException"><paramref name="guild" /> is <see langword="null" />.</exception>
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);
}
/// <summary>
/// Gets a guild member by their ID. If the member is not found, <see langword="null" /> is returned instead of
/// <see cref="NotFoundException" /> being thrown.
/// </summary>
/// <param name="guild">The guild whose member list to search.</param>
/// <param name="userId">The ID of the member to retrieve.</param>
/// <exception cref="ArgumentNullException"><paramref name="guild" /> is <see langword="null" />.</exception>
public static async Task<DiscordMember?> 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;
}
}
/// <summary>
/// Normalizes a <see cref="DiscordGuild" /> so that the internal client is assured to be a specified value.
/// </summary>
/// <param name="guild">The <see cref="DiscordGuild" /> to normalize.</param>
/// <param name="client">The target client.</param>
/// <returns>
/// A <see cref="DiscordGuild" /> whose public values will match <paramref name="guild" />, but whose internal client is
/// <paramref name="client" />.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <para><paramref name="guild" /> is <see langword="null" /></para>
/// -or-
/// <para><paramref name="client" /> is <see langword="null" /></para>
/// </exception>
public static async Task<DiscordGuild> 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);
}
}

View File

@ -0,0 +1,73 @@
using DSharpPlus;
using DSharpPlus.Entities;
namespace X10D.DSharpPlus;
/// <summary>
/// Extension methods for <see cref="DiscordMember" />.
/// </summary>
public static class DiscordMemberExtensions
{
/// <summary>
/// Returns a value indicating whether this member has the specified role.
/// </summary>
/// <param name="member">The member whose roles to search.</param>
/// <param name="role">The role for which to check.</param>
/// <returns>
/// <see langword="true" /> if <paramref name="member" /> has the role; otherwise, <see langword="false" />.
/// </returns>
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);
}
/// <summary>
/// Normalizes a <see cref="DiscordMember" /> so that the internal client is assured to be a specified value.
/// </summary>
/// <param name="member">The <see cref="DiscordMember" /> to normalize.</param>
/// <param name="client">The target client.</param>
/// <returns>
/// A <see cref="DiscordMember" /> whose public values will match <paramref name="member" />, but whose internal client
/// is <paramref name="client" />.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <para><paramref name="member" /> is <see langword="null" /></para>
/// -or-
/// <para><paramref name="client" /> is <see langword="null" /></para>
/// </exception>
public static async Task<DiscordMember> 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);
}
}

View File

@ -0,0 +1,89 @@
using DSharpPlus;
using DSharpPlus.Entities;
namespace X10D.DSharpPlus;
/// <summary>
/// Extension methods for <see cref="DiscordMessage" />.
/// </summary>
public static class DiscordMessageExtensions
{
/// <summary>
/// Deletes this message after a specified delay.
/// </summary>
/// <param name="message">The message to delete.</param>
/// <param name="delay">The delay before deletion.</param>
/// <param name="reason">The reason for the deletion.</param>
/// <exception cref="ArgumentNullException"><paramref name="message" /> is <see langword="null" />.</exception>
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);
}
/// <summary>
/// Deletes the message as created by this task after a specified delay.
/// </summary>
/// <param name="task">The task whose <see cref="DiscordMessage" /> result should be deleted.</param>
/// <param name="delay">The delay before deletion.</param>
/// <param name="reason">The reason for the deletion.</param>
/// <exception cref="ArgumentNullException"><paramref name="task" /> is <see langword="null" />.</exception>
public static async Task DeleteAfterAsync(this Task<DiscordMessage> 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);
}
/// <summary>
/// Normalizes a <see cref="DiscordMessage" /> so that the internal client is assured to be a specified value.
/// </summary>
/// <param name="message">The <see cref="DiscordMessage" /> to normalize.</param>
/// <param name="client">The target client.</param>
/// <returns>
/// A <see cref="DiscordMessage" /> whose public values will match <paramref name="message" />, but whose internal client
/// is <paramref name="client" />.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <para><paramref name="message" /> is <see langword="null" /></para>
/// -or-
/// <para><paramref name="client" /> is <see langword="null" /></para>
/// </exception>
public static async Task<DiscordMessage> 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);
}
}

View File

@ -0,0 +1,158 @@
using DSharpPlus;
using DSharpPlus.Entities;
using DSharpPlus.Exceptions;
namespace X10D.DSharpPlus;
/// <summary>
/// Extension methods for <see cref="DiscordUser" />.
/// </summary>
public static class DiscordUserExtensions
{
/// <summary>
/// Returns the current <see cref="DiscordUser" /> as a member of the specified guild.
/// </summary>
/// <param name="user">The user to transform.</param>
/// <param name="guild">The guild whose member list to search.</param>
/// <returns>
/// A <see cref="DiscordMember" /> whose <see cref="DiscordMember.Guild" /> is equal to <paramref name="guild" />, or
/// <see langword="null" /> if this user is not in the specified <paramref name="guild" />.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <para><paramref name="user" /> is <see langword="null" />.</para>
/// -or-
/// <para><paramref name="guild" /> is <see langword="null" />.</para>
/// </exception>
public static async Task<DiscordMember?> 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;
}
}
/// <summary>
/// Returns the user's username with the discriminator, in the format <c>username#discriminator</c>.
/// </summary>
/// <param name="user">The user whose username and discriminator to retrieve.</param>
/// <returns>A string in the format <c>username#discriminator</c></returns>
/// <exception cref="ArgumentNullException"><paramref name="user" /> is <see langword="null" />.</exception>
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}";
}
/// <summary>
/// Returns a value indicating whether the current user is in the specified guild.
/// </summary>
/// <param name="user">The user to check.</param>
/// <param name="guild">The guild whose member list to search.</param>
/// <returns>
/// <see langword="true" /> if <paramref name="user" /> is a member of <paramref name="guild" />; otherwise,
/// <see langword="false" />.
/// </returns>
public static async Task<bool> 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;
}
}
/// <summary>
/// Normalizes a <see cref="DiscordUser" /> so that the internal client is assured to be a specified value.
/// </summary>
/// <param name="user">The <see cref="DiscordUser" /> to normalize.</param>
/// <param name="client">The target client.</param>
/// <returns>
/// A <see cref="DiscordUser" /> whose public values will match <paramref name="user" />, but whose internal client is
/// <paramref name="client" />.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <para><paramref name="user" /> is <see langword="null" /></para>
/// -or-
/// <para><paramref name="client" /> is <see langword="null" /></para>
/// </exception>
public static async Task<DiscordUser> 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);
}
}

View File

@ -0,0 +1,329 @@
using System.Globalization;
namespace X10D.DSharpPlus;
/// <summary>
/// Provides methods for encoding and decoding Discord mention strings.
/// </summary>
/// <remarks>
/// The implementations in this class are designed to resemble <c>MentionUtils</c> as provided by Discord.NET. The source is
/// available
/// <a href="https://github.com/discord-net/Discord.Net/blob/dev/src/Discord.Net.Core/Utils/MentionUtils.cs">
/// here
/// </a>.
/// </remarks>
public static class MentionUtility
{
/// <summary>
/// Returns a channel mention string built from the specified channel ID.
/// </summary>
/// <param name="id">The ID of the channel to mention.</param>
/// <returns>A channel mention string in the format <c>&lt;#123&gt;</c>.</returns>
public static string MentionChannel(decimal id)
{
return $"<#{id:N0}>";
}
/// <summary>
/// Returns a channel mention string built from the specified channel ID.
/// </summary>
/// <param name="id">The ID of the channel to mention.</param>
/// <returns>A channel mention string in the format <c>&lt;#123&gt;</c>.</returns>
[CLSCompliant(false)]
public static string MentionChannel(ulong id)
{
return $"<#{id}>";
}
/// <summary>
/// Returns a role mention string built from the specified channel ID.
/// </summary>
/// <param name="id">The ID of the role to mention.</param>
/// <returns>A role mention string in the format <c>&lt;@&amp;123&gt;</c>.</returns>
public static string MentionRole(decimal id)
{
return $"<@&{id:N0}>";
}
/// <summary>
/// Returns a role mention string built from the specified role ID.
/// </summary>
/// <param name="id">The ID of the role to mention.</param>
/// <returns>A role mention string in the format <c>&lt;@&amp;123&gt;</c>.</returns>
[CLSCompliant(false)]
public static string MentionRole(ulong id)
{
return $"<@&{id}>";
}
/// <summary>
/// Returns a user mention string built from the specified user ID.
/// </summary>
/// <param name="id">The ID of the user to mention.</param>
/// <returns>A user mention string in the format <c>&lt;@123&gt;</c>.</returns>
[CLSCompliant(false)]
public static string MentionUser(decimal id)
{
return MentionUser(id, false);
}
/// <summary>
/// Returns a user mention string built from the specified user ID.
/// </summary>
/// <param name="id">The ID of the user to mention.</param>
/// <param name="nickname">
/// <see langword="true" /> if the mention string should account for nicknames; otherwise, <see langword="false" />.
/// </param>
/// <returns>
/// A user mention string in the format <c>&lt;@!123&gt;</c> if <paramref name="nickname" /> is <see langword="true" />,
/// or in the format <c>&lt;@123&gt;</c> if <paramref name="nickname" /> is <see langword="false" />.
/// </returns>
[CLSCompliant(false)]
public static string MentionUser(decimal id, bool nickname)
{
return nickname ? $"<@!{id:N0}>" : $"<@{id:N0}>";
}
/// <summary>
/// Returns a user mention string built from the specified user ID.
/// </summary>
/// <param name="id">The ID of the user to mention.</param>
/// <returns>A user mention string in the format <c>&lt;@123&gt;</c>.</returns>
[CLSCompliant(false)]
public static string MentionUser(ulong id)
{
return MentionUser(id, false);
}
/// <summary>
/// Returns a user mention string built from the specified user ID.
/// </summary>
/// <param name="id">The ID of the user to mention.</param>
/// <param name="nickname">
/// <see langword="true" /> if the mention string should account for nicknames; otherwise, <see langword="false" />.
/// </param>
/// <returns>
/// A user mention string in the format <c>&lt;@!123&gt;</c> if <paramref name="nickname" /> is <see langword="true" />,
/// or in the format <c>&lt;@123&gt;</c> if <paramref name="nickname" /> is <see langword="false" />.
/// </returns>
[CLSCompliant(false)]
public static string MentionUser(ulong id, bool nickname)
{
return nickname ? $"<@!{id}>" : $"<@{id}>";
}
/// <summary>
/// Parses a provided channel mention string to a decimal value representing the channel ID. A return value indicates
/// whether the parse succeeded.
/// </summary>
/// <param name="value">A string containing a mention string to parse, in the format <c>&lt;#123&gt;</c>.</param>
/// <param name="result">
/// When this method returns, contains the decimal value representing the channel ID contained within
/// <paramref name="value" />, if the conversion succeeded, or zero if the conversion failed. The conversion fails if the
/// <paramref name="value" /> parameter is <see langword="null" /> or <see cref="string.Empty" />, is not of the correct
/// format, or represents a number less than <see cref="ulong.MinValue" /> or greater than <see cref="ulong.MaxValue" />.
/// </param>
/// <returns><see langword="true" /> if the parse was successful; otherwise, <see langword="false" />.</returns>
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;
}
/// <summary>
/// Parses a provided channel mention string to a 64-bit unsigned integer representing the channel ID. A return value
/// indicates whether the parse succeeded.
/// </summary>
/// <param name="value">A string containing a mention string to parse, in the format <c>&lt;#123&gt;</c>.</param>
/// <param name="result">
/// When this method returns, contains the 64-bit unsigned integer value representing the channel ID contained within
/// <paramref name="value" />, if the conversion succeeded, or zero if the conversion failed. The conversion fails if the
/// <paramref name="value" /> parameter is <see langword="null" /> or <see cref="string.Empty" />, is not of the correct
/// format, or represents a number less than <see cref="ulong.MinValue" /> or greater than <see cref="ulong.MaxValue" />.
/// </param>
/// <returns><see langword="true" /> if the parse was successful; otherwise, <see langword="false" />.</returns>
[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);
}
/// <summary>
/// Parses a provided role mention string to a decimal value representing the role ID. A return value indicates whether
/// the parse succeeded.
/// </summary>
/// <param name="value">A string containing a mention string to parse, in the format <c>&lt;@&amp;123&gt;</c>.</param>
/// <param name="result">
/// When this method returns, contains the decimal value representing the role ID contained within
/// <paramref name="value" />, if the conversion succeeded, or zero if the conversion failed. The conversion fails if the
/// <paramref name="value" /> parameter is <see langword="null" /> or <see cref="string.Empty" />, is not of the correct
/// format, or represents a number less than <see cref="ulong.MinValue" /> or greater than <see cref="ulong.MaxValue" />.
/// </param>
/// <returns><see langword="true" /> if the parse was successful; otherwise, <see langword="false" />.</returns>
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;
}
/// <summary>
/// Parses a provided role mention string to a 64-bit unsigned integer representing the role ID. A return value indicates
/// whether the parse succeeded.
/// </summary>
/// <param name="value">A string containing a mention string to parse, in the format <c>&lt;@&amp;123&gt;</c>.</param>
/// <param name="result">
/// When this method returns, contains the 64-bit unsigned integer value representing the role ID contained within
/// <paramref name="value" />, if the conversion succeeded, or zero if the conversion failed. The conversion fails if the
/// <paramref name="value" /> parameter is <see langword="null" /> or <see cref="string.Empty" />, is not of the correct
/// format, or represents a number less than <see cref="ulong.MinValue" /> or greater than <see cref="ulong.MaxValue" />.
/// </param>
/// <returns><see langword="true" /> if the parse was successful; otherwise, <see langword="false" />.</returns>
[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);
}
/// <summary>
/// Parses a provided user mention string to a decimal value representing the user ID. A return value indicates whether
/// the parse succeeded.
/// </summary>
/// <param name="value">
/// A string containing a mention string to parse, in the format <c>&lt;@123&gt;</c> or <c>&lt;@!123&gt;</c>.
/// </param>
/// <param name="result">
/// When this method returns, contains the decimal value representing the user ID contained within
/// <paramref name="value" />, if the conversion succeeded, or zero if the conversion failed. The conversion fails if the
/// <paramref name="value" /> parameter is <see langword="null" /> or <see cref="string.Empty" />, is not of the correct
/// format, or represents a number less than <see cref="ulong.MinValue" /> or greater than <see cref="ulong.MaxValue" />.
/// </param>
/// <returns><see langword="true" /> if the parse was successful; otherwise, <see langword="false" />.</returns>
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;
}
/// <summary>
/// Parses a provided user mention string to a 64-bit unsigned integer representing the user ID. A return value indicates
/// whether the parse succeeded.
/// </summary>
/// <param name="value">
/// A string containing a mention string to parse, in the format <c>&lt;@123&gt;</c> or <c>&lt;@!123&gt;</c>.
/// </param>
/// <param name="result">
/// When this method returns, contains the 64-bit unsigned integer value representing the user ID contained within
/// <paramref name="value" />, if the conversion succeeded, or zero if the conversion failed. The conversion fails if the
/// <paramref name="value" /> parameter is <see langword="null" /> or <see cref="string.Empty" />, is not of the correct
/// format, or represents a number less than <see cref="ulong.MinValue" /> or greater than <see cref="ulong.MaxValue" />.
/// </param>
/// <returns><see langword="true" /> if the parse was successful; otherwise, <see langword="false" />.</returns>
[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);
}
}

View File

@ -1,7 +1,69 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net7.0;net6.0;netstandard2.1</TargetFrameworks>
<LangVersion>11.0</LangVersion>
<Optimize>true</Optimize>
<ImplicitUsings>true</ImplicitUsings>
<Authors>Oliver Booth</Authors>
<NeutralLanguage>en</NeutralLanguage>
<RepositoryUrl>https://github.com/oliverbooth/X10D</RepositoryUrl>
<RepositoryType>git</RepositoryType>
<Description>Extension methods on crack.</Description>
<PackageLicenseFile>LICENSE.md</PackageLicenseFile>
<PackageIcon>branding_Icon.png</PackageIcon>
<PackageIconUrl/>
<PackageTags>dotnet extension-methods</PackageTags>
<PackageReleaseNotes>$([System.IO.File]::ReadAllText("$(MSBuildProjectDirectory)/../CHANGELOG.md"))</PackageReleaseNotes>
<CodeAnalysisTreatWarningsAsErrors>true</CodeAnalysisTreatWarningsAsErrors>
<VersionPrefix>4.0.0</VersionPrefix>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<EnableNETAnalyzers>true</EnableNETAnalyzers>
<DebugType>pdbonly</DebugType>
<DebugSymbols>true</DebugSymbols>
</PropertyGroup>
<PropertyGroup Condition="'$(GITHUB_ACTIONS)' == 'true'">
<ContinuousIntegrationBuild>true</ContinuousIntegrationBuild>
</PropertyGroup>
<PropertyGroup Condition="'$(VersionSuffix)' != '' And '$(BuildNumber)' == ''">
<Version>$(VersionPrefix)-$(VersionSuffix)</Version>
<AssemblyVersion>$(VersionPrefix).0</AssemblyVersion>
<FileVersion>$(VersionPrefix).0</FileVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(VersionSuffix)' != '' And '$(BuildNumber)' != ''">
<Version>$(VersionPrefix)-$(VersionSuffix).$(BuildNumber)</Version>
<AssemblyVersion>$(VersionPrefix).$(BuildNumber)</AssemblyVersion>
<FileVersion>$(VersionPrefix).$(BuildNumber)</FileVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(VersionSuffix)' == ''">
<Version>$(VersionPrefix)</Version>
<AssemblyVersion>$(VersionPrefix).0</AssemblyVersion>
<FileVersion>$(VersionPrefix).0</FileVersion>
</PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="7.0.0"/> <PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="7.0.0"/>
</ItemGroup> </ItemGroup>
<ItemGroup>
<None Include="..\branding_Icon.png">
<Pack>True</Pack>
<PackagePath/>
</None>
<None Include="..\LICENSE.md">
<Pack>True</Pack>
<PackagePath/>
</None>
<None Include="..\CHANGELOG.md">
<Pack>True</Pack>
<PackagePath/>
</None>
</ItemGroup>
</Project> </Project>

View File

@ -21,22 +21,6 @@ public static class ServiceCollectionExtensions
return services.AddSingleton<IHostedService, TService>(provider => provider.GetRequiredService<TService>()); return services.AddSingleton<IHostedService, TService>(provider => provider.GetRequiredService<TService>());
} }
/// <summary>
/// Adds an <see cref="IHostedService" /> registration for the given type, while simultaneously adding it as a singleton.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection" /> to add the service to.</param>
/// <typeparam name="TService">The type of the service to add.</typeparam>
/// <typeparam name="TImplementation">The type of the implementation to use.</typeparam>
/// <returns>A reference to this instance after the operation has completed.</returns>
public static IServiceCollection AddHostedSingleton<TService, TImplementation>(this IServiceCollection services)
where TService : class
where TImplementation : class, TService, IHostedService
{
services.AddSingleton<TService, TImplementation>();
return services.AddSingleton<IHostedService, TImplementation>(provider =>
(TImplementation)provider.GetRequiredService<TService>());
}
/// <summary> /// <summary>
/// Adds an <see cref="IHostedService" /> registration for the given type, while simultaneously adding it as a singleton. /// Adds an <see cref="IHostedService" /> registration for the given type, while simultaneously adding it as a singleton.
/// </summary> /// </summary>
@ -48,19 +32,4 @@ public static class ServiceCollectionExtensions
services.AddSingleton(type); services.AddSingleton(type);
return services.AddSingleton(provider => (IHostedService)provider.GetRequiredService(type)); return services.AddSingleton(provider => (IHostedService)provider.GetRequiredService(type));
} }
/// <summary>
/// Adds an <see cref="IHostedService" /> registration for the given type, while simultaneously adding it as a singleton.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection" /> to add the service to.</param>
/// <param name="serviceType">The type of the service to register.</param>
/// <param name="implementationType">The type of the implementation to use.</param>
/// <returns>A reference to this instance after the operation has completed.</returns>
public static IServiceCollection AddHostedSingleton(this IServiceCollection services,
Type serviceType,
Type implementationType)
{
services.AddSingleton(serviceType, implementationType);
return services.AddSingleton(provider => (IHostedService)provider.GetRequiredService(serviceType));
}
} }

View File

@ -3,7 +3,7 @@ using System.Text.RegularExpressions;
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text;
namespace SourceGenerator; namespace X10D.SourceGenerator;
[Generator] [Generator]
internal sealed class EmojiRegexGenerator : ISourceGenerator internal sealed class EmojiRegexGenerator : ISourceGenerator
@ -47,8 +47,8 @@ internal sealed class EmojiRegexGenerator : ISourceGenerator
} }
var builder = new StringBuilder(); var builder = new StringBuilder();
builder.AppendLine("// This file was auto-generated by the X10D source generator"); builder.AppendLine("// This file was auto-generated by X10D.SourceGenerator");
builder.AppendLine("// Do not edit this file manually!"); builder.AppendLine("// Do not edit this file manually");
builder.AppendLine(); builder.AppendLine();
builder.AppendLine("using System.Text.RegularExpressions;"); builder.AppendLine("using System.Text.RegularExpressions;");

View File

@ -2,6 +2,11 @@
<PropertyGroup> <PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework> <TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>11.0</LangVersion>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<ExcludeFromCodeCoverage>true</ExcludeFromCodeCoverage>
<EnableNETAnalyzers>true</EnableNETAnalyzers>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
@ -12,8 +17,4 @@
</PackageReference> </PackageReference>
</ItemGroup> </ItemGroup>
<ItemGroup>
<ProjectReference Include="..\X10D.MetaServices\X10D.MetaServices.csproj" PrivateAssets="all"/>
</ItemGroup>
</Project> </Project>

View File

@ -2,25 +2,24 @@
<PropertyGroup> <PropertyGroup>
<TargetFrameworks>net7.0;net6.0;netcoreapp3.1</TargetFrameworks> <TargetFrameworks>net7.0;net6.0;netcoreapp3.1</TargetFrameworks>
<LangVersion>11.0</LangVersion>
<IsPackable>false</IsPackable> <IsPackable>false</IsPackable>
<Nullable>enable</Nullable>
<ImplicitUsings>true</ImplicitUsings>
<CoverletOutputFormat>json,cobertura</CoverletOutputFormat> <CoverletOutputFormat>json,cobertura</CoverletOutputFormat>
<CollectCoverage>true</CollectCoverage> <CollectCoverage>true</CollectCoverage>
<CodeAnalysisTreatWarningsAsErrors>false</CodeAnalysisTreatWarningsAsErrors>
</PropertyGroup>
<PropertyGroup Condition="'$(TargetFramework)' == 'netcoreapp3.1'">
<SuppressTfmSupportBuildWarnings>true</SuppressTfmSupportBuildWarnings>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.1"/> <PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.0"/>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.5.0"/> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.5.0"/>
<PackageReference Include="NSubstitute" Version="5.0.0"/> <PackageReference Include="Moq" Version="4.18.4"/>
<PackageReference Include="NUnit" Version="3.13.3"/> <PackageReference Include="MSTest.TestAdapter" Version="3.0.2"/>
<PackageReference Include="NUnit3TestAdapter" Version="4.4.2"/> <PackageReference Include="MSTest.TestFramework" Version="3.0.2"/>
<PackageReference Include="NUnit.Analyzers" Version="3.6.1"/> <PackageReference Include="coverlet.collector" Version="3.2.0">
<PackageReference Include="coverlet.collector" Version="3.2.0"/> <PrivateAssets>all</PrivateAssets>
<PackageReference Include="System.Reactive" Version="5.0.0"/> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@ -1 +1 @@
[assembly: CLSCompliant(false)] [assembly: CLSCompliant(true)]

View File

@ -1,42 +1,42 @@
using NUnit.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting;
using X10D.Collections; using X10D.Collections;
namespace X10D.Tests.Collections; namespace X10D.Tests.Collections;
internal static partial class ArrayTests public partial class ArrayTests
{ {
[TestFixture] [TestClass]
internal class AsReadOnlyTests public class AsReadOnlyTests
{ {
[Test] [TestMethod]
public void AsReadOnly_ShouldReturnReadOnlyCollection_WhenArrayIsNotNull() public void AsReadOnly_ShouldReturnReadOnlyCollection_WhenArrayIsNotNull()
{ {
int[] array = {1, 2, 3}; int[] array = {1, 2, 3};
IReadOnlyCollection<int> result = array.AsReadOnly(); IReadOnlyCollection<int> result = array.AsReadOnly();
Assert.That(result, Is.InstanceOf<IReadOnlyCollection<int>>()); Assert.IsInstanceOfType(result, typeof(IReadOnlyCollection<int>));
} }
[Test] [TestMethod]
public void AsReadOnly_ShouldThrowArgumentNullException_WhenArrayIsNull() public void AsReadOnly_ShouldThrowArgumentNullException_WhenArrayIsNull()
{ {
int[] array = null!; int[]? array = null;
Assert.Throws<ArgumentNullException>(() => _ = array.AsReadOnly()); Assert.ThrowsException<ArgumentNullException>(() => array!.AsReadOnly());
} }
[Test] [TestMethod]
public void AsReadOnly_ShouldReturnCorrectCount_WhenArrayIsNotEmpty() public void AsReadOnly_ShouldReturnCorrectCount_WhenArrayIsNotEmpty()
{ {
int[] array = {1, 2, 3}; int[] array = {1, 2, 3};
IReadOnlyCollection<int> result = array.AsReadOnly(); IReadOnlyCollection<int> result = array.AsReadOnly();
Assert.That(result, Has.Count.EqualTo(array.Length)); Assert.AreEqual(array.Length, result.Count);
} }
[Test] [TestMethod]
public void AsReadOnly_ShouldReturnEmptyCollection_WhenArrayIsEmpty() public void AsReadOnly_ShouldReturnEmptyCollection_WhenArrayIsEmpty()
{ {
int[] array = Array.Empty<int>(); int[] array = Array.Empty<int>();
IReadOnlyCollection<int> result = array.AsReadOnly(); IReadOnlyCollection<int> result = array.AsReadOnly();
Assert.That(result, Is.Empty); Assert.AreEqual(0, result.Count);
} }
} }
} }

View File

@ -1,63 +1,63 @@
using NUnit.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting;
using X10D.Collections; using X10D.Collections;
namespace X10D.Tests.Collections; namespace X10D.Tests.Collections;
internal static partial class ArrayTests public partial class ArrayTests
{ {
[TestFixture] [TestClass]
public class ClearTests public class ClearTests
{ {
[Test] [TestMethod]
public void Clear_ShouldClearTheArray() public void Clear_ShouldClearTheArray()
{ {
var array = new int?[] {1, 2, 3, null, 4}; var array = new int?[] {1, 2, 3, null, 4};
array.Clear(); array.Clear();
Assert.That(array.All(x => x == null)); Assert.IsTrue(array.All(x => x == null));
} }
[Test] [TestMethod]
public void Clear_ShouldDoNothing_WhenArrayIsEmpty() public void Clear_ShouldDoNothing_WhenArrayIsEmpty()
{ {
int[] array = Array.Empty<int>(); int[] array = Array.Empty<int>();
array.Clear(); array.Clear();
} }
[Test] [TestMethod]
public void Clear_WithRange_ShouldClearTheSpecifiedRangeOfTheArray() public void Clear_WithRange_ShouldClearTheSpecifiedRangeOfTheArray()
{ {
var array = new int?[] {1, 2, 3, null, 4}; var array = new int?[] {1, 2, 3, null, 4};
array.Clear(1..4); array.Clear(1..4);
Assert.That(array.Length, Is.EqualTo(5)); Assert.AreEqual(5, array.Length);
Assert.That(array[0], Is.EqualTo(1)); Assert.AreEqual(1, array[0]);
Assert.That(array[4], Is.EqualTo(4)); Assert.AreEqual(4, array[4]);
Assert.That(array[1..4].All(x => x == null)); Assert.IsTrue(array[1..4].All(x => x == null));
} }
[Test] [TestMethod]
public void Clear_WithIndexAndLength_ShouldClearTheSpecifiedRangeOfTheArray() public void Clear_WithIndexAndLength_ShouldClearTheSpecifiedRangeOfTheArray()
{ {
var array = new int?[] {1, 2, 3, null, 4}; var array = new int?[] {1, 2, 3, null, 4};
array.Clear(1, 3); array.Clear(1, 3);
Assert.That(array.Length, Is.EqualTo(5)); Assert.AreEqual(5, array.Length);
Assert.That(array[0], Is.EqualTo(1)); Assert.AreEqual(1, array[0]);
Assert.That(array[4], Is.EqualTo(4)); Assert.AreEqual(4, array[4]);
Assert.That(array[1..4].All(x => x == null)); Assert.IsTrue(array[1..4].All(x => x == null));
} }
[Test] [TestMethod]
public void Clear_ShouldThrowArgumentNullException_WhenArrayIsNull() public void Clear_ShouldThrowArgumentNullException_WhenArrayIsNull()
{ {
int[] array = null!; int[] array = null!;
Assert.Throws<ArgumentNullException>(() => array.Clear()); Assert.ThrowsException<ArgumentNullException>(() => array.Clear());
Assert.Throws<ArgumentNullException>(() => array.Clear(0, 1)); Assert.ThrowsException<ArgumentNullException>(() => array.Clear(0, 1));
Assert.Throws<ArgumentNullException>(() => array.Clear(..1)); Assert.ThrowsException<ArgumentNullException>(() => array.Clear(..1));
} }
} }
} }

View File

@ -1,8 +1,8 @@
using NUnit.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace X10D.Tests.Collections; namespace X10D.Tests.Collections;
[TestFixture] [TestClass]
internal static partial class ArrayTests public partial class ArrayTests
{ {
} }

View File

@ -1,56 +1,56 @@
using NUnit.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting;
using X10D.Collections; using X10D.Collections;
namespace X10D.Tests.Collections; namespace X10D.Tests.Collections;
[TestFixture] [TestClass]
internal class BoolListTests public class BoolListTests
{ {
[Test] [TestMethod]
public void PackByte_Should_Pack_Correctly() public void PackByte_Should_Pack_Correctly()
{ {
var array = new[] {true, false, true, false, true, false, true, false}; var array = new[] {true, false, true, false, true, false, true, false};
Assert.That(array.PackByte(), Is.EqualTo(85)); // 01010101 Assert.AreEqual(85, array.PackByte()); // 01010101
} }
[Test] [TestMethod]
public void Pack16Bit_Should_Pack_Correctly() public void Pack16Bit_Should_Pack_Correctly()
{ {
var array = new[] {true, false, true, false, true, false, true, false, true, true, false, true}; var array = new[] {true, false, true, false, true, false, true, false, true, true, false, true};
Assert.That(array.PackInt16(), Is.EqualTo(2901)); // 101101010101 Assert.AreEqual(2901, array.PackInt16()); // 101101010101
} }
[Test] [TestMethod]
public void Pack32Bit_Should_Pack_Correctly() public void Pack32Bit_Should_Pack_Correctly()
{ {
var array = new[] {true, false, true, false, true, false, true, false, true, true, false, true}; var array = new[] {true, false, true, false, true, false, true, false, true, true, false, true};
Assert.That(array.PackInt32(), Is.EqualTo(2901)); // 101101010101 Assert.AreEqual(2901, array.PackInt32()); // 101101010101
} }
[Test] [TestMethod]
public void Pack64Bit_Should_Pack_Correctly() public void Pack64Bit_Should_Pack_Correctly()
{ {
var array = new[] {true, false, true, false, true, false, true, false, true, true, false, true}; var array = new[] {true, false, true, false, true, false, true, false, true, true, false, true};
Assert.That(array.PackInt64(), Is.EqualTo(2901)); // 101101010101 Assert.AreEqual(2901, array.PackInt64()); // 101101010101
} }
[Test] [TestMethod]
public void Pack_ShouldThrow_GivenLargeArray() public void Pack_ShouldThrow_GivenLargeArray()
{ {
bool[] array = Enumerable.Repeat(false, 65).ToArray(); bool[] array = Enumerable.Repeat(false, 65).ToArray();
Assert.Throws<ArgumentException>(() => _ = array.PackByte()); Assert.ThrowsException<ArgumentException>(() => array.PackByte());
Assert.Throws<ArgumentException>(() => _ = array.PackInt16()); Assert.ThrowsException<ArgumentException>(() => array.PackInt16());
Assert.Throws<ArgumentException>(() => _ = array.PackInt32()); Assert.ThrowsException<ArgumentException>(() => array.PackInt32());
Assert.Throws<ArgumentException>(() => _ = array.PackInt64()); Assert.ThrowsException<ArgumentException>(() => array.PackInt64());
} }
[Test] [TestMethod]
public void Pack_ShouldThrow_GivenNull() public void Pack_ShouldThrow_GivenNull()
{ {
bool[] array = null!; bool[]? array = null;
Assert.Throws<ArgumentNullException>(() => _ = array.PackByte()); Assert.ThrowsException<ArgumentNullException>(() => array!.PackByte());
Assert.Throws<ArgumentNullException>(() => _ = array.PackInt16()); Assert.ThrowsException<ArgumentNullException>(() => array!.PackInt16());
Assert.Throws<ArgumentNullException>(() => _ = array.PackInt32()); Assert.ThrowsException<ArgumentNullException>(() => array!.PackInt32());
Assert.Throws<ArgumentNullException>(() => _ = array.PackInt64()); Assert.ThrowsException<ArgumentNullException>(() => array!.PackInt64());
} }
} }

View File

@ -1,74 +1,67 @@
using System.Runtime.Intrinsics.X86; using System.Runtime.Intrinsics.X86;
using NUnit.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting;
using X10D.Collections; using X10D.Collections;
namespace X10D.Tests.Collections; namespace X10D.Tests.Collections;
[TestFixture] [TestClass]
internal class ByteTests public class ByteTests
{ {
[Test] [TestMethod]
public void Unpack_ShouldUnpackToArrayCorrectly() public void Unpack_ShouldUnpackToArrayCorrectly()
{ {
const byte value = 0b11010100; const byte value = 0b11010100;
bool[] bits = value.Unpack(); bool[] bits = value.Unpack();
Assert.That(bits, Has.Length.EqualTo(8)); Assert.AreEqual(8, bits.Length);
Assert.Multiple(() =>
{ Assert.IsFalse(bits[0]);
Assert.That(bits[0], Is.False); Assert.IsFalse(bits[1]);
Assert.That(bits[1], Is.False); Assert.IsTrue(bits[2]);
Assert.That(bits[2], Is.True); Assert.IsFalse(bits[3]);
Assert.That(bits[3], Is.False); Assert.IsTrue(bits[4]);
Assert.That(bits[4], Is.True); Assert.IsFalse(bits[5]);
Assert.That(bits[5], Is.False); Assert.IsTrue(bits[6]);
Assert.That(bits[6], Is.True); Assert.IsTrue(bits[7]);
Assert.That(bits[7], Is.True);
});
} }
[Test] [TestMethod]
public void Unpack_ShouldUnpackToSpanCorrectly() public void Unpack_ShouldUnpackToSpanCorrectly()
{ {
const byte value = 0b11010100; const byte value = 0b11010100;
Assert.Multiple(() =>
{
Span<bool> bits = stackalloc bool[8]; Span<bool> bits = stackalloc bool[8];
value.Unpack(bits); value.Unpack(bits);
Assert.That(bits[0], Is.False); Assert.IsFalse(bits[0]);
Assert.That(bits[1], Is.False); Assert.IsFalse(bits[1]);
Assert.That(bits[2], Is.True); Assert.IsTrue(bits[2]);
Assert.That(bits[3], Is.False); Assert.IsFalse(bits[3]);
Assert.That(bits[4], Is.True); Assert.IsTrue(bits[4]);
Assert.That(bits[5], Is.False); Assert.IsFalse(bits[5]);
Assert.That(bits[6], Is.True); Assert.IsTrue(bits[6]);
Assert.That(bits[7], Is.True); Assert.IsTrue(bits[7]);
});
} }
#if NET5_0_OR_GREATER #if NET5_0_OR_GREATER
[Test]
[TestMethod]
public void UnpackInternal_Fallback_ShouldUnpackToSpanCorrectly() public void UnpackInternal_Fallback_ShouldUnpackToSpanCorrectly()
{ {
const byte value = 0b11010100; const byte value = 0b11010100;
Assert.Multiple(() =>
{
Span<bool> bits = stackalloc bool[8]; Span<bool> bits = stackalloc bool[8];
value.UnpackInternal_Fallback(bits); value.UnpackInternal_Fallback(bits);
Assert.That(bits[0], Is.False); Assert.IsFalse(bits[0]);
Assert.That(bits[1], Is.False); Assert.IsFalse(bits[1]);
Assert.That(bits[2], Is.True); Assert.IsTrue(bits[2]);
Assert.That(bits[3], Is.False); Assert.IsFalse(bits[3]);
Assert.That(bits[4], Is.True); Assert.IsTrue(bits[4]);
Assert.That(bits[5], Is.False); Assert.IsFalse(bits[5]);
Assert.That(bits[6], Is.True); Assert.IsTrue(bits[6]);
Assert.That(bits[7], Is.True); Assert.IsTrue(bits[7]);
});
} }
[Test] [TestMethod]
public void UnpackInternal_Ssse3_ShouldUnpackToSpanCorrectly() public void UnpackInternal_Ssse3_ShouldUnpackToSpanCorrectly()
{ {
if (!Sse3.IsSupported) if (!Sse3.IsSupported)
@ -77,34 +70,31 @@ internal class ByteTests
} }
const byte value = 0b11010100; const byte value = 0b11010100;
Assert.Multiple(() =>
{
Span<bool> bits = stackalloc bool[8]; Span<bool> bits = stackalloc bool[8];
value.Unpack(bits); value.UnpackInternal_Ssse3(bits);
Assert.That(bits[0], Is.False); Assert.IsFalse(bits[0]);
Assert.That(bits[1], Is.False); Assert.IsFalse(bits[1]);
Assert.That(bits[2], Is.True); Assert.IsTrue(bits[2]);
Assert.That(bits[3], Is.False); Assert.IsFalse(bits[3]);
Assert.That(bits[4], Is.True); Assert.IsTrue(bits[4]);
Assert.That(bits[5], Is.False); Assert.IsFalse(bits[5]);
Assert.That(bits[6], Is.True); Assert.IsTrue(bits[6]);
Assert.That(bits[7], Is.True); Assert.IsTrue(bits[7]);
});
} }
#endif #endif
[Test] [TestMethod]
public void Unpack_ShouldRepackEqually() public void Unpack_ShouldRepackEqually()
{ {
const byte value = 0b11010100; const byte value = 0b11010100;
Assert.That(value.Unpack().PackByte(), Is.EqualTo(value)); Assert.AreEqual(value, value.Unpack().PackByte());
} }
[Test] [TestMethod]
public void Unpack_ShouldThrow_GivenTooSmallSpan() public void Unpack_ShouldThrow_GivenTooSmallSpan()
{ {
Assert.Throws<ArgumentException>(() => Assert.ThrowsException<ArgumentException>(() =>
{ {
const byte value = 0b11010100; const byte value = 0b11010100;
Span<bool> bits = stackalloc bool[0]; Span<bool> bits = stackalloc bool[0];

View File

@ -1,46 +1,45 @@
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
using NSubstitute; using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework; using Moq;
using X10D.Collections; using X10D.Collections;
namespace X10D.Tests.Collections; namespace X10D.Tests.Collections;
internal partial class CollectionTests public partial class CollectionTests
{ {
[TestFixture] [TestClass]
public class ClearAndDisposeAllTests public class ClearAndDisposeAllTests
{ {
[Test] [TestMethod]
public void ClearAndDisposeAll_ShouldClearAndDisposeAllItems_WhenCalledWithValidList() public void ClearAndDisposeAll_ShouldClearAndDisposeAllItems_WhenCalledWithValidList()
{ {
var substitute1 = Substitute.For<IDisposable>(); var mock1 = new Mock<IDisposable>();
var substitute2 = Substitute.For<IDisposable>(); var mock2 = new Mock<IDisposable>();
var substitute3 = Substitute.For<IDisposable>(); var mock3 = new Mock<IDisposable>();
var list = new List<IDisposable> {substitute1, substitute2, substitute3}; var list = new List<IDisposable> {mock1.Object, mock2.Object, mock3.Object};
list.ClearAndDisposeAll(); list.ClearAndDisposeAll();
substitute1.Received(1).Dispose(); mock1.Verify(i => i.Dispose(), Times.Once);
substitute2.Received(1).Dispose(); mock2.Verify(i => i.Dispose(), Times.Once);
substitute3.Received(1).Dispose(); mock3.Verify(i => i.Dispose(), Times.Once);
Assert.AreEqual(0, list.Count);
Assert.That(list, Is.Empty);
} }
[Test] [TestMethod]
public void ClearAndDisposeAll_ShouldThrowArgumentNullException_WhenCalledWithNullList() public void ClearAndDisposeAll_ShouldThrowArgumentNullException_WhenCalledWithNullList()
{ {
List<IDisposable>? list = null; List<IDisposable>? list = null;
Assert.Throws<ArgumentNullException>(() => list!.ClearAndDisposeAll()); Assert.ThrowsException<ArgumentNullException>(() => list!.ClearAndDisposeAll());
} }
[Test] [TestMethod]
public void ClearAndDisposeAll_ShouldThrowInvalidOperationException_WhenCalledWithReadOnlyList() public void ClearAndDisposeAll_ShouldThrowInvalidOperationException_WhenCalledWithReadOnlyList()
{ {
var substitute = Substitute.For<IDisposable>(); var mock = new Mock<IDisposable>();
var list = new ReadOnlyCollection<IDisposable>(new List<IDisposable> {substitute}); var list = new ReadOnlyCollection<IDisposable>(new List<IDisposable> {mock.Object});
Assert.Throws<InvalidOperationException>(() => list.ClearAndDisposeAll()); Assert.ThrowsException<InvalidOperationException>(() => list.ClearAndDisposeAll());
} }
} }
} }

View File

@ -1,46 +1,45 @@
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
using NSubstitute; using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework; using Moq;
using X10D.Collections; using X10D.Collections;
namespace X10D.Tests.Collections; namespace X10D.Tests.Collections;
internal partial class CollectionTests public partial class CollectionTests
{ {
[TestFixture] [TestClass]
public class ClearAndDisposeAllAsyncTests public class ClearAndDisposeAllAsyncTests
{ {
[Test] [TestMethod]
public async Task ClearAndDisposeAllAsync_ShouldClearAndDisposeAllItems_WhenCalledWithValidList() public async Task ClearAndDisposeAllAsync_ShouldClearAndDisposeAllItems_WhenCalledWithValidList()
{ {
var substitute1 = Substitute.For<IAsyncDisposable>(); var mock1 = new Mock<IAsyncDisposable>();
var substitute2 = Substitute.For<IAsyncDisposable>(); var mock2 = new Mock<IAsyncDisposable>();
var substitute3 = Substitute.For<IAsyncDisposable>(); var mock3 = new Mock<IAsyncDisposable>();
var list = new List<IAsyncDisposable> {substitute1, substitute2, substitute3}; var list = new List<IAsyncDisposable> {mock1.Object, mock2.Object, mock3.Object};
await list.ClearAndDisposeAllAsync().ConfigureAwait(false); await list.ClearAndDisposeAllAsync().ConfigureAwait(false);
await substitute1.Received(1).DisposeAsync(); mock1.Verify(i => i.DisposeAsync(), Times.Once);
await substitute2.Received(1).DisposeAsync(); mock2.Verify(i => i.DisposeAsync(), Times.Once);
await substitute3.Received(1).DisposeAsync(); mock3.Verify(i => i.DisposeAsync(), Times.Once);
Assert.AreEqual(0, list.Count);
Assert.That(list, Is.Empty);
} }
[Test] [TestMethod]
public void ClearAndDisposeAllAsync_ShouldThrowArgumentNullException_WhenCalledWithNullList() public async Task ClearAndDisposeAllAsync_ShouldThrowArgumentNullException_WhenCalledWithNullList()
{ {
List<IAsyncDisposable>? list = null; List<IAsyncDisposable>? list = null;
Assert.ThrowsAsync<ArgumentNullException>(list!.ClearAndDisposeAllAsync); await Assert.ThrowsExceptionAsync<ArgumentNullException>(list!.ClearAndDisposeAllAsync).ConfigureAwait(false);
} }
[Test] [TestMethod]
public void ClearAndDisposeAllAsync_ShouldThrowInvalidOperationException_WhenCalledWithReadOnlyList() public async Task ClearAndDisposeAllAsync_ShouldThrowInvalidOperationException_WhenCalledWithReadOnlyList()
{ {
var substitute = Substitute.For<IAsyncDisposable>(); var mock = new Mock<IAsyncDisposable>();
var list = new ReadOnlyCollection<IAsyncDisposable>(new List<IAsyncDisposable> {substitute}); var list = new ReadOnlyCollection<IAsyncDisposable>(new List<IAsyncDisposable> {mock.Object});
Assert.ThrowsAsync<InvalidOperationException>(list.ClearAndDisposeAllAsync); await Assert.ThrowsExceptionAsync<InvalidOperationException>(list.ClearAndDisposeAllAsync).ConfigureAwait(false);
} }
} }
} }

View File

@ -1,8 +1,8 @@
using NUnit.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace X10D.Tests.Collections; namespace X10D.Tests.Collections;
[TestFixture] [TestClass]
internal partial class CollectionTests public partial class CollectionTests
{ {
} }

View File

@ -1,231 +1,176 @@
using NUnit.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting;
using X10D.Collections; using X10D.Collections;
namespace X10D.Tests.Collections; namespace X10D.Tests.Collections;
[TestFixture] [TestClass]
internal class DictionaryTests public class DictionaryTests
{ {
[Test] [TestMethod]
public void AddOrUpdate_ShouldAddNewKey_IfNotExists_GivenConcreteDictionary() public void AddOrUpdate_ShouldAddNewKey_IfNotExists_GivenConcreteDictionary()
{ {
var dictionary = new Dictionary<int, string>(); var dictionary = new Dictionary<int, string>();
Assert.That(dictionary.ContainsKey(1), Is.False); Assert.IsFalse(dictionary.ContainsKey(1));
dictionary.AddOrUpdate(1, "one", (_, _) => string.Empty); dictionary.AddOrUpdate(1, "one", (_, _) => string.Empty);
Assert.Multiple(() => Assert.IsTrue(dictionary.ContainsKey(1));
{ Assert.AreEqual("one", dictionary[1]);
Assert.That(dictionary.ContainsKey(1));
Assert.That(dictionary[1], Is.EqualTo("one"));
});
dictionary.Clear(); dictionary.Clear();
Assert.That(dictionary.ContainsKey(1), Is.False); Assert.IsFalse(dictionary.ContainsKey(1));
dictionary.AddOrUpdate(1, _ => "one", (_, _) => string.Empty); dictionary.AddOrUpdate(1, _ => "one", (_, _) => string.Empty);
Assert.Multiple(() => Assert.IsTrue(dictionary.ContainsKey(1));
{ Assert.AreEqual("one", dictionary[1]);
Assert.That(dictionary.ContainsKey(1));
Assert.That(dictionary[1], Is.EqualTo("one"));
});
dictionary.Clear(); dictionary.Clear();
Assert.That(dictionary, Is.Empty); Assert.IsFalse(dictionary.ContainsKey(1));
Assert.That(dictionary.ContainsKey(1), Is.False);
dictionary.AddOrUpdate(1, (_, _) => "one", (_, _, _) => string.Empty, 0); dictionary.AddOrUpdate(1, (_, _) => "one", (_, _, _) => string.Empty, 0);
Assert.Multiple(() => Assert.IsTrue(dictionary.ContainsKey(1));
{ Assert.AreEqual("one", dictionary[1]);
Assert.That(dictionary.ContainsKey(1), Is.True);
Assert.That(dictionary[1], Is.EqualTo("one"));
});
} }
[Test] [TestMethod]
public void AddOrUpdate_ShouldAddNewKey_IfNotExists_GivenIDictionary() public void AddOrUpdate_ShouldAddNewKey_IfNotExists_GivenIDictionary()
{ {
IDictionary<int, string> dictionary = new Dictionary<int, string>(); IDictionary<int, string> dictionary = new Dictionary<int, string>();
Assert.That(dictionary.ContainsKey(1), Is.False); Assert.IsFalse(dictionary.ContainsKey(1));
dictionary.AddOrUpdate(1, "one", (_, _) => string.Empty); dictionary.AddOrUpdate(1, "one", (_, _) => string.Empty);
Assert.Multiple(() => Assert.IsTrue(dictionary.ContainsKey(1));
{ Assert.AreEqual("one", dictionary[1]);
Assert.That(dictionary.ContainsKey(1), Is.True);
Assert.That(dictionary[1], Is.EqualTo("one"));
});
dictionary.Clear(); dictionary.Clear();
Assert.That(dictionary.ContainsKey(1), Is.False); Assert.IsFalse(dictionary.ContainsKey(1));
dictionary.AddOrUpdate(1, _ => "one", (_, _) => string.Empty); dictionary.AddOrUpdate(1, _ => "one", (_, _) => string.Empty);
Assert.Multiple(() => Assert.IsTrue(dictionary.ContainsKey(1));
{ Assert.AreEqual("one", dictionary[1]);
Assert.That(dictionary.ContainsKey(1), Is.True);
Assert.That(dictionary[1], Is.EqualTo("one"));
});
dictionary.Clear(); dictionary.Clear();
Assert.That(dictionary, Is.Empty); Assert.IsFalse(dictionary.ContainsKey(1));
Assert.That(dictionary.ContainsKey(1), Is.False);
dictionary.AddOrUpdate(1, (_, _) => "one", (_, _, _) => string.Empty, 0); dictionary.AddOrUpdate(1, (_, _) => "one", (_, _, _) => string.Empty, 0);
Assert.Multiple(() => Assert.IsTrue(dictionary.ContainsKey(1));
{ Assert.AreEqual("one", dictionary[1]);
Assert.That(dictionary.ContainsKey(1), Is.True);
Assert.That(dictionary[1], Is.EqualTo("one"));
});
} }
[Test] [TestMethod]
public void AddOrUpdate_ShouldUpdateKey_IfExists_GivenConcreteDirection() public void AddOrUpdate_ShouldUpdateKey_IfExists_GivenConcreteDirection()
{ {
var dictionary = new Dictionary<int, string> {[1] = "one"}; var dictionary = new Dictionary<int, string> {[1] = "one"};
Assert.Multiple(() => Assert.IsTrue(dictionary.ContainsKey(1));
{ Assert.AreEqual("one", dictionary[1]);
Assert.That(dictionary.ContainsKey(1));
Assert.That(dictionary[1], Is.EqualTo("one"));
});
dictionary.AddOrUpdate(1, string.Empty, (_, _) => "two"); dictionary.AddOrUpdate(1, string.Empty, (_, _) => "two");
Assert.Multiple(() => Assert.IsTrue(dictionary.ContainsKey(1));
{ Assert.AreEqual("two", dictionary[1]);
Assert.That(dictionary.ContainsKey(1));
Assert.That(dictionary[1], Is.EqualTo("two"));
});
dictionary.Clear(); dictionary.Clear();
Assert.That(dictionary, Is.Empty); Assert.IsFalse(dictionary.ContainsKey(1));
Assert.That(dictionary.ContainsKey(1), Is.False);
dictionary[1] = "one"; dictionary[1] = "one";
dictionary.AddOrUpdate(1, _ => string.Empty, (_, _) => "two");
Assert.Multiple(() => dictionary.AddOrUpdate(1, _ => string.Empty, (_, _) => "two");
{ Assert.IsTrue(dictionary.ContainsKey(1));
Assert.That(dictionary.ContainsKey(1)); Assert.AreEqual("two", dictionary[1]);
Assert.That(dictionary[1], Is.EqualTo("two"));
});
dictionary.Clear(); dictionary.Clear();
Assert.That(dictionary, Is.Empty); Assert.IsFalse(dictionary.ContainsKey(1));
Assert.That(dictionary.ContainsKey(1), Is.False);
dictionary[1] = "one"; dictionary[1] = "one";
dictionary.AddOrUpdate(1, (_, _) => string.Empty, (_, _, _) => "two", 0); dictionary.AddOrUpdate(1, (_, _) => string.Empty, (_, _, _) => "two", 0);
Assert.Multiple(() => Assert.IsTrue(dictionary.ContainsKey(1));
{ Assert.AreEqual("two", dictionary[1]);
Assert.That(dictionary.ContainsKey(1));
Assert.That(dictionary[1], Is.EqualTo("two"));
});
} }
[Test] [TestMethod]
public void AddOrUpdate_ShouldUpdateKey_IfExists_GivenIDictionary() public void AddOrUpdate_ShouldUpdateKey_IfExists_GivenIDictionary()
{ {
IDictionary<int, string> dictionary = new Dictionary<int, string> {[1] = "one"}; IDictionary<int, string> dictionary = new Dictionary<int, string> {[1] = "one"};
Assert.Multiple(() => Assert.IsTrue(dictionary.ContainsKey(1));
{ Assert.AreEqual("one", dictionary[1]);
Assert.That(dictionary.ContainsKey(1));
Assert.That(dictionary[1], Is.EqualTo("one"));
});
dictionary.AddOrUpdate(1, string.Empty, (_, _) => "two"); dictionary.AddOrUpdate(1, string.Empty, (_, _) => "two");
Assert.Multiple(() => Assert.IsTrue(dictionary.ContainsKey(1));
{ Assert.AreEqual("two", dictionary[1]);
Assert.That(dictionary.ContainsKey(1));
Assert.That(dictionary[1], Is.EqualTo("two"));
});
dictionary.Clear(); dictionary.Clear();
Assert.Multiple(() => Assert.IsFalse(dictionary.ContainsKey(1));
{
Assert.That(dictionary, Is.Empty);
Assert.That(dictionary.ContainsKey(1), Is.False);
});
dictionary[1] = "one"; dictionary[1] = "one";
dictionary.AddOrUpdate(1, _ => string.Empty, (_, _) => "two"); dictionary.AddOrUpdate(1, _ => string.Empty, (_, _) => "two");
Assert.Multiple(() => Assert.IsTrue(dictionary.ContainsKey(1));
{ Assert.AreEqual("two", dictionary[1]);
Assert.That(dictionary.ContainsKey(1));
Assert.That(dictionary[1], Is.EqualTo("two"));
});
dictionary.Clear(); dictionary.Clear();
Assert.Multiple(() => Assert.IsFalse(dictionary.ContainsKey(1));
{
Assert.That(dictionary, Is.Empty);
Assert.That(dictionary.ContainsKey(1), Is.False);
dictionary[1] = "one"; dictionary[1] = "one";
});
dictionary.AddOrUpdate(1, (_, _) => string.Empty, (_, _, _) => "two", 0); dictionary.AddOrUpdate(1, (_, _) => string.Empty, (_, _, _) => "two", 0);
Assert.Multiple(() => Assert.IsTrue(dictionary.ContainsKey(1));
{ Assert.AreEqual("two", dictionary[1]);
Assert.That(dictionary.ContainsKey(1));
Assert.That(dictionary[1], Is.EqualTo("two"));
});
} }
[Test] [TestMethod]
public void AddOrUpdate_ShouldThrow_GivenNullDictionary_GivenConcreteDictionary() public void AddOrUpdate_ShouldThrow_GivenNullDictionary_GivenConcreteDictionary()
{ {
Dictionary<int, string>? dictionary = null; Dictionary<int, string>? dictionary = null;
Assert.Throws<ArgumentNullException>(() => dictionary!.AddOrUpdate(1, string.Empty, (_, _) => string.Empty)); Assert.ThrowsException<ArgumentNullException>(() => dictionary!.AddOrUpdate(1, string.Empty, (_, _) => string.Empty));
Assert.Throws<ArgumentNullException>(() => Assert.ThrowsException<ArgumentNullException>(() =>
dictionary!.AddOrUpdate(1, _ => string.Empty, (_, _) => string.Empty)); dictionary!.AddOrUpdate(1, _ => string.Empty, (_, _) => string.Empty));
Assert.Throws<ArgumentNullException>(() => Assert.ThrowsException<ArgumentNullException>(() =>
dictionary!.AddOrUpdate(1, (_, _) => string.Empty, (_, _, _) => string.Empty, 0)); dictionary!.AddOrUpdate(1, (_, _) => string.Empty, (_, _, _) => string.Empty, 0));
} }
[Test] [TestMethod]
public void AddOrUpdate_ShouldThrow_GivenNullDictionary_GivenIDictionary() public void AddOrUpdate_ShouldThrow_GivenNullDictionary_GivenIDictionary()
{ {
IDictionary<int, string>? dictionary = null; IDictionary<int, string>? dictionary = null;
Assert.Throws<ArgumentNullException>(() => dictionary!.AddOrUpdate(1, string.Empty, (_, _) => string.Empty)); Assert.ThrowsException<ArgumentNullException>(() => dictionary!.AddOrUpdate(1, string.Empty, (_, _) => string.Empty));
Assert.Throws<ArgumentNullException>(() => Assert.ThrowsException<ArgumentNullException>(() =>
dictionary!.AddOrUpdate(1, _ => string.Empty, (_, _) => string.Empty)); dictionary!.AddOrUpdate(1, _ => string.Empty, (_, _) => string.Empty));
Assert.Throws<ArgumentNullException>(() => Assert.ThrowsException<ArgumentNullException>(() =>
dictionary!.AddOrUpdate(1, (_, _) => string.Empty, (_, _, _) => string.Empty, 0)); dictionary!.AddOrUpdate(1, (_, _) => string.Empty, (_, _, _) => string.Empty, 0));
} }
[Test] [TestMethod]
public void AddOrUpdate_ShouldThrow_GivenNullUpdateValueFactory_GivenConcreteDictionary() public void AddOrUpdate_ShouldThrow_GivenNullUpdateValueFactory_GivenConcreteDictionary()
{ {
var dictionary = new Dictionary<int, string>(); var dictionary = new Dictionary<int, string>();
Assert.Throws<ArgumentNullException>(() => dictionary.AddOrUpdate(1, string.Empty, null!)); Assert.ThrowsException<ArgumentNullException>(() => dictionary.AddOrUpdate(1, string.Empty, null!));
Assert.Throws<ArgumentNullException>(() => dictionary.AddOrUpdate(1, _ => string.Empty, null!)); Assert.ThrowsException<ArgumentNullException>(() => dictionary.AddOrUpdate(1, _ => string.Empty, null!));
Assert.Throws<ArgumentNullException>(() => dictionary.AddOrUpdate(1, (_, _) => string.Empty, null!, 0)); Assert.ThrowsException<ArgumentNullException>(() => dictionary.AddOrUpdate(1, (_, _) => string.Empty, null!, 0));
} }
[Test] [TestMethod]
public void AddOrUpdate_ShouldThrow_GivenNullUpdateValueFactory_GivenIDictionary() public void AddOrUpdate_ShouldThrow_GivenNullUpdateValueFactory_GivenIDictionary()
{ {
IDictionary<int, string> dictionary = new Dictionary<int, string>(); IDictionary<int, string> dictionary = new Dictionary<int, string>();
Assert.Throws<ArgumentNullException>(() => dictionary.AddOrUpdate(1, string.Empty, null!)); Assert.ThrowsException<ArgumentNullException>(() => dictionary.AddOrUpdate(1, string.Empty, null!));
Assert.Throws<ArgumentNullException>(() => dictionary.AddOrUpdate(1, _ => string.Empty, null!)); Assert.ThrowsException<ArgumentNullException>(() => dictionary.AddOrUpdate(1, _ => string.Empty, null!));
Assert.Throws<ArgumentNullException>(() => dictionary.AddOrUpdate(1, (_, _) => string.Empty, null!, 0)); Assert.ThrowsException<ArgumentNullException>(() => dictionary.AddOrUpdate(1, (_, _) => string.Empty, null!, 0));
} }
[Test] [TestMethod]
public void AddOrUpdate_ShouldThrow_GivenNullAddValueFactory_GivenConcreteDictionary() public void AddOrUpdate_ShouldThrow_GivenNullAddValueFactory_GivenConcreteDictionary()
{ {
var dictionary = new Dictionary<int, string>(); var dictionary = new Dictionary<int, string>();
Func<int, string>? addValueFactory = null; Func<int, string>? addValueFactory = null;
Assert.Throws<ArgumentNullException>(() => dictionary.AddOrUpdate(1, addValueFactory!, (_, _) => "one")); Assert.ThrowsException<ArgumentNullException>(() => dictionary.AddOrUpdate(1, addValueFactory!, (_, _) => "one"));
Assert.Throws<ArgumentNullException>(() => dictionary.AddOrUpdate(1, null!, (_, _, _) => "one", 0)); Assert.ThrowsException<ArgumentNullException>(() => dictionary.AddOrUpdate(1, null!, (_, _, _) => "one", 0));
} }
[Test] [TestMethod]
public void AddOrUpdate_ShouldThrow_GivenNullAddValueFactory_GivenIDictionary() public void AddOrUpdate_ShouldThrow_GivenNullAddValueFactory_GivenIDictionary()
{ {
IDictionary<int, string> dictionary = new Dictionary<int, string>(); IDictionary<int, string> dictionary = new Dictionary<int, string>();
Func<int, string>? addValueFactory = null; Func<int, string>? addValueFactory = null;
Assert.Throws<ArgumentNullException>(() => dictionary.AddOrUpdate(1, addValueFactory!, (_, _) => "one")); Assert.ThrowsException<ArgumentNullException>(() => dictionary.AddOrUpdate(1, addValueFactory!, (_, _) => "one"));
Assert.Throws<ArgumentNullException>(() => dictionary.AddOrUpdate(1, null!, (_, _, _) => "one", 0)); Assert.ThrowsException<ArgumentNullException>(() => dictionary.AddOrUpdate(1, null!, (_, _, _) => "one", 0));
} }
[Test] [TestMethod]
public void ToConnectionString_ShouldReturnConnectionString() public void ToConnectionString_ShouldReturnConnectionString()
{ {
var dictionary = new Dictionary<string, string?> var dictionary = new Dictionary<string, string?>
@ -234,10 +179,10 @@ internal class DictionaryTests
}; };
string connectionString = dictionary.ToConnectionString(); string connectionString = dictionary.ToConnectionString();
Assert.That(connectionString, Is.EqualTo("Data Source=localhost;Initial Catalog=test;Integrated Security=True;Foobar=")); Assert.AreEqual("Data Source=localhost;Initial Catalog=test;Integrated Security=True;Foobar=", connectionString);
} }
[Test] [TestMethod]
public void ToConnectionString_ShouldReturnTransformedValueConnectionString() public void ToConnectionString_ShouldReturnTransformedValueConnectionString()
{ {
var dictionary = new Dictionary<string, string?> var dictionary = new Dictionary<string, string?>
@ -246,10 +191,10 @@ internal class DictionaryTests
}; };
string connectionString = dictionary.ToConnectionString(v => v?.ToUpperInvariant()); string connectionString = dictionary.ToConnectionString(v => v?.ToUpperInvariant());
Assert.That(connectionString, Is.EqualTo("Data Source=LOCALHOST;Initial Catalog=TEST;Integrated Security=TRUE;Foobar=")); Assert.AreEqual("Data Source=LOCALHOST;Initial Catalog=TEST;Integrated Security=TRUE;Foobar=", connectionString);
} }
[Test] [TestMethod]
public void ToConnectionString_ShouldReturnTransformedKeyValueConnectionString() public void ToConnectionString_ShouldReturnTransformedKeyValueConnectionString()
{ {
var dictionary = new Dictionary<string, string?> var dictionary = new Dictionary<string, string?>
@ -258,69 +203,69 @@ internal class DictionaryTests
}; };
string connectionString = dictionary.ToConnectionString(k => k.ToUpper(), v => v?.ToUpperInvariant()); string connectionString = dictionary.ToConnectionString(k => k.ToUpper(), v => v?.ToUpperInvariant());
Assert.That(connectionString, Is.EqualTo("DATA SOURCE=LOCALHOST;INITIAL CATALOG=TEST;INTEGRATED SECURITY=TRUE;FOOBAR=")); Assert.AreEqual("DATA SOURCE=LOCALHOST;INITIAL CATALOG=TEST;INTEGRATED SECURITY=TRUE;FOOBAR=", connectionString);
} }
[Test] [TestMethod]
public void ToConnectionString_ShouldThrow_GivenNullSource() public void ToConnectionString_ShouldThrow_GivenNullSource()
{ {
Dictionary<string, string> dictionary = null!; Dictionary<string, string>? dictionary = null;
Assert.Throws<ArgumentNullException>(() => _ = dictionary.ToConnectionString()); Assert.ThrowsException<ArgumentNullException>(() => dictionary!.ToConnectionString());
Assert.Throws<ArgumentNullException>(() => _ = dictionary.ToConnectionString(null!)); Assert.ThrowsException<ArgumentNullException>(() => dictionary!.ToConnectionString(null!));
Assert.Throws<ArgumentNullException>(() => _ = dictionary.ToConnectionString(null!, null!)); Assert.ThrowsException<ArgumentNullException>(() => dictionary!.ToConnectionString(null!, null!));
} }
[Test] [TestMethod]
public void ToConnectionString_ShouldThrow_GivenNullSelector() public void ToConnectionString_ShouldThrow_GivenNullSelector()
{ {
var dictionary = new Dictionary<string, string>(); var dictionary = new Dictionary<string, string>();
Assert.Throws<ArgumentNullException>(() => _ = dictionary.ToConnectionString(null!)); Assert.ThrowsException<ArgumentNullException>(() => dictionary.ToConnectionString(null!));
Assert.Throws<ArgumentNullException>(() => _ = dictionary.ToConnectionString(null!, _ => _)); Assert.ThrowsException<ArgumentNullException>(() => dictionary.ToConnectionString(null!, _ => _));
Assert.Throws<ArgumentNullException>(() => _ = dictionary.ToConnectionString(_ => _, null!)); Assert.ThrowsException<ArgumentNullException>(() => dictionary.ToConnectionString(_ => _, null!));
} }
[Test] [TestMethod]
public void ToGetParameters_ShouldReturnParameters() public void ToGetParameters_ShouldReturnParameters()
{ {
var dictionary = new Dictionary<string, string> {["id"] = "1", ["user"] = "hello world", ["foo"] = "bar"}; var dictionary = new Dictionary<string, string> {["id"] = "1", ["user"] = "hello world", ["foo"] = "bar"};
string queryString = dictionary.ToGetParameters(); string queryString = dictionary.ToGetParameters();
Assert.That(queryString, Is.EqualTo("id=1&user=hello+world&foo=bar")); Assert.AreEqual("id=1&user=hello+world&foo=bar", queryString);
} }
[Test] [TestMethod]
public void ToGetParameters_ShouldReturnTransformedValueParameters() public void ToGetParameters_ShouldReturnTransformedValueParameters()
{ {
var dictionary = new Dictionary<string, string?> {["id"] = "1", ["user"] = "hello world", ["foo"] = null}; var dictionary = new Dictionary<string, string?> {["id"] = "1", ["user"] = "hello world", ["foo"] = null};
string queryString = dictionary.ToGetParameters(v => v?.ToUpper()); string queryString = dictionary.ToGetParameters(v => v?.ToUpper());
Assert.That(queryString, Is.EqualTo("id=1&user=HELLO+WORLD&foo=")); Assert.AreEqual("id=1&user=HELLO+WORLD&foo=", queryString);
} }
[Test] [TestMethod]
public void ToGetParameters_ShouldReturnTransformedKeyValueParameters() public void ToGetParameters_ShouldReturnTransformedKeyValueParameters()
{ {
var dictionary = new Dictionary<string, string?> {["id"] = "1", ["user"] = "hello world", ["foo"] = null}; var dictionary = new Dictionary<string, string?> {["id"] = "1", ["user"] = "hello world", ["foo"] = null};
string queryString = dictionary.ToGetParameters(k => k.ToUpper(), v => v?.ToUpper()); string queryString = dictionary.ToGetParameters(k => k.ToUpper(), v => v?.ToUpper());
Assert.That(queryString, Is.EqualTo("ID=1&USER=HELLO+WORLD&FOO=")); Assert.AreEqual("ID=1&USER=HELLO+WORLD&FOO=", queryString);
} }
[Test] [TestMethod]
public void ToGetParameters_ShouldThrow_GivenNullSource() public void ToGetParameters_ShouldThrow_GivenNullSource()
{ {
Dictionary<string, string> dictionary = null!; Dictionary<string, string>? dictionary = null;
Assert.Throws<ArgumentNullException>(() => _ = dictionary.ToGetParameters()); Assert.ThrowsException<ArgumentNullException>(() => dictionary!.ToGetParameters());
Assert.Throws<ArgumentNullException>(() => _ = dictionary.ToGetParameters(null!)); Assert.ThrowsException<ArgumentNullException>(() => dictionary!.ToGetParameters(null!));
Assert.Throws<ArgumentNullException>(() => _ = dictionary.ToGetParameters(null!, null!)); Assert.ThrowsException<ArgumentNullException>(() => dictionary!.ToGetParameters(null!, null!));
} }
[Test] [TestMethod]
public void ToGetParameters_ShouldThrow_GivenNullSelector() public void ToGetParameters_ShouldThrow_GivenNullSelector()
{ {
var dictionary = new Dictionary<string, string>(); var dictionary = new Dictionary<string, string>();
Assert.Throws<ArgumentNullException>(() => _ = dictionary.ToGetParameters(null!)); Assert.ThrowsException<ArgumentNullException>(() => dictionary.ToGetParameters(null!));
Assert.Throws<ArgumentNullException>(() => _ = dictionary.ToGetParameters(null!, _ => _)); Assert.ThrowsException<ArgumentNullException>(() => dictionary.ToGetParameters(null!, _ => _));
Assert.Throws<ArgumentNullException>(() => _ = dictionary.ToGetParameters(_ => _, null!)); Assert.ThrowsException<ArgumentNullException>(() => dictionary.ToGetParameters(_ => _, null!));
} }
} }

View File

@ -1,34 +1,34 @@
using NSubstitute; using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework; using Moq;
using X10D.Collections; using X10D.Collections;
namespace X10D.Tests.Collections; namespace X10D.Tests.Collections;
internal partial class EnumerableTests public partial class EnumerableTests
{ {
[TestFixture] [TestClass]
public class DisposeAllTests public class DisposeAllTests
{ {
[Test] [TestMethod]
public void DisposeAll_ShouldDisposeAllItems_WhenCalledWithValidList() public void DisposeAll_ShouldDisposeAllItems_WhenCalledWithValidList()
{ {
var substitute1 = Substitute.For<IDisposable>(); var mock1 = new Mock<IDisposable>();
var substitute2 = Substitute.For<IDisposable>(); var mock2 = new Mock<IDisposable>();
var substitute3 = Substitute.For<IDisposable>(); var mock3 = new Mock<IDisposable>();
var list = new List<IDisposable> { substitute1, substitute2, null!, substitute3 }; var list = new List<IDisposable> {mock1.Object, mock2.Object, null!, mock3.Object};
list.DisposeAll(); list.DisposeAll();
substitute1.Received(1).Dispose(); mock1.Verify(i => i.Dispose(), Times.Once);
substitute2.Received(1).Dispose(); mock2.Verify(i => i.Dispose(), Times.Once);
substitute3.Received(1).Dispose(); mock3.Verify(i => i.Dispose(), Times.Once);
} }
[Test] [TestMethod]
public void DisposeAll_ShouldThrowArgumentNullException_WhenCalledWithNullList() public void DisposeAll_ShouldThrowArgumentNullException_WhenCalledWithNullList()
{ {
List<IDisposable> list = null!; List<IDisposable>? list = null;
Assert.Throws<ArgumentNullException>(() => list.DisposeAll()); Assert.ThrowsException<ArgumentNullException>(() => list!.DisposeAll());
} }
} }
} }

View File

@ -1,34 +1,34 @@
using NSubstitute; using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework; using Moq;
using X10D.Collections; using X10D.Collections;
namespace X10D.Tests.Collections; namespace X10D.Tests.Collections;
internal partial class EnumerableTests public partial class EnumerableTests
{ {
[TestFixture] [TestClass]
public class DisposeAllAsyncTests public class DisposeAllAsyncTests
{ {
[Test] [TestMethod]
public async Task DisposeAllAsync_ShouldDisposeAllItems_WhenCalledWithValidList() public async Task DisposeAllAsync_ShouldDisposeAllItems_WhenCalledWithValidList()
{ {
var substitute1 = Substitute.For<IAsyncDisposable>(); var mock1 = new Mock<IAsyncDisposable>();
var substitute2 = Substitute.For<IAsyncDisposable>(); var mock2 = new Mock<IAsyncDisposable>();
var substitute3 = Substitute.For<IAsyncDisposable>(); var mock3 = new Mock<IAsyncDisposable>();
var list = new List<IAsyncDisposable> { substitute1, substitute2, null!, substitute3 }; var list = new List<IAsyncDisposable> {mock1.Object, mock2.Object, null!, mock3.Object};
await list.DisposeAllAsync().ConfigureAwait(false); await list.DisposeAllAsync().ConfigureAwait(false);
await substitute1.Received(1).DisposeAsync(); mock1.Verify(i => i.DisposeAsync(), Times.Once);
await substitute2.Received(1).DisposeAsync(); mock2.Verify(i => i.DisposeAsync(), Times.Once);
await substitute3.Received(1).DisposeAsync(); mock3.Verify(i => i.DisposeAsync(), Times.Once);
} }
[Test] [TestMethod]
public void DisposeAllAsync_ShouldThrowArgumentNullException_WhenCalledWithNullList() public async Task DisposeAllAsync_ShouldThrowArgumentNullException_WhenCalledWithNullList()
{ {
List<IAsyncDisposable> list = null!; List<IAsyncDisposable>? list = null;
Assert.ThrowsAsync<ArgumentNullException>(() => list.DisposeAllAsync()); await Assert.ThrowsExceptionAsync<ArgumentNullException>(() => list!.DisposeAllAsync()).ConfigureAwait(false);
} }
} }
} }

View File

@ -1,33 +1,33 @@
using NUnit.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting;
using X10D.Collections; using X10D.Collections;
using X10D.Core; using X10D.Core;
namespace X10D.Tests.Collections; namespace X10D.Tests.Collections;
[TestFixture] [TestClass]
internal partial class EnumerableTests public partial class EnumerableTests
{ {
[Test] [TestMethod]
public void CountWhereNot_ShouldReturnCorrectCount_GivenSequence() public void CountWhereNot_ShouldReturnCorrectCount_GivenSequence()
{ {
var enumerable = new[] {2, 4, 6, 7, 8, 9, 10}; var enumerable = new[] {2, 4, 6, 7, 8, 9, 10};
int count = enumerable.CountWhereNot(x => x % 2 == 0); int count = enumerable.CountWhereNot(x => x % 2 == 0);
Assert.That(count, Is.EqualTo(2)); Assert.AreEqual(2, count);
} }
[Test] [TestMethod]
public void CountWhereNot_ShouldThrowArgumentNullException_GivenNullSource() public void CountWhereNot_ShouldThrowArgumentNullException_GivenNullSource()
{ {
Assert.Throws<ArgumentNullException>(() => ((IEnumerable<int>?)null)!.CountWhereNot(x => x % 2 == 0)); Assert.ThrowsException<ArgumentNullException>(() => ((IEnumerable<int>?)null)!.CountWhereNot(x => x % 2 == 0));
} }
[Test] [TestMethod]
public void CountWhereNot_ShouldThrowArgumentNullException_GivenNullPredicate() public void CountWhereNot_ShouldThrowArgumentNullException_GivenNullPredicate()
{ {
Assert.Throws<ArgumentNullException>(() => Enumerable.Empty<int>().CountWhereNot(null!)); Assert.ThrowsException<ArgumentNullException>(() => Enumerable.Empty<int>().CountWhereNot(null!));
} }
[Test] [TestMethod]
public void CountWhereNot_ShouldThrowOverflowException_GivenLargeSource() public void CountWhereNot_ShouldThrowOverflowException_GivenLargeSource()
{ {
IEnumerable<byte> GetValues() IEnumerable<byte> GetValues()
@ -40,76 +40,76 @@ internal partial class EnumerableTests
// ReSharper disable once IteratorNeverReturns // ReSharper disable once IteratorNeverReturns
} }
Assert.Throws<OverflowException>(() => _ = GetValues().CountWhereNot(x => x % 2 == 0)); Assert.ThrowsException<OverflowException>(() => GetValues().CountWhereNot(x => x % 2 == 0));
} }
[Test] [TestMethod]
public void FirstWhereNot_ShouldReturnCorrectElements_GivenSequence() public void FirstWhereNot_ShouldReturnCorrectElements_GivenSequence()
{ {
var enumerable = new[] {2, 4, 6, 7, 8, 9, 10}; var enumerable = new[] {2, 4, 6, 7, 8, 9, 10};
int result = enumerable.FirstWhereNot(x => x % 2 == 0); int result = enumerable.FirstWhereNot(x => x % 2 == 0);
Assert.That(result, Is.EqualTo(7)); Assert.AreEqual(7, result);
} }
[Test] [TestMethod]
public void FirstWhereNot_ShouldThrowArgumentNullException_GivenNullSource() public void FirstWhereNot_ShouldThrowArgumentNullException_GivenNullSource()
{ {
Assert.Throws<ArgumentNullException>(() => _ = ((IEnumerable<int>?)null)!.FirstWhereNot(x => x % 2 == 0)); Assert.ThrowsException<ArgumentNullException>(() => ((IEnumerable<int>?)null)!.FirstWhereNot(x => x % 2 == 0));
} }
[Test] [TestMethod]
public void FirstWhereNot_ShouldThrowArgumentNullException_GivenNullPredicate() public void FirstWhereNot_ShouldThrowArgumentNullException_GivenNullPredicate()
{ {
Assert.Throws<ArgumentNullException>(() => _ = Enumerable.Range(0, 1).FirstWhereNot(null!)); Assert.ThrowsException<ArgumentNullException>(() => Enumerable.Range(0, 1).FirstWhereNot(null!));
} }
[Test] [TestMethod]
public void FirstWhereNot_ShouldThrowInvalidOperationException_GivenEmptySource() public void FirstWhereNot_ShouldThrowInvalidOperationException_GivenEmptySource()
{ {
Assert.Throws<InvalidOperationException>(() => _ = Enumerable.Empty<int>().FirstWhereNot(x => x % 2 == 0)); Assert.ThrowsException<InvalidOperationException>(() => Enumerable.Empty<int>().FirstWhereNot(x => x % 2 == 0));
} }
[Test] [TestMethod]
public void FirstWhereNot_ShouldThrowInvalidOperationException_GivenSourceWithNoMatchingElements() public void FirstWhereNot_ShouldThrowInvalidOperationException_GivenSourceWithNoMatchingElements()
{ {
Assert.Throws<InvalidOperationException>(() => _ = 2.AsArrayValue().FirstWhereNot(x => x % 2 == 0)); Assert.ThrowsException<InvalidOperationException>(() => 2.AsArrayValue().FirstWhereNot(x => x % 2 == 0));
} }
[Test] [TestMethod]
public void FirstWhereNotOrDefault_ShouldReturnCorrectElements_GivenSequence() public void FirstWhereNotOrDefault_ShouldReturnCorrectElements_GivenSequence()
{ {
var enumerable = new[] {2, 4, 6, 7, 8, 9, 10}; var enumerable = new[] {2, 4, 6, 7, 8, 9, 10};
int result = enumerable.FirstWhereNotOrDefault(x => x % 2 == 0); int result = enumerable.FirstWhereNotOrDefault(x => x % 2 == 0);
Assert.That(result, Is.EqualTo(7)); Assert.AreEqual(7, result);
} }
[Test] [TestMethod]
public void FirstWhereNotOrDefault_ShouldThrowArgumentNullException_GivenNullSource() public void FirstWhereNotOrDefault_ShouldThrowArgumentNullException_GivenNullSource()
{ {
Assert.Throws<ArgumentNullException>(() => _ = ((IEnumerable<int>?)null)!.FirstWhereNotOrDefault(x => x % 2 == 0)); Assert.ThrowsException<ArgumentNullException>(() => ((IEnumerable<int>?)null)!.FirstWhereNotOrDefault(x => x % 2 == 0));
} }
[Test] [TestMethod]
public void FirstWhereNotOrDefault_ShouldThrowArgumentNullException_GivenNullPredicate() public void FirstWhereNotOrDefault_ShouldThrowArgumentNullException_GivenNullPredicate()
{ {
Assert.Throws<ArgumentNullException>(() => _ = Enumerable.Empty<int>().FirstWhereNotOrDefault(null!)); Assert.ThrowsException<ArgumentNullException>(() => Enumerable.Empty<int>().FirstWhereNotOrDefault(null!));
} }
[Test] [TestMethod]
public void FirstWhereNotOrDefault_ShouldReturnDefault_GivenEmptySource() public void FirstWhereNotOrDefault_ShouldReturnDefault_GivenEmptySource()
{ {
int result = Enumerable.Empty<int>().FirstWhereNotOrDefault(x => x % 2 == 0); int result = Enumerable.Empty<int>().FirstWhereNotOrDefault(x => x % 2 == 0);
Assert.That(result, Is.Zero); Assert.AreEqual(default, result);
} }
[Test] [TestMethod]
public void FirstWhereNotOrDefault_ShouldReturnDefault_GivenSourceWithNoMatchingElements() public void FirstWhereNotOrDefault_ShouldReturnDefault_GivenSourceWithNoMatchingElements()
{ {
int result = 2.AsArrayValue().FirstWhereNotOrDefault(x => x % 2 == 0); int result = 2.AsArrayValue().FirstWhereNotOrDefault(x => x % 2 == 0);
Assert.That(result, Is.Zero); Assert.AreEqual(default, result);
} }
[Test] [TestMethod]
public void For_ShouldTransform_GivenTransformationDelegate() public void For_ShouldTransform_GivenTransformationDelegate()
{ {
var oneToTen = new[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; var oneToTen = new[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
@ -124,21 +124,21 @@ internal partial class EnumerableTests
CollectionAssert.AreEqual(multipliedByIndex, values.ToArray()); CollectionAssert.AreEqual(multipliedByIndex, values.ToArray());
} }
[Test] [TestMethod]
public void For_ShouldThrow_GivenNullSource() public void For_ShouldThrow_GivenNullSource()
{ {
IEnumerable<object>? source = null; IEnumerable<object>? source = null;
Assert.Throws<ArgumentNullException>(() => source!.For((_, _) => { })); Assert.ThrowsException<ArgumentNullException>(() => source!.For((_, _) => { }));
} }
[Test] [TestMethod]
public void For_ShouldThrow_GivenNullAction() public void For_ShouldThrow_GivenNullAction()
{ {
IEnumerable<object> source = ArraySegment<object>.Empty; IEnumerable<object> source = ArraySegment<object>.Empty;
Assert.Throws<ArgumentNullException>(() => source.For(null!)); Assert.ThrowsException<ArgumentNullException>(() => source.For(null!));
} }
[Test] [TestMethod]
public void ForEach_ShouldTransform_GivenTransformationDelegate() public void ForEach_ShouldTransform_GivenTransformationDelegate()
{ {
var oneToTen = new[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; var oneToTen = new[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
@ -153,93 +153,93 @@ internal partial class EnumerableTests
CollectionAssert.AreEqual(oneToTenDoubled, values.ToArray()); CollectionAssert.AreEqual(oneToTenDoubled, values.ToArray());
} }
[Test] [TestMethod]
public void ForEach_ShouldThrow_GivenNullSource() public void ForEach_ShouldThrow_GivenNullSource()
{ {
IEnumerable<object>? source = null; IEnumerable<object>? source = null;
Assert.Throws<ArgumentNullException>(() => source!.ForEach(_ => { })); Assert.ThrowsException<ArgumentNullException>(() => source!.ForEach(_ => { }));
} }
[Test] [TestMethod]
public void ForEach_ShouldThrow_GivenNullAction() public void ForEach_ShouldThrow_GivenNullAction()
{ {
IEnumerable<object> source = ArraySegment<object>.Empty; IEnumerable<object> source = ArraySegment<object>.Empty;
Assert.Throws<ArgumentNullException>(() => source.ForEach(null!)); Assert.ThrowsException<ArgumentNullException>(() => source.ForEach(null!));
} }
[Test] [TestMethod]
public void LastWhereNot_ShouldReturnCorrectElements_GivenSequence() public void LastWhereNot_ShouldReturnCorrectElements_GivenSequence()
{ {
var enumerable = new[] {2, 4, 6, 7, 8, 9, 10}; var enumerable = new[] {2, 4, 6, 7, 8, 9, 10};
int result = enumerable.LastWhereNot(x => x % 2 == 0); int result = enumerable.LastWhereNot(x => x % 2 == 0);
Assert.That(result, Is.EqualTo(9)); Assert.AreEqual(9, result);
} }
[Test] [TestMethod]
public void LastWhereNot_ShouldThrowArgumentNullException_GivenNullSource() public void LastWhereNot_ShouldThrowArgumentNullException_GivenNullSource()
{ {
Assert.Throws<ArgumentNullException>(() => _ = ((IEnumerable<int>?)null)!.LastWhereNot(x => x % 2 == 0)); Assert.ThrowsException<ArgumentNullException>(() => ((IEnumerable<int>?)null)!.LastWhereNot(x => x % 2 == 0));
} }
[Test] [TestMethod]
public void LastWhereNot_ShouldThrowArgumentNullException_GivenNullPredicate() public void LastWhereNot_ShouldThrowArgumentNullException_GivenNullPredicate()
{ {
Assert.Throws<ArgumentNullException>(() => _ = Array.Empty<int>().LastWhereNot(null!)); Assert.ThrowsException<ArgumentNullException>(() => Array.Empty<int>().LastWhereNot(null!));
} }
[Test] [TestMethod]
public void LastWhereNot_ShouldThrowInvalidOperationException_GivenEmptySource() public void LastWhereNot_ShouldThrowInvalidOperationException_GivenEmptySource()
{ {
Assert.Throws<InvalidOperationException>(() => _ = Array.Empty<int>().LastWhereNot(x => x % 2 == 0)); Assert.ThrowsException<InvalidOperationException>(() => Array.Empty<int>().LastWhereNot(x => x % 2 == 0));
} }
[Test] [TestMethod]
public void LastWhereNot_ShouldThrowInvalidOperationException_GivenSourceWithNoMatchingElements() public void LastWhereNot_ShouldThrowInvalidOperationException_GivenSourceWithNoMatchingElements()
{ {
Assert.Throws<InvalidOperationException>(() => _ = 2.AsArrayValue().LastWhereNot(x => x % 2 == 0)); Assert.ThrowsException<InvalidOperationException>(() => 2.AsArrayValue().LastWhereNot(x => x % 2 == 0));
} }
[Test] [TestMethod]
public void LastWhereNotOrDefault_ShouldReturnCorrectElements_GivenSequence() public void LastWhereNotOrDefault_ShouldReturnCorrectElements_GivenSequence()
{ {
var enumerable = new[] {2, 4, 6, 7, 8, 9, 10}; var enumerable = new[] {2, 4, 6, 7, 8, 9, 10};
int result = enumerable.LastWhereNotOrDefault(x => x % 2 == 0); int result = enumerable.LastWhereNotOrDefault(x => x % 2 == 0);
Assert.That(result, Is.EqualTo(9)); Assert.AreEqual(9, result);
} }
[Test] [TestMethod]
public void LastWhereNotOrDefault_ShouldThrowArgumentNullException_GivenNullSource() public void LastWhereNotOrDefault_ShouldThrowArgumentNullException_GivenNullSource()
{ {
Assert.Throws<ArgumentNullException>(() => _ = ((IEnumerable<int>?)null)!.LastWhereNotOrDefault(x => x % 2 == 0)); Assert.ThrowsException<ArgumentNullException>(() => ((IEnumerable<int>?)null)!.LastWhereNotOrDefault(x => x % 2 == 0));
} }
[Test] [TestMethod]
public void LastWhereNotOrDefault_ShouldThrowArgumentNullException_GivenNullPredicate() public void LastWhereNotOrDefault_ShouldThrowArgumentNullException_GivenNullPredicate()
{ {
Assert.Throws<ArgumentNullException>(() => _ = Array.Empty<int>().LastWhereNotOrDefault(null!)); Assert.ThrowsException<ArgumentNullException>(() => Array.Empty<int>().LastWhereNotOrDefault(null!));
} }
[Test] [TestMethod]
public void LastWhereNotOrDefault_ShouldReturnDefault_GivenEmptySource() public void LastWhereNotOrDefault_ShouldReturnDefault_GivenEmptySource()
{ {
int result = Array.Empty<int>().LastWhereNotOrDefault(x => x % 2 == 0); int result = Array.Empty<int>().LastWhereNotOrDefault(x => x % 2 == 0);
Assert.That(result, Is.Zero); Assert.AreEqual(default, result);
} }
[Test] [TestMethod]
public void LastWhereNotOrDefault_ShouldReturnDefault_GivenSourceWithNoMatchingElements() public void LastWhereNotOrDefault_ShouldReturnDefault_GivenSourceWithNoMatchingElements()
{ {
int result = 2.AsArrayValue().LastWhereNotOrDefault(x => x % 2 == 0); int result = 2.AsArrayValue().LastWhereNotOrDefault(x => x % 2 == 0);
Assert.That(result, Is.Zero); Assert.AreEqual(default, result);
} }
[Test] [TestMethod]
public void Shuffled_ShouldThrow_GivenNull() public void Shuffled_ShouldThrow_GivenNull()
{ {
Assert.Throws<ArgumentNullException>(() => _ = ((List<int>?)null)!.Shuffled()); Assert.ThrowsException<ArgumentNullException>(() => ((List<int>?)null)!.Shuffled());
} }
[Test] [TestMethod]
public void Shuffled_ShouldReorder_GivenNotNull() public void Shuffled_ShouldReorder_GivenNotNull()
{ {
int[] array = Enumerable.Range(1, 52).ToArray(); // 52! chance of being shuffled to the same order int[] array = Enumerable.Range(1, 52).ToArray(); // 52! chance of being shuffled to the same order
@ -251,7 +251,7 @@ internal partial class EnumerableTests
CollectionAssert.AreNotEqual(array, shuffled); CollectionAssert.AreNotEqual(array, shuffled);
} }
[Test] [TestMethod]
public void WhereNot_ShouldReturnCorrectElements_GivenSequence() public void WhereNot_ShouldReturnCorrectElements_GivenSequence()
{ {
var enumerable = new[] {2, 4, 6, 7, 8, 9, 10}; var enumerable = new[] {2, 4, 6, 7, 8, 9, 10};
@ -259,19 +259,19 @@ internal partial class EnumerableTests
CollectionAssert.AreEqual(new[] {7, 9}, result.ToArray()); CollectionAssert.AreEqual(new[] {7, 9}, result.ToArray());
} }
[Test] [TestMethod]
public void WhereNot_ShouldThrowArgumentNullException_GivenNullSource() public void WhereNot_ShouldThrowArgumentNullException_GivenNullSource()
{ {
Assert.Throws<ArgumentNullException>(() => _ = ((IEnumerable<int>?)null)!.WhereNot(x => x % 2 == 0)); Assert.ThrowsException<ArgumentNullException>(() => ((IEnumerable<int>?)null)!.WhereNot(x => x % 2 == 0));
} }
[Test] [TestMethod]
public void WhereNot_ShouldThrowArgumentNullException_GivenNullPredicate() public void WhereNot_ShouldThrowArgumentNullException_GivenNullPredicate()
{ {
Assert.Throws<ArgumentNullException>(() => _ = Enumerable.Empty<int>().WhereNot(null!)); Assert.ThrowsException<ArgumentNullException>(() => Enumerable.Empty<int>().WhereNot(null!));
} }
[Test] [TestMethod]
public void WhereNotNull_ShouldContainNoNullElements() public void WhereNotNull_ShouldContainNoNullElements()
{ {
object?[] array = Enumerable.Repeat(new object(), 10).ToArray(); object?[] array = Enumerable.Repeat(new object(), 10).ToArray();
@ -289,14 +289,14 @@ internal partial class EnumerableTests
actualCount++; actualCount++;
} }
Assert.That(actualCount, Is.EqualTo(expectedCount)); Assert.AreEqual(expectedCount, actualCount);
} }
[Test] [TestMethod]
public void WhereNotNull_ShouldThrowArgumentNullException_GivenNullSource() public void WhereNotNull_ShouldThrowArgumentNullException_GivenNullSource()
{ {
IEnumerable<string> source = null!; IEnumerable<string> source = null!;
Assert.Throws<ArgumentNullException>(() => source.WhereNotNull()); Assert.ThrowsException<ArgumentNullException>(() => source.WhereNotNull());
} }
private class DummyClass private class DummyClass

View File

@ -1,133 +1,119 @@
#if NET5_0_OR_GREATER using System.Runtime.Intrinsics.X86;
using System.Runtime.Intrinsics.X86; using Microsoft.VisualStudio.TestTools.UnitTesting;
#endif
using NUnit.Framework;
using X10D.Collections; using X10D.Collections;
namespace X10D.Tests.Collections; namespace X10D.Tests.Collections;
[TestFixture] [TestClass]
internal class Int16Tests public class Int16Tests
{ {
[Test] [TestMethod]
public void Unpack_ShouldUnpackToArrayCorrectly() public void Unpack_ShouldUnpackToArrayCorrectly()
{
Assert.Multiple(() =>
{ {
const short value = 0b11010100; const short value = 0b11010100;
bool[] bits = value.Unpack(); bool[] bits = value.Unpack();
Assert.That(bits, Has.Length.EqualTo(16)); Assert.AreEqual(16, bits.Length);
Assert.That(bits[0], Is.False);
Assert.That(bits[1], Is.False); Assert.IsFalse(bits[0]);
Assert.That(bits[2], Is.True); Assert.IsFalse(bits[1]);
Assert.That(bits[3], Is.False); Assert.IsTrue(bits[2]);
Assert.That(bits[4], Is.True); Assert.IsFalse(bits[3]);
Assert.That(bits[5], Is.False); Assert.IsTrue(bits[4]);
Assert.That(bits[6], Is.True); Assert.IsFalse(bits[5]);
Assert.That(bits[7], Is.True); Assert.IsTrue(bits[6]);
Assert.IsTrue(bits[7]);
for (var index = 8; index < 16; index++) for (var index = 8; index < 16; index++)
{ {
Assert.That(bits[index], Is.False); Assert.IsFalse(bits[index]);
} }
});
} }
[Test] [TestMethod]
public void Unpack_ShouldUnpackToSpanCorrectly() public void Unpack_ShouldUnpackToSpanCorrectly()
{ {
const short value = 0b11010100; const short value = 0b11010100;
Assert.Multiple(() =>
{
Span<bool> bits = stackalloc bool[16]; Span<bool> bits = stackalloc bool[16];
value.Unpack(bits); value.Unpack(bits);
Assert.That(bits[0], Is.False); Assert.IsFalse(bits[0]);
Assert.That(bits[1], Is.False); Assert.IsFalse(bits[1]);
Assert.That(bits[2], Is.True); Assert.IsTrue(bits[2]);
Assert.That(bits[3], Is.False); Assert.IsFalse(bits[3]);
Assert.That(bits[4], Is.True); Assert.IsTrue(bits[4]);
Assert.That(bits[5], Is.False); Assert.IsFalse(bits[5]);
Assert.That(bits[6], Is.True); Assert.IsTrue(bits[6]);
Assert.That(bits[7], Is.True); Assert.IsTrue(bits[7]);
for (var index = 8; index < 16; index++) for (var index = 8; index < 16; index++)
{ {
Assert.That(bits[index], Is.False); Assert.IsFalse(bits[index]);
} }
});
} }
[Test] [TestMethod]
public void Unpack_ShouldUnpackToSpanCorrectly_GivenFallbackImplementation() public void Unpack_ShouldUnpackToSpanCorrectly_GivenFallbackImplementation()
{ {
const short value = 0b11010100; const short value = 0b11010100;
Assert.Multiple(() =>
{
Span<bool> bits = stackalloc bool[16]; Span<bool> bits = stackalloc bool[16];
value.UnpackInternal_Fallback(bits); value.UnpackInternal_Fallback(bits);
Assert.That(bits[0], Is.False); Assert.IsFalse(bits[0]);
Assert.That(bits[1], Is.False); Assert.IsFalse(bits[1]);
Assert.That(bits[2], Is.True); Assert.IsTrue(bits[2]);
Assert.That(bits[3], Is.False); Assert.IsFalse(bits[3]);
Assert.That(bits[4], Is.True); Assert.IsTrue(bits[4]);
Assert.That(bits[5], Is.False); Assert.IsFalse(bits[5]);
Assert.That(bits[6], Is.True); Assert.IsTrue(bits[6]);
Assert.That(bits[7], Is.True); Assert.IsTrue(bits[7]);
for (var index = 8; index < 16; index++) for (var index = 8; index < 16; index++)
{ {
Assert.That(bits[index], Is.False); Assert.IsFalse(bits[index]);
} }
});
} }
#if NET5_0_OR_GREATER #if NET5_0_OR_GREATER
[Test] [TestMethod]
public void UnpackInternal_Ssse3_ShouldUnpackToSpanCorrectly() public void UnpackInternal_Ssse3_ShouldUnpackToSpanCorrectly()
{ {
if (!Sse3.IsSupported) if (!Sse3.IsSupported)
{ {
Assert.Pass();
return; return;
} }
const short value = 0b11010100; const short value = 0b11010100;
Assert.Multiple(() =>
{
Span<bool> bits = stackalloc bool[16]; Span<bool> bits = stackalloc bool[16];
value.UnpackInternal_Ssse3(bits); value.UnpackInternal_Ssse3(bits);
Assert.That(bits[0], Is.False); Assert.IsFalse(bits[0]);
Assert.That(bits[1], Is.False); Assert.IsFalse(bits[1]);
Assert.That(bits[2], Is.True); Assert.IsTrue(bits[2]);
Assert.That(bits[3], Is.False); Assert.IsFalse(bits[3]);
Assert.That(bits[4], Is.True); Assert.IsTrue(bits[4]);
Assert.That(bits[5], Is.False); Assert.IsFalse(bits[5]);
Assert.That(bits[6], Is.True); Assert.IsTrue(bits[6]);
Assert.That(bits[7], Is.True); Assert.IsTrue(bits[7]);
for (var index = 8; index < 16; index++) for (var index = 8; index < 16; index++)
{ {
Assert.That(bits[index], Is.False); Assert.IsFalse(bits[index]);
} }
});
} }
#endif #endif
[Test] [TestMethod]
public void Unpack_ShouldRepackEqually() public void Unpack_ShouldRepackEqually()
{ {
const short value = 0b11010100; const short value = 0b11010100;
Assert.That(value.Unpack().PackInt16(), Is.EqualTo(value)); Assert.AreEqual(value, value.Unpack().PackInt16());
} }
[Test] [TestMethod]
public void Unpack_ShouldThrow_GivenTooSmallSpan() public void Unpack_ShouldThrow_GivenTooSmallSpan()
{ {
Assert.Throws<ArgumentException>(() => Assert.ThrowsException<ArgumentException>(() =>
{ {
const short value = 0b11010100; const short value = 0b11010100;
Span<bool> bits = stackalloc bool[0]; Span<bool> bits = stackalloc bool[0];

View File

@ -1,92 +1,81 @@
#if NET5_0_OR_GREATER using System.Runtime.Intrinsics.X86;
using System.Runtime.Intrinsics.X86; using Microsoft.VisualStudio.TestTools.UnitTesting;
#endif
using NUnit.Framework;
using X10D.Collections; using X10D.Collections;
namespace X10D.Tests.Collections; namespace X10D.Tests.Collections;
[TestFixture] [TestClass]
internal class Int32Tests public class Int32Tests
{ {
[Test] [TestMethod]
public void Unpack_ShouldUnpackToArrayCorrectly() public void Unpack_ShouldUnpackToArrayCorrectly()
{ {
const int value = 0b11010100; const int value = 0b11010100;
Assert.Multiple(() =>
{
bool[] bits = value.Unpack(); bool[] bits = value.Unpack();
Assert.That(bits, Has.Length.EqualTo(32));
Assert.That(bits[0], Is.False); Assert.AreEqual(32, bits.Length);
Assert.That(bits[1], Is.False);
Assert.That(bits[2], Is.True); Assert.IsFalse(bits[0]);
Assert.That(bits[3], Is.False); Assert.IsFalse(bits[1]);
Assert.That(bits[4], Is.True); Assert.IsTrue(bits[2]);
Assert.That(bits[5], Is.False); Assert.IsFalse(bits[3]);
Assert.That(bits[6], Is.True); Assert.IsTrue(bits[4]);
Assert.That(bits[7], Is.True); Assert.IsFalse(bits[5]);
Assert.IsTrue(bits[6]);
Assert.IsTrue(bits[7]);
for (var index = 8; index < 32; index++) for (var index = 8; index < 32; index++)
{ {
Assert.That(bits[index], Is.False); Assert.IsFalse(bits[index]);
} }
});
} }
[Test] [TestMethod]
public void Unpack_ShouldUnpackToSpanCorrectly() public void Unpack_ShouldUnpackToSpanCorrectly()
{ {
const int value = 0b11010100; const int value = 0b11010100;
Assert.Multiple(() =>
{
Span<bool> bits = stackalloc bool[32]; Span<bool> bits = stackalloc bool[32];
value.Unpack(bits); value.Unpack(bits);
Assert.That(bits[0], Is.False); Assert.IsFalse(bits[0]);
Assert.That(bits[1], Is.False); Assert.IsFalse(bits[1]);
Assert.That(bits[2], Is.True); Assert.IsTrue(bits[2]);
Assert.That(bits[3], Is.False); Assert.IsFalse(bits[3]);
Assert.That(bits[4], Is.True); Assert.IsTrue(bits[4]);
Assert.That(bits[5], Is.False); Assert.IsFalse(bits[5]);
Assert.That(bits[6], Is.True); Assert.IsTrue(bits[6]);
Assert.That(bits[7], Is.True); Assert.IsTrue(bits[7]);
for (var index = 8; index < 32; index++) for (var index = 8; index < 32; index++)
{ {
Assert.That(bits[index], Is.False); Assert.IsFalse(bits[index]);
} }
});
} }
[Test] [TestMethod]
public void UnpackInternal_Fallback_ShouldUnpackToSpanCorrectly() public void UnpackInternal_Fallback_ShouldUnpackToSpanCorrectly()
{ {
const int value = 0b11010100; const int value = 0b11010100;
Assert.Multiple(() =>
{
Span<bool> bits = stackalloc bool[32]; Span<bool> bits = stackalloc bool[32];
value.UnpackInternal_Fallback(bits); value.UnpackInternal_Fallback(bits);
Assert.That(bits[0], Is.False); Assert.IsFalse(bits[0]);
Assert.That(bits[1], Is.False); Assert.IsFalse(bits[1]);
Assert.That(bits[2], Is.True); Assert.IsTrue(bits[2]);
Assert.That(bits[3], Is.False); Assert.IsFalse(bits[3]);
Assert.That(bits[4], Is.True); Assert.IsTrue(bits[4]);
Assert.That(bits[5], Is.False); Assert.IsFalse(bits[5]);
Assert.That(bits[6], Is.True); Assert.IsTrue(bits[6]);
Assert.That(bits[7], Is.True); Assert.IsTrue(bits[7]);
for (var index = 8; index < 32; index++) for (var index = 8; index < 32; index++)
{ {
Assert.That(bits[index], Is.False); Assert.IsFalse(bits[index]);
} }
});
} }
#if NET5_0_OR_GREATER #if NET5_0_OR_GREATER
[Test] [TestMethod]
public void UnpackInternal_Ssse3_ShouldUnpackToSpanCorrectly() public void UnpackInternal_Ssse3_ShouldUnpackToSpanCorrectly()
{ {
if (!Ssse3.IsSupported) if (!Ssse3.IsSupported)
@ -95,28 +84,25 @@ internal class Int32Tests
} }
const int value = 0b11010100; const int value = 0b11010100;
Assert.Multiple(() =>
{
Span<bool> bits = stackalloc bool[32]; Span<bool> bits = stackalloc bool[32];
value.UnpackInternal_Ssse3(bits); value.UnpackInternal_Ssse3(bits);
Assert.That(bits[0], Is.False); Assert.IsFalse(bits[0]);
Assert.That(bits[1], Is.False); Assert.IsFalse(bits[1]);
Assert.That(bits[2], Is.True); Assert.IsTrue(bits[2]);
Assert.That(bits[3], Is.False); Assert.IsFalse(bits[3]);
Assert.That(bits[4], Is.True); Assert.IsTrue(bits[4]);
Assert.That(bits[5], Is.False); Assert.IsFalse(bits[5]);
Assert.That(bits[6], Is.True); Assert.IsTrue(bits[6]);
Assert.That(bits[7], Is.True); Assert.IsTrue(bits[7]);
for (var index = 8; index < 32; index++) for (var index = 8; index < 32; index++)
{ {
Assert.That(bits[index], Is.False); Assert.IsFalse(bits[index]);
} }
});
} }
[Test] [TestMethod]
public void UnpackInternal_Avx2_ShouldUnpackToSpanCorrectly() public void UnpackInternal_Avx2_ShouldUnpackToSpanCorrectly()
{ {
if (!Avx2.IsSupported) if (!Avx2.IsSupported)
@ -125,39 +111,36 @@ internal class Int32Tests
} }
const int value = 0b11010100; const int value = 0b11010100;
Assert.Multiple(() =>
{
Span<bool> bits = stackalloc bool[32]; Span<bool> bits = stackalloc bool[32];
value.UnpackInternal_Avx2(bits); value.UnpackInternal_Avx2(bits);
Assert.That(bits[0], Is.False); Assert.IsFalse(bits[0]);
Assert.That(bits[1], Is.False); Assert.IsFalse(bits[1]);
Assert.That(bits[2], Is.True); Assert.IsTrue(bits[2]);
Assert.That(bits[3], Is.False); Assert.IsFalse(bits[3]);
Assert.That(bits[4], Is.True); Assert.IsTrue(bits[4]);
Assert.That(bits[5], Is.False); Assert.IsFalse(bits[5]);
Assert.That(bits[6], Is.True); Assert.IsTrue(bits[6]);
Assert.That(bits[7], Is.True); Assert.IsTrue(bits[7]);
for (var index = 8; index < 32; index++) for (var index = 8; index < 32; index++)
{ {
Assert.That(bits[index], Is.False); Assert.IsFalse(bits[index]);
} }
});
} }
#endif #endif
[Test] [TestMethod]
public void Unpack_ShouldRepackEqually() public void Unpack_ShouldRepackEqually()
{ {
const int value = 0b11010100; const int value = 0b11010100;
Assert.That(value.Unpack().PackInt32(), Is.EqualTo(value)); Assert.AreEqual(value, value.Unpack().PackInt32());
} }
[Test] [TestMethod]
public void Unpack_ShouldThrow_GivenTooSmallSpan() public void Unpack_ShouldThrow_GivenTooSmallSpan()
{ {
Assert.Throws<ArgumentException>(() => Assert.ThrowsException<ArgumentException>(() =>
{ {
const int value = 0b11010100; const int value = 0b11010100;
Span<bool> bits = stackalloc bool[0]; Span<bool> bits = stackalloc bool[0];

View File

@ -1,74 +1,68 @@
using System.Diagnostics; using System.Diagnostics;
using System.Globalization; using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;
using X10D.Collections; using X10D.Collections;
namespace X10D.Tests.Collections; namespace X10D.Tests.Collections;
[TestFixture] [TestClass]
internal class Int64Tests public class Int64Tests
{ {
[Test] [TestMethod]
public void UnpackBits_ShouldUnpackToArrayCorrectly() public void UnpackBits_ShouldUnpackToArrayCorrectly()
{ {
bool[] bits = 0b11010100L.Unpack(); bool[] bits = 0b11010100L.Unpack();
Assert.That(bits, Has.Length.EqualTo(64)); Assert.AreEqual(64, bits.Length);
Trace.WriteLine(Convert.ToString(0b11010100L, 2)); Trace.WriteLine(Convert.ToString(0b11010100L, 2));
Trace.WriteLine(string.Join("", bits.Select(b => b ? "1" : "0"))); Trace.WriteLine(string.Join("", bits.Select(b => b ? "1" : "0")));
Assert.Multiple(() =>
{ Assert.IsFalse(bits[0]);
Assert.That(bits[0], Is.False); Assert.IsFalse(bits[1]);
Assert.That(bits[1], Is.False); Assert.IsTrue(bits[2]);
Assert.That(bits[2], Is.True); Assert.IsFalse(bits[3]);
Assert.That(bits[3], Is.False); Assert.IsTrue(bits[4]);
Assert.That(bits[4], Is.True); Assert.IsFalse(bits[5]);
Assert.That(bits[5], Is.False); Assert.IsTrue(bits[6]);
Assert.That(bits[6], Is.True); Assert.IsTrue(bits[7]);
Assert.That(bits[7], Is.True);
for (var index = 8; index < 64; index++) for (var index = 8; index < 64; index++)
{ {
Assert.That(bits[index], Is.False, index.ToString(CultureInfo.InvariantCulture)); Assert.IsFalse(bits[index], index.ToString());
} }
});
} }
[Test] [TestMethod]
public void UnpackBits_ShouldUnpackToSpanCorrectly() public void UnpackBits_ShouldUnpackToSpanCorrectly()
{
Assert.Multiple(() =>
{ {
Span<bool> bits = stackalloc bool[64]; Span<bool> bits = stackalloc bool[64];
0b11010100L.Unpack(bits); 0b11010100L.Unpack(bits);
Assert.That(bits[0], Is.False); Assert.IsFalse(bits[0]);
Assert.That(bits[1], Is.False); Assert.IsFalse(bits[1]);
Assert.That(bits[2], Is.True); Assert.IsTrue(bits[2]);
Assert.That(bits[3], Is.False); Assert.IsFalse(bits[3]);
Assert.That(bits[4], Is.True); Assert.IsTrue(bits[4]);
Assert.That(bits[5], Is.False); Assert.IsFalse(bits[5]);
Assert.That(bits[6], Is.True); Assert.IsTrue(bits[6]);
Assert.That(bits[7], Is.True); Assert.IsTrue(bits[7]);
for (var index = 8; index < 64; index++) for (var index = 8; index < 64; index++)
{ {
Assert.That(bits[index], Is.False, index.ToString(CultureInfo.InvariantCulture)); Assert.IsFalse(bits[index], index.ToString());
} }
});
} }
[Test] [TestMethod]
public void UnpackBits_ShouldRepackEqually() public void UnpackBits_ShouldRepackEqually()
{ {
Assert.That(0b11010100L.Unpack().PackInt64(), Is.EqualTo(0b11010100L)); Assert.AreEqual(0b11010100L, 0b11010100L.Unpack().PackInt64());
} }
[Test] [TestMethod]
public void UnpackBits_ShouldThrow_GivenTooSmallSpan() public void UnpackBits_ShouldThrow_GivenTooSmallSpan()
{ {
Assert.Throws<ArgumentException>(() => Assert.ThrowsException<ArgumentException>(() =>
{ {
Span<bool> bits = stackalloc bool[0]; Span<bool> bits = stackalloc bool[0];
0b11010100L.Unpack(bits); 0b11010100L.Unpack(bits);

View File

@ -1,15 +1,16 @@
using NUnit.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting;
using X10D.Collections; using X10D.Collections;
namespace X10D.Tests.Collections; namespace X10D.Tests.Collections;
[TestFixture] [TestClass]
internal class ListTests public class ListTests
{ {
[Test] [CLSCompliant(false)]
[TestCase(1)] [TestMethod]
[TestCase(1, 2, 3)] [DataRow(1)]
[TestCase(1, 2, 3, 4, 5)] [DataRow(1, 2, 3)]
[DataRow(1, 2, 3, 4, 5)]
public void Fill_ShouldGiveHomogenousList_GivenValue(params int[] args) public void Fill_ShouldGiveHomogenousList_GivenValue(params int[] args)
{ {
int[] all42 = Enumerable.Repeat(42, args.Length).ToArray(); int[] all42 = Enumerable.Repeat(42, args.Length).ToArray();
@ -25,169 +26,155 @@ internal class ListTests
CollectionAssert.AreEqual(all42, list); CollectionAssert.AreEqual(all42, list);
} }
[Test] [CLSCompliant(false)]
[TestCase(1)] [TestMethod]
[TestCase(1, 2, 3)] [DataRow(1)]
[TestCase(1, 2, 3, 4, 5)] [DataRow(1, 2, 3)]
[DataRow(1, 2, 3, 4, 5)]
public void SlicedFill_ShouldLeaveFirstElement_GivenStartIndex1(params int[] args) public void SlicedFill_ShouldLeaveFirstElement_GivenStartIndex1(params int[] args)
{ {
int first = args[0]; int first = args[0];
args.Fill(1, 1, args.Length - 1); args.Fill(1, 1, args.Length - 1);
int[] comparison = Enumerable.Repeat(1, args.Length - 1).ToArray(); int[] comparison = Enumerable.Repeat(1, args.Length - 1).ToArray();
Assert.That(args[0], Is.EqualTo(first)); Assert.AreEqual(first, args[0]);
CollectionAssert.AreEqual(comparison, args[1..]); CollectionAssert.AreEqual(comparison, args[1..]);
} }
[Test] [TestMethod]
public void Fill_ShouldThrow_GivenExceededCount() public void Fill_ShouldThrow_GivenExceededCount()
{ {
int[] array = Array.Empty<int>(); int[] array = Array.Empty<int>();
var list = new List<int>(); var list = new List<int>();
Assert.Throws<ArgumentOutOfRangeException>(() => array.Fill(0, 0, 1)); Assert.ThrowsException<ArgumentOutOfRangeException>(() => array.Fill(0, 0, 1));
Assert.Throws<ArgumentOutOfRangeException>(() => list.Fill(0, 0, 1)); Assert.ThrowsException<ArgumentOutOfRangeException>(() => list.Fill(0, 0, 1));
} }
[Test] [TestMethod]
public void Fill_ShouldThrow_GivenNegativeCount() public void Fill_ShouldThrow_GivenNegativeCount()
{ {
int[] array = Array.Empty<int>(); int[] array = Array.Empty<int>();
var list = new List<int>(); var list = new List<int>();
Assert.Throws<ArgumentOutOfRangeException>(() => array.Fill(0, 0, -1)); Assert.ThrowsException<ArgumentOutOfRangeException>(() => array.Fill(0, 0, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => list.Fill(0, 0, -1)); Assert.ThrowsException<ArgumentOutOfRangeException>(() => list.Fill(0, 0, -1));
} }
[Test] [TestMethod]
public void Fill_ShouldThrow_GivenNegativeStartIndex() public void Fill_ShouldThrow_GivenNegativeStartIndex()
{ {
int[] array = Array.Empty<int>(); int[] array = Array.Empty<int>();
var list = new List<int>(); var list = new List<int>();
Assert.Throws<ArgumentOutOfRangeException>(() => array.Fill(0, -1, 0)); Assert.ThrowsException<ArgumentOutOfRangeException>(() => array.Fill(0, -1, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => list.Fill(0, -1, 0)); Assert.ThrowsException<ArgumentOutOfRangeException>(() => list.Fill(0, -1, 0));
} }
[Test] [TestMethod]
public void Fill_ShouldThrow_GivenNull() public void Fill_ShouldThrow_GivenNull()
{ {
int[]? array = null; int[]? array = null;
List<int>? list = null; List<int>? list = null;
Assert.Throws<ArgumentNullException>(() => array!.Fill(0)); Assert.ThrowsException<ArgumentNullException>(() => array!.Fill(0));
Assert.Throws<ArgumentNullException>(() => list!.Fill(0)); Assert.ThrowsException<ArgumentNullException>(() => list!.Fill(0));
Assert.Throws<ArgumentNullException>(() => array!.Fill(0, 0, 0)); Assert.ThrowsException<ArgumentNullException>(() => array!.Fill(0, 0, 0));
Assert.Throws<ArgumentNullException>(() => list!.Fill(0, 0, 0)); Assert.ThrowsException<ArgumentNullException>(() => list!.Fill(0, 0, 0));
} }
[Test] [TestMethod]
public void IndexOf_ShouldReturnCorrectValue_FromStartOfList() public void IndexOf_ShouldReturnCorrectValue_FromStartOfList()
{ {
int[] array = {0, 1, 2, 3, 4}; int[] array = {0, 1, 2, 3, 4};
Assert.Multiple(() => Assert.AreEqual(2, array.IndexOf(2));
{ Assert.AreEqual(2, array.IndexOf(2, 0));
Assert.That(array.IndexOf(2), Is.EqualTo(2)); Assert.AreEqual(2, array.IndexOf(2, 0, 5));
Assert.That(array.IndexOf(2, 0), Is.EqualTo(2));
Assert.That(array.IndexOf(2, 0, 5), Is.EqualTo(2));
});
} }
[Test] [TestMethod]
public void IndexOf_ShouldReturnCorrectValue_GivenSubRange() public void IndexOf_ShouldReturnCorrectValue_GivenSubRange()
{ {
int[] array = {0, 1, 2, 3, 4, 0}; int[] array = {0, 1, 2, 3, 4, 0};
Assert.Multiple(() => Assert.AreEqual(0, array.IndexOf(0));
{ Assert.AreEqual(0, array.IndexOf(0, 0));
Assert.That(array.IndexOf(0), Is.Zero); Assert.AreEqual(0, array.IndexOf(0, 0, 5));
Assert.That(array.IndexOf(0, 0), Is.Zero);
Assert.That(array.IndexOf(0, 0, 5), Is.Zero);
Assert.That(array.IndexOf(0, 1), Is.EqualTo(5)); Assert.AreEqual(5, array.IndexOf(0, 1));
Assert.That(array.IndexOf(0, 1, 5), Is.EqualTo(5)); Assert.AreEqual(5, array.IndexOf(0, 1, 5));
});
} }
[Test] [TestMethod]
public void IndexOf_ShouldReturnNegative1_ForEmptyList() public void IndexOf_ShouldReturnNegative1_ForEmptyList()
{ {
int[] array = Array.Empty<int>(); int[] array = Array.Empty<int>();
Assert.Multiple(() => Assert.AreEqual(-1, array.IndexOf(0));
{ Assert.AreEqual(-1, array.IndexOf(0, 0));
Assert.That(array.IndexOf(0), Is.EqualTo(-1)); Assert.AreEqual(-1, array.IndexOf(0, 0, 0));
Assert.That(array.IndexOf(0, 0), Is.EqualTo(-1));
Assert.That(array.IndexOf(0, 0, 0), Is.EqualTo(-1));
});
} }
[Test] [TestMethod]
public void IndexOf_ShouldThrowArgumentNullException_GivenNullList() public void IndexOf_ShouldThrowArgumentNullException_GivenNullList()
{ {
int[]? array = null; int[]? array = null;
Assert.Multiple(() => Assert.ThrowsException<ArgumentNullException>(() => array!.IndexOf(0));
{ Assert.ThrowsException<ArgumentNullException>(() => array!.IndexOf(0, 0));
Assert.Throws<ArgumentNullException>(() => array!.IndexOf(0)); Assert.ThrowsException<ArgumentNullException>(() => array!.IndexOf(0, 0, 0));
Assert.Throws<ArgumentNullException>(() => array!.IndexOf(0, 0));
Assert.Throws<ArgumentNullException>(() => array!.IndexOf(0, 0, 0));
});
} }
[Test] [TestMethod]
public void IndexOf_ShouldThrowArgumentOutOfRangeException_GivenNegativeCount() public void IndexOf_ShouldThrowArgumentOutOfRangeException_GivenNegativeCount()
{ {
int[] array = Array.Empty<int>(); int[] array = Array.Empty<int>();
Assert.Throws<ArgumentOutOfRangeException>(() => array.IndexOf(0, 0, -1)); Assert.ThrowsException<ArgumentOutOfRangeException>(() => array.IndexOf(0, 0, -1));
} }
[Test] [TestMethod]
public void IndexOf_ShouldThrowArgumentOutOfRangeException_GivenNegativeStartIndex() public void IndexOf_ShouldThrowArgumentOutOfRangeException_GivenNegativeStartIndex()
{ {
int[] array = Array.Empty<int>(); int[] array = Array.Empty<int>();
Assert.Multiple(() => Assert.ThrowsException<ArgumentOutOfRangeException>(() => array.IndexOf(0, -1));
{ Assert.ThrowsException<ArgumentOutOfRangeException>(() => array.IndexOf(0, -1, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => array.IndexOf(0, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => array.IndexOf(0, -1, 0));
});
} }
[Test] [TestMethod]
public void IndexOf_ShouldThrowArgumentOutOfRangeException_GivenInvalidStartIndexCountPair() public void IndexOf_ShouldThrowArgumentOutOfRangeException_GivenInvalidStartIndexCountPair()
{ {
int[] array = {0, 1, 2}; int[] array = {0, 1, 2};
Assert.Throws<ArgumentOutOfRangeException>(() => array.IndexOf(0, 2, 4)); Assert.ThrowsException<ArgumentOutOfRangeException>(() => array.IndexOf(0, 2, 4));
} }
[Test] [TestMethod]
public void Random_ShouldReturnContainedObject_GivenNotNull() public void Random_ShouldReturnContainedObject_GivenNotNull()
{ {
var list = new List<int>(Enumerable.Range(1, 52)); // 52! chance of being shuffled to the same order var list = new List<int>(Enumerable.Range(1, 52)); // 52! chance of being shuffled to the same order
int random = list.Random(); int random = list.Random();
Assert.That(list, Does.Contain(random)); Assert.IsTrue(list.Contains(random));
} }
[Test] [TestMethod]
public void Random_ShouldThrow_GivenNull() public void Random_ShouldThrow_GivenNull()
{ {
Assert.Throws<ArgumentNullException>(() => _ = ((List<int>?)null)!.Random()); Assert.ThrowsException<ArgumentNullException>(() => ((List<int>?)null)!.Random());
} }
[Test] [TestMethod]
public void RemoveRange_ShouldThrowArgumentNullException_GivenNull() public void RemoveRange_ShouldThrowArgumentNullException_GivenNull()
{ {
Assert.Throws<ArgumentNullException>(() => ((List<int>?)null)!.RemoveRange(new Range())); Assert.ThrowsException<ArgumentNullException>(() => ((List<int>?)null)!.RemoveRange(new Range()));
} }
[Test] [TestMethod]
public void RemoveRange_ShouldThrowArgumentException_GivenEndIndexLessThanStart() public void RemoveRange_ShouldThrowArgumentException_GivenEndIndexLessThanStart()
{ {
Assert.Throws<ArgumentException>(() => new List<int>().RemoveRange(2..0)); Assert.ThrowsException<ArgumentException>(() => new List<int>().RemoveRange(2..0));
} }
[Test] [TestMethod]
public void RemoveRange_ShouldThrowArgumentOutOfRangeException_GivenEndIndexGreaterThanOrEqualToCount() public void RemoveRange_ShouldThrowArgumentOutOfRangeException_GivenEndIndexGreaterThanOrEqualToCount()
{ {
Assert.Throws<ArgumentOutOfRangeException>(() => new List<int>().RemoveRange(..0)); Assert.ThrowsException<ArgumentOutOfRangeException>(() => new List<int>().RemoveRange(..0));
Assert.Throws<ArgumentOutOfRangeException>(() => new List<int> {1}.RemoveRange(..2)); Assert.ThrowsException<ArgumentOutOfRangeException>(() => new List<int> {1}.RemoveRange(..2));
} }
[Test] [TestMethod]
public void RemoveRange_ShouldRemoveElements_GivenList() public void RemoveRange_ShouldRemoveElements_GivenList()
{ {
var list = new List<int> var list = new List<int>
@ -204,14 +191,13 @@ internal class ListTests
10 10
}; };
Assert.That(list, Has.Count.EqualTo(10)); Assert.AreEqual(10, list.Count);
list.RemoveRange(2..5); 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); CollectionAssert.AreEqual(new[] {1, 2, 7, 8, 9, 10}, list);
} }
[Test] [TestMethod]
public void Shuffle_ShouldReorder_GivenNotNull() public void Shuffle_ShouldReorder_GivenNotNull()
{ {
var list = new List<int>(Enumerable.Range(1, 52)); // 52! chance of being shuffled to the same order var list = new List<int>(Enumerable.Range(1, 52)); // 52! chance of being shuffled to the same order
@ -224,27 +210,27 @@ internal class ListTests
CollectionAssert.AreNotEqual(list, shuffled); CollectionAssert.AreNotEqual(list, shuffled);
} }
[Test] [TestMethod]
public void Shuffle_ShouldThrow_GivenNull() public void Shuffle_ShouldThrow_GivenNull()
{ {
Assert.Throws<ArgumentNullException>(() => ((List<int>?)null)!.Shuffle()); Assert.ThrowsException<ArgumentNullException>(() => ((List<int>?)null)!.Shuffle());
} }
[Test] [TestMethod]
public void Slice_ShouldReturnCorrectValue_GivenStartIndex() public void Slice_ShouldReturnCorrectValue_GivenStartIndex()
{ {
int[] array = {0, 1, 2, 3, 4, 5}; int[] array = {0, 1, 2, 3, 4, 5};
CollectionAssert.AreEqual(new[] {2, 3, 4, 5}, array.Slice(2).ToArray()); CollectionAssert.AreEqual(new[] {2, 3, 4, 5}, array.Slice(2).ToArray());
} }
[Test] [TestMethod]
public void Slice_ShouldReturnCorrectValue_GivenStartIndexAndLength() public void Slice_ShouldReturnCorrectValue_GivenStartIndexAndLength()
{ {
int[] array = {0, 1, 2, 3, 4, 5}; int[] array = {0, 1, 2, 3, 4, 5};
CollectionAssert.AreEqual(new[] {2, 3, 4}, array.Slice(2, 3).ToArray()); CollectionAssert.AreEqual(new[] {2, 3, 4}, array.Slice(2, 3).ToArray());
} }
[Test] [TestMethod]
public void Slice_ShouldReturnEmptyList_ForEmptyList() public void Slice_ShouldReturnEmptyList_ForEmptyList()
{ {
int[] array = Array.Empty<int>(); int[] array = Array.Empty<int>();
@ -252,49 +238,49 @@ internal class ListTests
CollectionAssert.AreEqual(Array.Empty<int>(), array.Slice(0, 0).ToArray()); CollectionAssert.AreEqual(Array.Empty<int>(), array.Slice(0, 0).ToArray());
} }
[Test] [TestMethod]
public void Slice_ShouldThrowArgumentNullException_GivenNullList() public void Slice_ShouldThrowArgumentNullException_GivenNullList()
{ {
int[]? array = null; int[]? array = null;
Assert.Throws<ArgumentNullException>(() => array!.Slice(0)); Assert.ThrowsException<ArgumentNullException>(() => array!.Slice(0));
Assert.Throws<ArgumentNullException>(() => array!.Slice(0, 0)); Assert.ThrowsException<ArgumentNullException>(() => array!.Slice(0, 0));
} }
[Test] [TestMethod]
public void Slice_ShouldThrowArgumentOutOfRangeException_GivenNegativeCount() public void Slice_ShouldThrowArgumentOutOfRangeException_GivenNegativeCount()
{ {
int[] array = Array.Empty<int>(); int[] array = Array.Empty<int>();
Assert.Throws<ArgumentOutOfRangeException>(() => array.Slice(0, -1)); Assert.ThrowsException<ArgumentOutOfRangeException>(() => array.Slice(0, -1));
} }
[Test] [TestMethod]
public void Slice_ShouldThrowArgumentOutOfRangeException_GivenNegativeStartIndex() public void Slice_ShouldThrowArgumentOutOfRangeException_GivenNegativeStartIndex()
{ {
int[] array = Array.Empty<int>(); int[] array = Array.Empty<int>();
Assert.Throws<ArgumentOutOfRangeException>(() => array.Slice(-1)); Assert.ThrowsException<ArgumentOutOfRangeException>(() => array.Slice(-1));
Assert.Throws<ArgumentOutOfRangeException>(() => array.Slice(-1, 0)); Assert.ThrowsException<ArgumentOutOfRangeException>(() => array.Slice(-1, 0));
} }
[Test] [TestMethod]
public void Slice_ShouldThrowArgumentOutOfRangeException_GivenInvalidStartIndexCountPair() public void Slice_ShouldThrowArgumentOutOfRangeException_GivenInvalidStartIndexCountPair()
{ {
int[] array = {0, 1, 2}; int[] array = {0, 1, 2};
Assert.Throws<ArgumentOutOfRangeException>(() => array.Slice(2, 4)); Assert.ThrowsException<ArgumentOutOfRangeException>(() => array.Slice(2, 4));
} }
[Test] [TestMethod]
public void Swap_ShouldThrowArgumentNullException_GivenNullSource() public void Swap_ShouldThrowArgumentNullException_GivenNullSource()
{ {
Assert.Throws<ArgumentNullException>(() => ((IList<int>?)null)!.Swap(new List<int>())); Assert.ThrowsException<ArgumentNullException>(() => ((IList<int>?)null)!.Swap(new List<int>()));
} }
[Test] [TestMethod]
public void Swap_ShouldThrowArgumentNullException_GivenNullTarget() public void Swap_ShouldThrowArgumentNullException_GivenNullTarget()
{ {
Assert.Throws<ArgumentNullException>(() => new List<int>().Swap(null!)); Assert.ThrowsException<ArgumentNullException>(() => new List<int>().Swap(null!));
} }
[Test] [TestMethod]
public void Swap_ShouldSwapElements_GivenMatchingElementCount() public void Swap_ShouldSwapElements_GivenMatchingElementCount()
{ {
var first = new List<int> {1, 2, 3}; var first = new List<int> {1, 2, 3};
@ -311,7 +297,7 @@ internal class ListTests
CollectionAssert.AreEqual(new[] {4, 5, 6}, second, string.Join(' ', second)); CollectionAssert.AreEqual(new[] {4, 5, 6}, second, string.Join(' ', second));
} }
[Test] [TestMethod]
public void Swap_ShouldSwapElements_GivenDifferentElementCount() public void Swap_ShouldSwapElements_GivenDifferentElementCount()
{ {
var first = new List<int> var first = new List<int>

View File

@ -1,76 +1,52 @@
using NUnit.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting;
using X10D.Collections; using X10D.Collections;
namespace X10D.Tests.Collections; namespace X10D.Tests.Collections;
[TestFixture] [TestClass]
internal class SpanTest public class SpanTest
{ {
[Test] [TestMethod]
public void Count_ShouldReturn0_GivenEmptySpan() public void Count_ShouldReturn0_GivenEmptySpan()
{ {
Span<int> span = Span<int>.Empty; Span<int> span = Span<int>.Empty;
int count = span.Count(2); int count = span.Count(2);
Assert.That(count, Is.Zero); Assert.AreEqual(0, count);
} }
[Test] [TestMethod]
public void Count_ShouldReturn0_GivenEmptyReadOnlySpan() public void Count_ShouldReturn0_GivenEmptyReadOnlySpan()
{ {
ReadOnlySpan<int> span = ReadOnlySpan<int>.Empty; ReadOnlySpan<int> span = ReadOnlySpan<int>.Empty;
int count = span.Count(2); int count = span.Count(2);
Assert.That(count, Is.Zero); Assert.AreEqual(0, count);
} }
[Test] [TestMethod]
public void Count_ShouldReturn8_GivenSpanWith8MatchingElements() public void Count_ShouldReturn8_GivenSpanWith8MatchingElements()
{ {
Span<int> span = stackalloc int[16] {1, 2, 3, 2, 5, 2, 7, 2, 9, 2, 11, 2, 13, 2, 15, 2}; Span<int> 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); int count = span.Count(2);
Assert.That(count, Is.EqualTo(8)); Assert.AreEqual(8, count);
} }
[Test] [TestMethod]
public void Count_ShouldReturn8_GivenReadOnlySpanWith8MatchingElements() public void Count_ShouldReturn8_GivenReadOnlySpanWith8MatchingElements()
{ {
ReadOnlySpan<int> span = stackalloc int[16] {1, 2, 3, 2, 5, 2, 7, 2, 9, 2, 11, 2, 13, 2, 15, 2}; ReadOnlySpan<int> 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); int count = span.Count(2);
Assert.That(count, Is.EqualTo(8)); Assert.AreEqual(8, count);
} }
[Test] [TestMethod]
public void Replace_ShouldReplaceAllElements_GivenSpanOfInt32()
{
Span<int> 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<char> 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<int> 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() public void Split_OnEmptySpan_ShouldYieldNothing_UsingCharDelimiter_GivenReadOnlySpan()
{ {
ReadOnlySpan<char> span = ReadOnlySpan<char>.Empty; ReadOnlySpan<char> span = ReadOnlySpan<char>.Empty;
@ -81,10 +57,10 @@ internal class SpanTest
index++; index++;
} }
Assert.That(index, Is.Zero); Assert.AreEqual(0, index);
} }
[Test] [TestMethod]
public void Split_OnEmptySpan_ShouldYieldNothing_UsingCharDelimiter_GivenSpan() public void Split_OnEmptySpan_ShouldYieldNothing_UsingCharDelimiter_GivenSpan()
{ {
Span<char> span = Span<char>.Empty; Span<char> span = Span<char>.Empty;
@ -95,10 +71,10 @@ internal class SpanTest
index++; index++;
} }
Assert.That(index, Is.Zero); Assert.AreEqual(0, index);
} }
[Test] [TestMethod]
public void Split_OnEmptySpan_ShouldYieldNothing_UsingStringDelimiter_GivenReadOnlySpan() public void Split_OnEmptySpan_ShouldYieldNothing_UsingStringDelimiter_GivenReadOnlySpan()
{ {
ReadOnlySpan<char> span = ReadOnlySpan<char>.Empty; ReadOnlySpan<char> span = ReadOnlySpan<char>.Empty;
@ -109,10 +85,10 @@ internal class SpanTest
index++; index++;
} }
Assert.That(index, Is.Zero); Assert.AreEqual(0, index);
} }
[Test] [TestMethod]
public void Split_OnEmptySpan_ShouldYieldNothing_UsingStringDelimiter_GivenSpan() public void Split_OnEmptySpan_ShouldYieldNothing_UsingStringDelimiter_GivenSpan()
{ {
Span<char> span = Span<char>.Empty; Span<char> span = Span<char>.Empty;
@ -123,10 +99,10 @@ internal class SpanTest
index++; index++;
} }
Assert.That(index, Is.Zero); Assert.AreEqual(0, index);
} }
[Test] [TestMethod]
public void Split_OnOneWord_ShouldYieldLength1_UsingCharDelimiter_GivenReadOnlySpan() public void Split_OnOneWord_ShouldYieldLength1_UsingCharDelimiter_GivenReadOnlySpan()
{ {
ReadOnlySpan<char> span = "Hello ".AsSpan(); ReadOnlySpan<char> span = "Hello ".AsSpan();
@ -136,16 +112,16 @@ internal class SpanTest
{ {
if (index == 0) if (index == 0)
{ {
Assert.That(subSpan.ToString(), Is.EqualTo("Hello")); Assert.AreEqual("Hello", subSpan.ToString());
} }
index++; index++;
} }
Assert.That(index, Is.EqualTo(1)); Assert.AreEqual(1, index);
} }
[Test] [TestMethod]
public void Split_OnOneWord_ShouldYieldLength1_UsingCharDelimiter_GivenSpan() public void Split_OnOneWord_ShouldYieldLength1_UsingCharDelimiter_GivenSpan()
{ {
ReadOnlySpan<char> source = "Hello ".AsSpan(); ReadOnlySpan<char> source = "Hello ".AsSpan();
@ -157,16 +133,16 @@ internal class SpanTest
{ {
if (index == 0) if (index == 0)
{ {
Assert.That(subSpan.ToString(), Is.EqualTo("Hello")); Assert.AreEqual("Hello", subSpan.ToString());
} }
index++; index++;
} }
Assert.That(index, Is.EqualTo(1)); Assert.AreEqual(1, index);
} }
[Test] [TestMethod]
public void Split_OnOneWord_ShouldYieldLength1_UsingStringDelimiter_GivenReadOnlySpan() public void Split_OnOneWord_ShouldYieldLength1_UsingStringDelimiter_GivenReadOnlySpan()
{ {
ReadOnlySpan<char> span = "Hello ".AsSpan(); ReadOnlySpan<char> span = "Hello ".AsSpan();
@ -176,16 +152,16 @@ internal class SpanTest
{ {
if (index == 0) if (index == 0)
{ {
Assert.That(subSpan.ToString(), Is.EqualTo("Hello")); Assert.AreEqual("Hello", subSpan.ToString());
} }
index++; index++;
} }
Assert.That(index, Is.EqualTo(1)); Assert.AreEqual(1, index);
} }
[Test] [TestMethod]
public void Split_OnOneWord_ShouldYieldLength1_UsingStringDelimiter_GivenSpan() public void Split_OnOneWord_ShouldYieldLength1_UsingStringDelimiter_GivenSpan()
{ {
ReadOnlySpan<char> source = "Hello ".AsSpan(); ReadOnlySpan<char> source = "Hello ".AsSpan();
@ -197,16 +173,16 @@ internal class SpanTest
{ {
if (index == 0) if (index == 0)
{ {
Assert.That(subSpan.ToString(), Is.EqualTo("Hello")); Assert.AreEqual("Hello", subSpan.ToString());
} }
index++; index++;
} }
Assert.That(index, Is.EqualTo(1)); Assert.AreEqual(1, index);
} }
[Test] [TestMethod]
public void Split_OnOneWordWithoutDelimiter_ShouldYieldLength1_UsingCharDelimiter_GivenReadOnlySpan() public void Split_OnOneWordWithoutDelimiter_ShouldYieldLength1_UsingCharDelimiter_GivenReadOnlySpan()
{ {
ReadOnlySpan<char> span = "Hello".AsSpan(); ReadOnlySpan<char> span = "Hello".AsSpan();
@ -216,16 +192,16 @@ internal class SpanTest
{ {
if (index == 0) if (index == 0)
{ {
Assert.That(subSpan.ToString(), Is.EqualTo("Hello")); Assert.AreEqual("Hello", subSpan.ToString());
} }
index++; index++;
} }
Assert.That(index, Is.EqualTo(1)); Assert.AreEqual(1, index);
} }
[Test] [TestMethod]
public void Split_OnOneWordWithoutDelimiter_ShouldYieldLength1_UsingCharDelimiter_GivenSpan() public void Split_OnOneWordWithoutDelimiter_ShouldYieldLength1_UsingCharDelimiter_GivenSpan()
{ {
ReadOnlySpan<char> source = "Hello".AsSpan(); ReadOnlySpan<char> source = "Hello".AsSpan();
@ -237,16 +213,16 @@ internal class SpanTest
{ {
if (index == 0) if (index == 0)
{ {
Assert.That(subSpan.ToString(), Is.EqualTo("Hello")); Assert.AreEqual("Hello", subSpan.ToString());
} }
index++; index++;
} }
Assert.That(index, Is.EqualTo(1)); Assert.AreEqual(1, index);
} }
[Test] [TestMethod]
public void Split_OnOneWordWithoutDelimiter_ShouldYieldLength1_UsingStringDelimiter_GivenReadOnlySpan() public void Split_OnOneWordWithoutDelimiter_ShouldYieldLength1_UsingStringDelimiter_GivenReadOnlySpan()
{ {
ReadOnlySpan<char> span = "Hello".AsSpan(); ReadOnlySpan<char> span = "Hello".AsSpan();
@ -256,16 +232,16 @@ internal class SpanTest
{ {
if (index == 0) if (index == 0)
{ {
Assert.That(subSpan.ToString(), Is.EqualTo("Hello")); Assert.AreEqual("Hello", subSpan.ToString());
} }
index++; index++;
} }
Assert.That(index, Is.EqualTo(1)); Assert.AreEqual(1, index);
} }
[Test] [TestMethod]
public void Split_OnOneWordWithoutDelimiter_ShouldYieldLength1_UsingStringDelimiter_GivenSpan() public void Split_OnOneWordWithoutDelimiter_ShouldYieldLength1_UsingStringDelimiter_GivenSpan()
{ {
ReadOnlySpan<char> source = "Hello".AsSpan(); ReadOnlySpan<char> source = "Hello".AsSpan();
@ -277,16 +253,16 @@ internal class SpanTest
{ {
if (index == 0) if (index == 0)
{ {
Assert.That(subSpan.ToString(), Is.EqualTo("Hello")); Assert.AreEqual("Hello", subSpan.ToString());
} }
index++; index++;
} }
Assert.That(index, Is.EqualTo(1)); Assert.AreEqual(1, index);
} }
[Test] [TestMethod]
public void Split_OnTwoWords_ShouldYieldLength2_UsingCharDelimiter_GivenReadOnlySpan() public void Split_OnTwoWords_ShouldYieldLength2_UsingCharDelimiter_GivenReadOnlySpan()
{ {
ReadOnlySpan<char> span = "Hello World ".AsSpan(); ReadOnlySpan<char> span = "Hello World ".AsSpan();
@ -297,20 +273,20 @@ internal class SpanTest
switch (index) switch (index)
{ {
case 0: case 0:
Assert.That(subSpan.ToString(), Is.EqualTo("Hello")); Assert.AreEqual("Hello", subSpan.ToString());
break; break;
case 1: case 1:
Assert.That(subSpan.ToString(), Is.EqualTo("World")); Assert.AreEqual("World", subSpan.ToString());
break; break;
} }
index++; index++;
} }
Assert.That(index, Is.EqualTo(2)); Assert.AreEqual(2, index);
} }
[Test] [TestMethod]
public void Split_OnTwoWords_ShouldYieldLength2_UsingCharDelimiter_GivenSpan() public void Split_OnTwoWords_ShouldYieldLength2_UsingCharDelimiter_GivenSpan()
{ {
ReadOnlySpan<char> source = "Hello World ".AsSpan(); ReadOnlySpan<char> source = "Hello World ".AsSpan();
@ -323,20 +299,20 @@ internal class SpanTest
switch (index) switch (index)
{ {
case 0: case 0:
Assert.That(subSpan.ToString(), Is.EqualTo("Hello")); Assert.AreEqual("Hello", subSpan.ToString());
break; break;
case 1: case 1:
Assert.That(subSpan.ToString(), Is.EqualTo("World")); Assert.AreEqual("World", subSpan.ToString());
break; break;
} }
index++; index++;
} }
Assert.That(index, Is.EqualTo(2)); Assert.AreEqual(2, index);
} }
[Test] [TestMethod]
public void Split_OnTwoWords_ShouldYieldLength2_UsingStringDelimiter_GivenReadOnlySpan() public void Split_OnTwoWords_ShouldYieldLength2_UsingStringDelimiter_GivenReadOnlySpan()
{ {
ReadOnlySpan<char> span = "Hello World ".AsSpan(); ReadOnlySpan<char> span = "Hello World ".AsSpan();
@ -347,20 +323,20 @@ internal class SpanTest
switch (index) switch (index)
{ {
case 0: case 0:
Assert.That(subSpan.ToString(), Is.EqualTo("Hello")); Assert.AreEqual("Hello", subSpan.ToString());
break; break;
case 1: case 1:
Assert.That(subSpan.ToString(), Is.EqualTo("World")); Assert.AreEqual("World", subSpan.ToString());
break; break;
} }
index++; index++;
} }
Assert.That(index, Is.EqualTo(2)); Assert.AreEqual(2, index);
} }
[Test] [TestMethod]
public void Split_OnTwoWords_ShouldYieldLength2_UsingStringDelimiter_GivenSpan() public void Split_OnTwoWords_ShouldYieldLength2_UsingStringDelimiter_GivenSpan()
{ {
ReadOnlySpan<char> source = "Hello World ".AsSpan(); ReadOnlySpan<char> source = "Hello World ".AsSpan();
@ -373,20 +349,20 @@ internal class SpanTest
switch (index) switch (index)
{ {
case 0: case 0:
Assert.That(subSpan.ToString(), Is.EqualTo("Hello")); Assert.AreEqual("Hello", subSpan.ToString());
break; break;
case 1: case 1:
Assert.That(subSpan.ToString(), Is.EqualTo("World")); Assert.AreEqual("World", subSpan.ToString());
break; break;
} }
index++; index++;
} }
Assert.That(index, Is.EqualTo(2)); Assert.AreEqual(2, index);
} }
[Test] [TestMethod]
public void Split_OnThreeWords_ShouldYieldLength3_UsingCharDelimiter_GivenReadOnlySpan() public void Split_OnThreeWords_ShouldYieldLength3_UsingCharDelimiter_GivenReadOnlySpan()
{ {
ReadOnlySpan<char> span = "Hello, the World ".AsSpan(); ReadOnlySpan<char> span = "Hello, the World ".AsSpan();
@ -397,23 +373,23 @@ internal class SpanTest
switch (index) switch (index)
{ {
case 0: case 0:
Assert.That(subSpan.ToString(), Is.EqualTo("Hello,")); Assert.AreEqual("Hello,", subSpan.ToString());
break; break;
case 1: case 1:
Assert.That(subSpan.ToString(), Is.EqualTo("the")); Assert.AreEqual("the", subSpan.ToString());
break; break;
case 2: case 2:
Assert.That(subSpan.ToString(), Is.EqualTo("World")); Assert.AreEqual("World", subSpan.ToString());
break; break;
} }
index++; index++;
} }
Assert.That(index, Is.EqualTo(3)); Assert.AreEqual(3, index);
} }
[Test] [TestMethod]
public void Split_OnThreeWords_ShouldYieldLength3_UsingCharDelimiter_GivenSpan() public void Split_OnThreeWords_ShouldYieldLength3_UsingCharDelimiter_GivenSpan()
{ {
ReadOnlySpan<char> source = "Hello, the World ".AsSpan(); ReadOnlySpan<char> source = "Hello, the World ".AsSpan();
@ -426,23 +402,23 @@ internal class SpanTest
switch (index) switch (index)
{ {
case 0: case 0:
Assert.That(subSpan.ToString(), Is.EqualTo("Hello,")); Assert.AreEqual("Hello,", subSpan.ToString());
break; break;
case 1: case 1:
Assert.That(subSpan.ToString(), Is.EqualTo("the")); Assert.AreEqual("the", subSpan.ToString());
break; break;
case 2: case 2:
Assert.That(subSpan.ToString(), Is.EqualTo("World")); Assert.AreEqual("World", subSpan.ToString());
break; break;
} }
index++; index++;
} }
Assert.That(index, Is.EqualTo(3)); Assert.AreEqual(3, index);
} }
[Test] [TestMethod]
public void Split_OnThreeWords_ShouldYieldLength3_UsingStringDelimiter_GivenReadOnlySpan() public void Split_OnThreeWords_ShouldYieldLength3_UsingStringDelimiter_GivenReadOnlySpan()
{ {
ReadOnlySpan<char> span = "Hello, the World ".AsSpan(); ReadOnlySpan<char> span = "Hello, the World ".AsSpan();
@ -453,23 +429,23 @@ internal class SpanTest
switch (index) switch (index)
{ {
case 0: case 0:
Assert.That(subSpan.ToString(), Is.EqualTo("Hello,")); Assert.AreEqual("Hello,", subSpan.ToString());
break; break;
case 1: case 1:
Assert.That(subSpan.ToString(), Is.EqualTo("the")); Assert.AreEqual("the", subSpan.ToString());
break; break;
case 2: case 2:
Assert.That(subSpan.ToString(), Is.EqualTo("World")); Assert.AreEqual("World", subSpan.ToString());
break; break;
} }
index++; index++;
} }
Assert.That(index, Is.EqualTo(3)); Assert.AreEqual(3, index);
} }
[Test] [TestMethod]
public void Split_OnThreeWords_ShouldYieldLength3_UsingStringDelimiter_GivenSpan() public void Split_OnThreeWords_ShouldYieldLength3_UsingStringDelimiter_GivenSpan()
{ {
ReadOnlySpan<char> source = "Hello, the World ".AsSpan(); ReadOnlySpan<char> source = "Hello, the World ".AsSpan();
@ -482,19 +458,19 @@ internal class SpanTest
switch (index) switch (index)
{ {
case 0: case 0:
Assert.That(subSpan.ToString(), Is.EqualTo("Hello,")); Assert.AreEqual("Hello,", subSpan.ToString());
break; break;
case 1: case 1:
Assert.That(subSpan.ToString(), Is.EqualTo("the")); Assert.AreEqual("the", subSpan.ToString());
break; break;
case 2: case 2:
Assert.That(subSpan.ToString(), Is.EqualTo("World")); Assert.AreEqual("World", subSpan.ToString());
break; break;
} }
index++; index++;
} }
Assert.That(index, Is.EqualTo(3)); Assert.AreEqual(3, index);
} }
} }

View File

@ -1,78 +1,76 @@
using NUnit.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting;
using X10D.Core; using X10D.Core;
namespace X10D.Tests.Core; namespace X10D.Tests.Core;
[TestFixture] [TestClass]
internal class CoreTests public class CoreTests
{ {
[Test] [TestMethod]
[TestCase(1)] [DataRow(1)]
[TestCase("f")] [DataRow("f")]
[TestCase(true)] [DataRow(true)]
public void AsArrayValue_ShouldBeLength1_GivenValue(object o) public void AsArrayValue_ShouldBeLength1_GivenValue(object o)
{ {
object[] array = o.AsArrayValue(); object[] array = o.AsArrayValue()!;
Assert.That(array, Is.Not.Null); Assert.IsNotNull(array);
Assert.That(array, Has.Length.EqualTo(1)); Assert.IsTrue(array.Length == 1);
} }
[Test] [TestMethod]
[TestCase(1)] [DataRow(1)]
[TestCase("f")] [DataRow("f")]
[TestCase(true)] [DataRow(true)]
public void AsArrayValue_ShouldContainValue_Given_Value(object o) public void AsArrayValue_ShouldContainValue_Given_Value(object o)
{ {
object[] array = o.AsArrayValue(); object[] array = o.AsArrayValue()!;
Assert.That(array, Is.Not.Null); Assert.IsNotNull(array);
Assert.That(array[0], Is.EqualTo(o)); Assert.AreEqual(o, array[0]);
} }
[Test] [TestMethod]
[TestCase(1)] [DataRow(1)]
[TestCase("f")] [DataRow("f")]
[TestCase(true)] [DataRow(true)]
public void AsEnumerableValue_ShouldBeLength1_GivenValue(object o) public void AsEnumerableValue_ShouldBeLength1_GivenValue(object o)
{ {
object[] enumerable = o.AsEnumerableValue().ToArray(); IEnumerable<object> enumerable = o.AsEnumerableValue()!;
Assert.That(enumerable, Is.Not.Null); Assert.IsNotNull(enumerable);
Assert.That(enumerable, Has.Length.EqualTo(1)); Assert.IsTrue(enumerable.Count() == 1);
} }
[Test] [TestMethod]
[TestCase(1)] [DataRow(1)]
[TestCase("f")] [DataRow("f")]
[TestCase(true)] [DataRow(true)]
public void AsEnumerableValue_ShouldContainValue_Given_Value(object o) public void AsEnumerableValue_ShouldContainValue_Given_Value(object o)
{ {
object[] enumerable = o.AsEnumerableValue().ToArray(); IEnumerable<object> enumerable = o.AsEnumerableValue()!;
Assert.That(enumerable, Is.Not.Null); Assert.IsNotNull(enumerable);
Assert.That(enumerable.ElementAt(0), Is.EqualTo(o)); Assert.AreEqual(o, enumerable.ElementAt(0));
} }
[Test] [TestMethod]
[TestCase(1)] [DataRow(1)]
[TestCase("f")] [DataRow("f")]
[TestCase(true)] [DataRow(true)]
public void RepeatValue_ShouldContainRepeatedValue_GivenValue(object o) public void RepeatValue_ShouldContainRepeatedValue_GivenValue(object o)
{ {
IEnumerable<object> enumerable = o.RepeatValue(10); IEnumerable<object> enumerable = o.RepeatValue(10);
// ReSharper disable once PossibleMultipleEnumeration Assert.IsNotNull(enumerable);
Assert.That(enumerable, Is.Not.Null);
// ReSharper disable once PossibleMultipleEnumeration
object[] array = enumerable.ToArray(); object[] array = enumerable.ToArray();
Assert.That(array, Has.Length.EqualTo(10)); Assert.AreEqual(10, array.Length);
CollectionAssert.AreEqual(new[] {o, o, o, o, o, o, o, o, o, o}, array); CollectionAssert.AreEqual(new[] {o, o, o, o, o, o, o, o, o, o}, array);
} }
[Test] [TestMethod]
[TestCase(1)] [DataRow(1)]
[TestCase("f")] [DataRow("f")]
[TestCase(true)] [DataRow(true)]
public void RepeatValue_ShouldThrow_GivenNegativeCount(object o) public void RepeatValue_ShouldThrow_GivenNegativeCount(object o)
{ {
// we must force enumeration via ToArray() to ensure the exception is thrown // we must force enumeration via ToArray() to ensure the exception is thrown
Assert.Throws<ArgumentOutOfRangeException>(() => _ = o.RepeatValue(-1).ToArray()); Assert.ThrowsException<ArgumentOutOfRangeException>(() => o.RepeatValue(-1).ToArray());
} }
} }

View File

@ -1,10 +1,10 @@
using NUnit.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting;
using X10D.Core; using X10D.Core;
namespace X10D.Tests.Core; namespace X10D.Tests.Core;
[TestFixture] [TestClass]
internal class EnumTests public class EnumTests
{ {
// Microsoft wrongfully decided to have Sunday be 0, Monday be 1, etc. // 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. // I personally hate this, Sunday is not the first day of the week.
@ -12,63 +12,51 @@ internal class EnumTests
// but Microsoft can't fix this without breaking compatibility. // but Microsoft can't fix this without breaking compatibility.
// I have feelings... // I have feelings...
[Test] [TestMethod]
public void Next() public void Next()
{ {
Assert.Multiple(() => Assert.AreEqual(DayOfWeek.Monday, DayOfWeek.Sunday.Next());
{ Assert.AreEqual(DayOfWeek.Tuesday, DayOfWeek.Monday.Next());
Assert.That(DayOfWeek.Sunday.Next(), Is.EqualTo(DayOfWeek.Monday)); Assert.AreEqual(DayOfWeek.Wednesday, DayOfWeek.Tuesday.Next());
Assert.That(DayOfWeek.Monday.Next(), Is.EqualTo(DayOfWeek.Tuesday)); Assert.AreEqual(DayOfWeek.Thursday, DayOfWeek.Wednesday.Next());
Assert.That(DayOfWeek.Tuesday.Next(), Is.EqualTo(DayOfWeek.Wednesday)); Assert.AreEqual(DayOfWeek.Friday, DayOfWeek.Thursday.Next());
Assert.That(DayOfWeek.Wednesday.Next(), Is.EqualTo(DayOfWeek.Thursday)); Assert.AreEqual(DayOfWeek.Saturday, DayOfWeek.Friday.Next());
Assert.That(DayOfWeek.Thursday.Next(), Is.EqualTo(DayOfWeek.Friday)); Assert.AreEqual(DayOfWeek.Sunday, DayOfWeek.Saturday.Next()); // Saturday is the "last" day. wrap to "first"
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"
});
} }
[Test] [TestMethod]
public void NextUnchecked() public void NextUnchecked()
{ {
Assert.Multiple(() => Assert.AreEqual(DayOfWeek.Monday, DayOfWeek.Sunday.NextUnchecked());
{ Assert.AreEqual(DayOfWeek.Tuesday, DayOfWeek.Monday.NextUnchecked());
Assert.That(DayOfWeek.Sunday.NextUnchecked(), Is.EqualTo(DayOfWeek.Monday)); Assert.AreEqual(DayOfWeek.Wednesday, DayOfWeek.Tuesday.NextUnchecked());
Assert.That(DayOfWeek.Monday.NextUnchecked(), Is.EqualTo(DayOfWeek.Tuesday)); Assert.AreEqual(DayOfWeek.Thursday, DayOfWeek.Wednesday.NextUnchecked());
Assert.That(DayOfWeek.Tuesday.NextUnchecked(), Is.EqualTo(DayOfWeek.Wednesday)); Assert.AreEqual(DayOfWeek.Friday, DayOfWeek.Thursday.NextUnchecked());
Assert.That(DayOfWeek.Wednesday.NextUnchecked(), Is.EqualTo(DayOfWeek.Thursday)); Assert.AreEqual(DayOfWeek.Saturday, DayOfWeek.Friday.NextUnchecked());
Assert.That(DayOfWeek.Thursday.NextUnchecked(), Is.EqualTo(DayOfWeek.Friday)); Assert.ThrowsException<IndexOutOfRangeException>(() => DayOfWeek.Saturday.NextUnchecked());
Assert.That(DayOfWeek.Friday.NextUnchecked(), Is.EqualTo(DayOfWeek.Saturday));
});
Assert.Throws<IndexOutOfRangeException>(() => _ = DayOfWeek.Saturday.NextUnchecked());
} }
[Test] [TestMethod]
public void Previous() public void Previous()
{ {
Assert.Multiple(() => Assert.AreEqual(DayOfWeek.Saturday, DayOfWeek.Sunday.Previous()); // Sunday is the "first" day. wrap to "last"
{ Assert.AreEqual(DayOfWeek.Sunday, DayOfWeek.Monday.Previous());
Assert.That(DayOfWeek.Sunday.Previous(), Is.EqualTo(DayOfWeek.Saturday)); // Sunday is the "first" day. wrap to "last" Assert.AreEqual(DayOfWeek.Monday, DayOfWeek.Tuesday.Previous());
Assert.That(DayOfWeek.Monday.Previous(), Is.EqualTo(DayOfWeek.Sunday)); Assert.AreEqual(DayOfWeek.Tuesday, DayOfWeek.Wednesday.Previous());
Assert.That(DayOfWeek.Tuesday.Previous(), Is.EqualTo(DayOfWeek.Monday)); Assert.AreEqual(DayOfWeek.Wednesday, DayOfWeek.Thursday.Previous());
Assert.That(DayOfWeek.Wednesday.Previous(), Is.EqualTo(DayOfWeek.Tuesday)); Assert.AreEqual(DayOfWeek.Thursday, DayOfWeek.Friday.Previous());
Assert.That(DayOfWeek.Thursday.Previous(), Is.EqualTo(DayOfWeek.Wednesday)); Assert.AreEqual(DayOfWeek.Friday, DayOfWeek.Saturday.Previous());
Assert.That(DayOfWeek.Friday.Previous(), Is.EqualTo(DayOfWeek.Thursday));
Assert.That(DayOfWeek.Saturday.Previous(), Is.EqualTo(DayOfWeek.Friday));
});
} }
[Test] [TestMethod]
public void PreviousUnchecked() public void PreviousUnchecked()
{ {
Assert.Multiple(() => Assert.AreEqual(DayOfWeek.Sunday, DayOfWeek.Monday.PreviousUnchecked());
{ Assert.AreEqual(DayOfWeek.Monday, DayOfWeek.Tuesday.PreviousUnchecked());
Assert.That(DayOfWeek.Monday.PreviousUnchecked(), Is.EqualTo(DayOfWeek.Sunday)); Assert.AreEqual(DayOfWeek.Tuesday, DayOfWeek.Wednesday.PreviousUnchecked());
Assert.That(DayOfWeek.Tuesday.PreviousUnchecked(), Is.EqualTo(DayOfWeek.Monday)); Assert.AreEqual(DayOfWeek.Wednesday, DayOfWeek.Thursday.PreviousUnchecked());
Assert.That(DayOfWeek.Wednesday.PreviousUnchecked(), Is.EqualTo(DayOfWeek.Tuesday)); Assert.AreEqual(DayOfWeek.Thursday, DayOfWeek.Friday.PreviousUnchecked());
Assert.That(DayOfWeek.Thursday.PreviousUnchecked(), Is.EqualTo(DayOfWeek.Wednesday)); Assert.AreEqual(DayOfWeek.Friday, DayOfWeek.Saturday.PreviousUnchecked());
Assert.That(DayOfWeek.Friday.PreviousUnchecked(), Is.EqualTo(DayOfWeek.Thursday)); Assert.ThrowsException<IndexOutOfRangeException>(() => DayOfWeek.Sunday.PreviousUnchecked());
Assert.That(DayOfWeek.Saturday.PreviousUnchecked(), Is.EqualTo(DayOfWeek.Friday));
});
Assert.Throws<IndexOutOfRangeException>(() => _ = DayOfWeek.Sunday.PreviousUnchecked());
} }
} }

View File

@ -1,15 +1,15 @@
#if NET6_0_OR_GREATER #if NET6_0_OR_GREATER
using System.Runtime.Intrinsics; using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86; using System.Runtime.Intrinsics.X86;
using NUnit.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting;
using X10D.Core; using X10D.Core;
namespace X10D.Tests.Core; namespace X10D.Tests.Core;
[TestFixture] [TestClass]
internal class IntrinsicTests public class IntrinsicTests
{ {
[Test] [TestMethod]
public void CorrectBoolean_ShouldReturnExpectedVector64Result_GivenInputVector() public void CorrectBoolean_ShouldReturnExpectedVector64Result_GivenInputVector()
{ {
var inputVector = Vector64.Create(0, 1, 2, 0, 3, 0, 0, (byte)4); var inputVector = Vector64.Create(0, 1, 2, 0, 3, 0, 0, (byte)4);
@ -17,10 +17,10 @@ internal class IntrinsicTests
Vector64<byte> result = inputVector.CorrectBoolean(); Vector64<byte> result = inputVector.CorrectBoolean();
Assert.That(result, Is.EqualTo(expectedResult)); Assert.AreEqual(expectedResult, result);
} }
[Test] [TestMethod]
public void CorrectBooleanInternal_Fallback_ShouldReturnExpectedVector128Result_GivenInputVector() 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); 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 @@ internal class IntrinsicTests
Vector128<byte> result = inputVector.CorrectBooleanInternal_Fallback(); Vector128<byte> result = inputVector.CorrectBooleanInternal_Fallback();
Assert.That(result, Is.EqualTo(expectedResult)); Assert.AreEqual(expectedResult, result);
} }
[Test] [TestMethod]
public void CorrectBooleanInternal_Sse2_ShouldReturnExpectedVector128Result_GivenInputVector() public void CorrectBooleanInternal_Sse2_ShouldReturnExpectedVector128Result_GivenInputVector()
{ {
if (!Sse2.IsSupported) if (!Sse2.IsSupported)
@ -44,10 +44,10 @@ internal class IntrinsicTests
Vector128<byte> result = inputVector.CorrectBooleanInternal_Sse2(); Vector128<byte> result = inputVector.CorrectBooleanInternal_Sse2();
Assert.That(result, Is.EqualTo(expectedResult)); Assert.AreEqual(expectedResult, result);
} }
[Test] [TestMethod]
public void CorrectBooleanInternal_Avx2_ShouldReturnExpectedVector256Result_GivenInputVector() public void CorrectBooleanInternal_Avx2_ShouldReturnExpectedVector256Result_GivenInputVector()
{ {
if (!Avx2.IsSupported) if (!Avx2.IsSupported)
@ -62,10 +62,10 @@ internal class IntrinsicTests
Vector256<byte> result = inputVector.CorrectBooleanInternal_Avx2(); Vector256<byte> result = inputVector.CorrectBooleanInternal_Avx2();
Assert.That(result, Is.EqualTo(expectedResult)); Assert.AreEqual(expectedResult, result);
} }
[Test] [TestMethod]
public void CorrectBooleanInternal_Fallback_ShouldReturnExpectedVector256Result_GivenInputVector() 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, 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 @@ internal class IntrinsicTests
Vector256<byte> result = inputVector.CorrectBooleanInternal_Fallback(); Vector256<byte> result = inputVector.CorrectBooleanInternal_Fallback();
Assert.That(result, Is.EqualTo(expectedResult)); Assert.AreEqual(expectedResult, result);
} }
[Test] [TestMethod]
public void HorizontalOr_ShouldReturnCombinedVector_GivenInputVector128OfUInt32() public void HorizontalOr_ShouldReturnCombinedVector_GivenInputVector128OfUInt32()
{ {
Vector128<uint> left = Vector128.Create(1U, 2U, 3U, 4U); Vector128<uint> left = Vector128.Create(1U, 2U, 3U, 4U);
@ -87,10 +87,10 @@ internal class IntrinsicTests
Vector128<uint> expected = Vector128.Create(3U, 7U, 7U, 15U); Vector128<uint> expected = Vector128.Create(3U, 7U, 7U, 15U);
Vector128<uint> actual = IntrinsicUtility.HorizontalOr(left, right); Vector128<uint> actual = IntrinsicUtility.HorizontalOr(left, right);
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
[Test] [TestMethod]
public void HorizontalOrInternal_Sse_ShouldReturnCombinedVector_GivenInputVector128OfInt32() public void HorizontalOrInternal_Sse_ShouldReturnCombinedVector_GivenInputVector128OfInt32()
{ {
Vector128<int> left = Vector128.Create(1, 2, 3, 4); Vector128<int> left = Vector128.Create(1, 2, 3, 4);
@ -99,10 +99,10 @@ internal class IntrinsicTests
Vector128<int> expected = Vector128.Create(3, 7, 7, 15); Vector128<int> expected = Vector128.Create(3, 7, 7, 15);
Vector128<int> actual = IntrinsicUtility.HorizontalOr_Sse(left, right); Vector128<int> actual = IntrinsicUtility.HorizontalOr_Sse(left, right);
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
[Test] [TestMethod]
public void HorizontalOrInternal_Fallback_ShouldReturnCombinedVector_GivenInputVector128OfInt32() public void HorizontalOrInternal_Fallback_ShouldReturnCombinedVector_GivenInputVector128OfInt32()
{ {
Vector128<int> left = Vector128.Create(1, 2, 3, 4); Vector128<int> left = Vector128.Create(1, 2, 3, 4);
@ -111,10 +111,10 @@ internal class IntrinsicTests
Vector128<int> expected = Vector128.Create(3, 7, 7, 15); Vector128<int> expected = Vector128.Create(3, 7, 7, 15);
Vector128<int> actual = IntrinsicUtility.HorizontalOrInternal_Fallback(left, right); Vector128<int> actual = IntrinsicUtility.HorizontalOrInternal_Fallback(left, right);
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
[Test] [TestMethod]
public void Multiply_ShouldReturnMultipliedVector_GivenInputVector128OfInt64() public void Multiply_ShouldReturnMultipliedVector_GivenInputVector128OfInt64()
{ {
Vector128<long> left = Vector128.Create(6L, 4L); Vector128<long> left = Vector128.Create(6L, 4L);
@ -123,10 +123,10 @@ internal class IntrinsicTests
Vector128<long> expected = Vector128.Create(12L, 12L); Vector128<long> expected = Vector128.Create(12L, 12L);
Vector128<long> actual = IntrinsicUtility.Multiply(left, right); Vector128<long> actual = IntrinsicUtility.Multiply(left, right);
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
[Test] [TestMethod]
public void MultiplyInternal_Sse2_ShouldReturnMultipliedVector_GivenInputVector128OfUInt64() public void MultiplyInternal_Sse2_ShouldReturnMultipliedVector_GivenInputVector128OfUInt64()
{ {
if (!Sse2.IsSupported) if (!Sse2.IsSupported)
@ -140,10 +140,10 @@ internal class IntrinsicTests
Vector128<ulong> expected = Vector128.Create(12UL, 12UL); Vector128<ulong> expected = Vector128.Create(12UL, 12UL);
Vector128<ulong> actual = IntrinsicUtility.MultiplyInternal_Sse2(left, right); Vector128<ulong> actual = IntrinsicUtility.MultiplyInternal_Sse2(left, right);
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
[Test] [TestMethod]
public void MultiplyInternal_Fallback_ShouldReturnMultipliedVector_GivenInputVector128OfUInt64() public void MultiplyInternal_Fallback_ShouldReturnMultipliedVector_GivenInputVector128OfUInt64()
{ {
Vector128<ulong> left = Vector128.Create(6UL, 4UL); Vector128<ulong> left = Vector128.Create(6UL, 4UL);
@ -152,10 +152,10 @@ internal class IntrinsicTests
Vector128<ulong> expected = Vector128.Create(12UL, 12UL); Vector128<ulong> expected = Vector128.Create(12UL, 12UL);
Vector128<ulong> actual = IntrinsicUtility.MultiplyInternal_Fallback(left, right); Vector128<ulong> actual = IntrinsicUtility.MultiplyInternal_Fallback(left, right);
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
[Test] [TestMethod]
public void Multiply_ShouldReturnMultipliedVector_GivenInputVector256OfInt64() public void Multiply_ShouldReturnMultipliedVector_GivenInputVector256OfInt64()
{ {
Vector256<long> left = Vector256.Create(4L, 6L, 8L, 10L); Vector256<long> left = Vector256.Create(4L, 6L, 8L, 10L);
@ -164,10 +164,10 @@ internal class IntrinsicTests
Vector256<long> expected = Vector256.Create(8L, 18L, 32L, 50L); Vector256<long> expected = Vector256.Create(8L, 18L, 32L, 50L);
Vector256<long> actual = IntrinsicUtility.Multiply(left, right); Vector256<long> actual = IntrinsicUtility.Multiply(left, right);
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
[Test] [TestMethod]
public void MultiplyInternal_Avx2_ShouldReturnMultipliedVector_GivenInputVector256OfUInt64() public void MultiplyInternal_Avx2_ShouldReturnMultipliedVector_GivenInputVector256OfUInt64()
{ {
if (!Avx2.IsSupported) if (!Avx2.IsSupported)
@ -181,10 +181,10 @@ internal class IntrinsicTests
Vector256<ulong> expected = Vector256.Create(8UL, 18UL, 32UL, 50UL); Vector256<ulong> expected = Vector256.Create(8UL, 18UL, 32UL, 50UL);
Vector256<ulong> actual = IntrinsicUtility.MultiplyInternal_Avx2(left, right); Vector256<ulong> actual = IntrinsicUtility.MultiplyInternal_Avx2(left, right);
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
[Test] [TestMethod]
public void MultiplyInternal_Fallback_ShouldReturnMultipliedVector_GivenInputVector256OfUInt64() public void MultiplyInternal_Fallback_ShouldReturnMultipliedVector_GivenInputVector256OfUInt64()
{ {
Vector256<ulong> left = Vector256.Create(4UL, 6UL, 8UL, 10UL); Vector256<ulong> left = Vector256.Create(4UL, 6UL, 8UL, 10UL);
@ -193,10 +193,10 @@ internal class IntrinsicTests
Vector256<ulong> expected = Vector256.Create(8UL, 18UL, 32UL, 50UL); Vector256<ulong> expected = Vector256.Create(8UL, 18UL, 32UL, 50UL);
Vector256<ulong> actual = IntrinsicUtility.MultiplyInternal_Fallback(left, right); Vector256<ulong> actual = IntrinsicUtility.MultiplyInternal_Fallback(left, right);
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
[Test] [TestMethod]
public void ReverseElementsInternal_Fallback_ShouldReturnExpectedVector128Result_GivenInputVector() public void ReverseElementsInternal_Fallback_ShouldReturnExpectedVector128Result_GivenInputVector()
{ {
var inputVector = Vector128.Create(42UL, 69UL); var inputVector = Vector128.Create(42UL, 69UL);
@ -204,10 +204,10 @@ internal class IntrinsicTests
Vector128<ulong> result = inputVector.ReverseElementsInternal_Fallback(); Vector128<ulong> result = inputVector.ReverseElementsInternal_Fallback();
Assert.That(result, Is.EqualTo(expectedResult)); Assert.AreEqual(expectedResult, result);
} }
[Test] [TestMethod]
public void ReverseElementsInternal_Sse2_ShouldReturnExpectedVector128Result_GivenInputVector() public void ReverseElementsInternal_Sse2_ShouldReturnExpectedVector128Result_GivenInputVector()
{ {
if (!Sse2.IsSupported) if (!Sse2.IsSupported)
@ -220,7 +220,7 @@ internal class IntrinsicTests
Vector128<ulong> result = inputVector.ReverseElementsInternal_Sse2(); Vector128<ulong> result = inputVector.ReverseElementsInternal_Sse2();
Assert.That(result, Is.EqualTo(expectedResult)); Assert.AreEqual(expectedResult, result);
} }
} }
#endif #endif

View File

@ -1,30 +1,24 @@
using NUnit.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting;
using X10D.Core; using X10D.Core;
namespace X10D.Tests.Core; namespace X10D.Tests.Core;
[TestFixture] [TestClass]
internal class NullableTests public class NullableTests
{ {
[Test] [TestMethod]
public void TryGetValue_ShouldBeTrue_GivenValue() public void TryGetValue_ShouldBeTrue_GivenValue()
{ {
int? value = 42; int? value = 42;
Assert.Multiple(() => Assert.IsTrue(value.TryGetValue(out int returnedValue));
{ Assert.AreEqual(value, returnedValue);
Assert.That(value.TryGetValue(out int returnedValue));
Assert.That(returnedValue, Is.EqualTo(value.Value));
});
} }
[Test] [TestMethod]
public void TryGetValue_ShouldBeFalse_GivenNull() public void TryGetValue_ShouldBeFalse_GivenNull()
{ {
int? value = null; int? value = null;
Assert.Multiple(() => Assert.IsFalse(value.TryGetValue(out int returnedValue));
{ Assert.AreEqual(default, returnedValue);
Assert.That(value.TryGetValue(out int returnedValue), Is.False);
Assert.That(returnedValue, Is.Zero);
});
} }
} }

View File

@ -1,121 +1,121 @@
using NUnit.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting;
using X10D.Collections; using X10D.Collections;
using X10D.Core; using X10D.Core;
namespace X10D.Tests.Core; namespace X10D.Tests.Core;
[TestFixture] [TestClass]
internal class RandomTests public class RandomTests
{ {
[Test] [TestMethod]
public void NextBoolean_ShouldBeFalse_GivenSeed1234() public void NextBoolean_ShouldBeFalse_GivenSeed1234()
{ {
var random = new Random(1234); var random = new Random(1234);
Assert.That(random.NextBoolean(), Is.False); Assert.IsFalse(random.NextBoolean());
} }
[Test] [TestMethod]
public void NextBoolean_ShouldThrow_GivenNull() public void NextBoolean_ShouldThrow_GivenNull()
{ {
Random random = null!; Random? random = null;
Assert.Throws<ArgumentNullException>(() => random.NextBoolean()); Assert.ThrowsException<ArgumentNullException>(() => random!.NextBoolean());
} }
[Test] [TestMethod]
public void NextByte_ShouldBe101_GivenSeed1234() public void NextByte_ShouldBe101_GivenSeed1234()
{ {
var random = new Random(1234); var random = new Random(1234);
Assert.That(random.NextByte(), Is.EqualTo(101)); Assert.AreEqual(101, random.NextByte());
} }
[Test] [TestMethod]
public void NextByte_WithMax10_ShouldBe3_GivenSeed1234() public void NextByte_WithMax10_ShouldBe3_GivenSeed1234()
{ {
var random = new Random(1234); var random = new Random(1234);
Assert.That(random.NextByte(10), Is.EqualTo(3)); Assert.AreEqual(3, random.NextByte(10));
} }
[Test] [TestMethod]
public void NextByte_WithMin0Max10_ShouldBe3_GivenSeed1234() public void NextByte_WithMin0Max10_ShouldBe3_GivenSeed1234()
{ {
var random = new Random(1234); var random = new Random(1234);
Assert.That(random.NextByte(0, 10), Is.EqualTo(3)); Assert.AreEqual(3, random.NextByte(0, 10));
} }
[Test] [TestMethod]
public void NextByte_ShouldThrow_GivenNull() public void NextByte_ShouldThrow_GivenNull()
{ {
Random? random = null; Random? random = null;
Assert.Throws<ArgumentNullException>(() => random!.NextByte()); Assert.ThrowsException<ArgumentNullException>(() => random!.NextByte());
Assert.Throws<ArgumentNullException>(() => random!.NextByte(10)); Assert.ThrowsException<ArgumentNullException>(() => random!.NextByte(10));
Assert.Throws<ArgumentNullException>(() => random!.NextByte(0, 10)); Assert.ThrowsException<ArgumentNullException>(() => random!.NextByte(0, 10));
} }
[Test] [TestMethod]
public void NextDouble_WithMax10_ShouldBe3point9908097935797695_GivenSeed1234() public void NextDouble_WithMax10_ShouldBe3point9908097935797695_GivenSeed1234()
{ {
var random = new Random(1234); var random = new Random(1234);
Assert.That(random.NextDouble(10), Is.EqualTo(3.9908097935797695)); Assert.AreEqual(3.9908097935797695, random.NextDouble(10));
} }
[Test] [TestMethod]
public void NextDouble_WithMin0Max10_ShouldBe3point9908097935797695_GivenSeed1234() public void NextDouble_WithMin0Max10_ShouldBe3point9908097935797695_GivenSeed1234()
{ {
var random = new Random(1234); var random = new Random(1234);
Assert.That(random.NextDouble(0, 10), Is.EqualTo(3.9908097935797695)); Assert.AreEqual(3.9908097935797695, random.NextDouble(0, 10));
} }
[Test] [TestMethod]
public void NextDouble_ShouldThrow_GivenNull() public void NextDouble_ShouldThrow_GivenNull()
{ {
Random? random = null; Random? random = null;
Assert.Throws<ArgumentNullException>(() => random!.NextDouble(10)); Assert.ThrowsException<ArgumentNullException>(() => random!.NextDouble(10));
Assert.Throws<ArgumentNullException>(() => random!.NextDouble(0, 10)); Assert.ThrowsException<ArgumentNullException>(() => random!.NextDouble(0, 10));
} }
[Test] [TestMethod]
public void NextDouble_ShouldThrow_GivenMaxLessThan0() public void NextDouble_ShouldThrow_GivenMaxLessThan0()
{ {
var random = new Random(1234); var random = new Random(1234);
Assert.Throws<ArgumentOutOfRangeException>(() => random.NextDouble(-1)); Assert.ThrowsException<ArgumentOutOfRangeException>(() => random.NextDouble(-1));
} }
[Test] [TestMethod]
public void NextDouble_ShouldThrow_GivenMaxLessThanMin() public void NextDouble_ShouldThrow_GivenMaxLessThanMin()
{ {
var random = new Random(1234); var random = new Random(1234);
Assert.Throws<ArgumentException>(() => random.NextDouble(0, -1)); Assert.ThrowsException<ArgumentException>(() => random.NextDouble(0, -1));
} }
[Test] [TestMethod]
public void NextEnum_ShouldBeTuesday_GivenSeed1234() public void NextEnum_ShouldBeTuesday_GivenSeed1234()
{ {
var random = new Random(1234); var random = new Random(1234);
Assert.That(random.Next<DayOfWeek>(), Is.EqualTo(DayOfWeek.Tuesday)); Assert.AreEqual(DayOfWeek.Tuesday, random.Next<DayOfWeek>());
} }
[Test] [TestMethod]
public void NextEnum_ShouldThrow_GivenNull() public void NextEnum_ShouldThrow_GivenNull()
{ {
Random? random = null; Random? random = null;
Assert.Throws<ArgumentNullException>(() => random!.Next<DayOfWeek>()); Assert.ThrowsException<ArgumentNullException>(() => random!.Next<DayOfWeek>());
} }
[Test] [TestMethod]
public void NextFrom_ShouldThrow_GivenNullRandom() public void NextFrom_ShouldThrow_GivenNullRandom()
{ {
Random? random = null; Random? random = null;
Assert.Throws<ArgumentNullException>(() => random!.NextFrom("")); Assert.ThrowsException<ArgumentNullException>(() => random!.NextFrom(""));
} }
[Test] [TestMethod]
public void NextFrom_ShouldThrow_GivenNullSource() public void NextFrom_ShouldThrow_GivenNullSource()
{ {
var random = new Random(1234); var random = new Random(1234);
Assert.Throws<ArgumentNullException>(() => random.NextFrom((string?)null!)); Assert.ThrowsException<ArgumentNullException>(() => random.NextFrom((string?)null!));
} }
[Test] [TestMethod]
public void NextFrom_ShouldEnumerate_GivenNonList() public void NextFrom_ShouldEnumerate_GivenNonList()
{ {
IEnumerable<int> Source() IEnumerable<int> Source()
@ -124,168 +124,168 @@ internal class RandomTests
} }
var random = new Random(1234); var random = new Random(1234);
Assert.That(random.NextFrom(Source()), Is.Zero); Assert.AreEqual(0, random.NextFrom(Source()));
} }
[Test] [TestMethod]
public void NextFromSpan_ShouldThrow_GivenNullRandom() public void NextFromSpan_ShouldThrow_GivenNullRandom()
{ {
Random? random = null; Random? random = null;
Assert.Throws<ArgumentNullException>(() => Assert.ThrowsException<ArgumentNullException>(() =>
{ {
Span<int> span = stackalloc int[1]; Span<int> span = stackalloc int[1];
_ = random!.NextFrom(span); return random!.NextFrom(span);
}); });
} }
[Test] [TestMethod]
public void NextFromReadOnlySpan_ShouldThrow_GivenNullRandom() public void NextFromReadOnlySpan_ShouldThrow_GivenNullRandom()
{ {
Random? random = null; Random? random = null;
Assert.Throws<ArgumentNullException>(() => Assert.ThrowsException<ArgumentNullException>(() =>
{ {
Span<int> span = stackalloc int[1]; Span<int> span = stackalloc int[1];
_ = random!.NextFrom(span.AsReadOnly()); return random!.NextFrom(span.AsReadOnly());
}); });
} }
[Test] [TestMethod]
public void NextFromSpan_ShouldReturnOnlyValue_GivenSpanWithLength1() public void NextFromSpan_ShouldReturnOnlyValue_GivenSpanWithLength1()
{ {
Span<int> span = stackalloc int[1]; Span<int> span = stackalloc int[1];
span[0] = 42; span[0] = 42;
var random = new Random(1234); var random = new Random(1234);
Assert.That(random.NextFrom(span), Is.EqualTo(42)); Assert.AreEqual(42, random.NextFrom(span));
} }
[Test] [TestMethod]
public void NextFromReadOnlySpan_ShouldReturnOnlyValue_GivenSpanWithLength1() public void NextFromReadOnlySpan_ShouldReturnOnlyValue_GivenSpanWithLength1()
{ {
Span<int> span = stackalloc int[1]; Span<int> span = stackalloc int[1];
span[0] = 42; span[0] = 42;
var random = new Random(1234); var random = new Random(1234);
Assert.That(random.NextFrom(span.AsReadOnly()), Is.EqualTo(42)); Assert.AreEqual(42, random.NextFrom(span.AsReadOnly()));
} }
[Test] [TestMethod]
public void NextInt16_ShouldBe13076_GivenSeed1234() public void NextInt16_ShouldBe13076_GivenSeed1234()
{ {
var random = new Random(1234); var random = new Random(1234);
Assert.That(random.NextInt16(), Is.EqualTo(13076)); Assert.AreEqual(13076, random.NextInt16());
} }
[Test] [TestMethod]
public void NextInt16_WithMax10_ShouldBe3_GivenSeed1234() public void NextInt16_WithMax10_ShouldBe3_GivenSeed1234()
{ {
var random = new Random(1234); var random = new Random(1234);
Assert.That(random.NextInt16(10), Is.EqualTo(3)); Assert.AreEqual(3, random.NextInt16(10));
} }
[Test] [TestMethod]
public void NextInt16_WithMin0Max10_ShouldBe3_GivenSeed1234() public void NextInt16_WithMin0Max10_ShouldBe3_GivenSeed1234()
{ {
var random = new Random(1234); var random = new Random(1234);
Assert.That(random.NextInt16(0, 10), Is.EqualTo(3)); Assert.AreEqual(3, random.NextInt16(0, 10));
} }
[Test] [TestMethod]
public void NextInt16_ShouldThrow_GivenMaxLessThan0() public void NextInt16_ShouldThrow_GivenMaxLessThan0()
{ {
var random = new Random(1234); var random = new Random(1234);
Assert.Throws<ArgumentOutOfRangeException>(() => random.NextInt16(-1)); Assert.ThrowsException<ArgumentOutOfRangeException>(() => random.NextInt16(-1));
} }
[Test] [TestMethod]
public void NextInt16_ShouldThrow_GivenNull() public void NextInt16_ShouldThrow_GivenNull()
{ {
Random? random = null; Random? random = null;
Assert.Throws<ArgumentNullException>(() => random!.NextInt16()); Assert.ThrowsException<ArgumentNullException>(() => random!.NextInt16());
Assert.Throws<ArgumentNullException>(() => random!.NextInt16(10)); Assert.ThrowsException<ArgumentNullException>(() => random!.NextInt16(10));
Assert.Throws<ArgumentNullException>(() => random!.NextInt16(0, 10)); Assert.ThrowsException<ArgumentNullException>(() => random!.NextInt16(0, 10));
} }
[Test] [TestMethod]
public void NextSingle_WithMax10_ShouldBe3point99081_GivenSeed1234() public void NextSingle_WithMax10_ShouldBe3point99081_GivenSeed1234()
{ {
var random = new Random(1234); var random = new Random(1234);
Assert.That(random.NextSingle(10), Is.EqualTo(3.99081f)); Assert.AreEqual(3.99081f, random.NextSingle(10));
} }
[Test] [TestMethod]
public void NextSingle_WithMin0Max10_ShouldBe3point99081_GivenSeed1234() public void NextSingle_WithMin0Max10_ShouldBe3point99081_GivenSeed1234()
{ {
var random = new Random(1234); var random = new Random(1234);
Assert.That(random.NextSingle(0, 10), Is.EqualTo(3.99081f)); Assert.AreEqual(3.99081f, random.NextSingle(0, 10));
} }
[Test] [TestMethod]
public void NextSingle_ShouldThrow_GivenNull() public void NextSingle_ShouldThrow_GivenNull()
{ {
Random? random = null; Random? random = null;
Assert.Throws<ArgumentNullException>(() => random!.NextSingle(10)); Assert.ThrowsException<ArgumentNullException>(() => random!.NextSingle(10));
Assert.Throws<ArgumentNullException>(() => random!.NextSingle(0, 10)); Assert.ThrowsException<ArgumentNullException>(() => random!.NextSingle(0, 10));
#if !NET6_0_OR_GREATER #if !NET6_0_OR_GREATER
Assert.Throws<ArgumentNullException>(() => random!.NextSingle()); Assert.ThrowsException<ArgumentNullException>(() => random!.NextSingle());
#endif #endif
} }
[Test] [TestMethod]
public void NextSingle_ShouldThrow_GivenMaxLessThan0() public void NextSingle_ShouldThrow_GivenMaxLessThan0()
{ {
var random = new Random(1234); var random = new Random(1234);
Assert.Throws<ArgumentOutOfRangeException>(() => random.NextSingle(-1)); Assert.ThrowsException<ArgumentOutOfRangeException>(() => random.NextSingle(-1));
} }
[Test] [TestMethod]
public void NextSingle_ShouldThrow_GivenMaxLessThanMin() public void NextSingle_ShouldThrow_GivenMaxLessThanMin()
{ {
var random = new Random(1234); var random = new Random(1234);
Assert.Throws<ArgumentException>(() => random.NextSingle(0, -1)); Assert.ThrowsException<ArgumentException>(() => random.NextSingle(0, -1));
} }
[Test] [TestMethod]
public void NextString_ShouldBe_kxiyiyvnqi_GivenSeed1234() public void NextString_ShouldBe_kxiyiyvnqi_GivenSeed1234()
{ {
const string alphabet = "abcdefghijklmnopqrstuvwxyz"; const string alphabet = "abcdefghijklmnopqrstuvwxyz";
var random = new Random(1234); var random = new Random(1234);
Assert.That(random.NextString(alphabet.ToCharArray(), 10), Is.EqualTo("kxiyiyvnqi")); Assert.AreEqual("kxiyiyvnqi", random.NextString(alphabet.ToCharArray(), 10));
} }
[Test] [TestMethod]
public void NextString_ShouldBeEmpty_GivenLength0() public void NextString_ShouldBeEmpty_GivenLength0()
{ {
var random = new Random(1234); var random = new Random(1234);
Assert.That(random.NextString(ArraySegment<char>.Empty, 0), Is.EqualTo(string.Empty)); Assert.AreEqual(string.Empty, random.NextString(ArraySegment<char>.Empty, 0));
} }
[Test] [TestMethod]
public void NextString_ShouldBeLength1_GivenLength1() public void NextString_ShouldBeLength1_GivenLength1()
{ {
var random = new Random(1234); var random = new Random(1234);
Assert.That(random.NextString("hello world".ToCharArray(), 1).Length, Is.EqualTo(1)); Assert.AreEqual(1, random.NextString("hello world".ToCharArray(), 1).Length);
} }
[Test] [TestMethod]
public void NextString_ShouldThrow_GivenNullRandom() public void NextString_ShouldThrow_GivenNullRandom()
{ {
Random? random = null; Random? random = null;
Assert.Throws<ArgumentNullException>(() => random!.NextString(ArraySegment<char>.Empty, 0)); Assert.ThrowsException<ArgumentNullException>(() => random!.NextString(ArraySegment<char>.Empty, 0));
} }
[Test] [TestMethod]
public void NextString_ShouldThrow_GivenNullSource() public void NextString_ShouldThrow_GivenNullSource()
{ {
var random = new Random(1234); var random = new Random(1234);
Assert.Throws<ArgumentNullException>(() => random.NextString(null!, 0)); Assert.ThrowsException<ArgumentNullException>(() => random.NextString(null!, 0));
} }
[Test] [TestMethod]
public void NextString_ShouldThrow_GivenNegativeLength() public void NextString_ShouldThrow_GivenNegativeLength()
{ {
var random = new Random(1234); var random = new Random(1234);
Assert.Throws<ArgumentOutOfRangeException>(() => random.NextString(ArraySegment<char>.Empty, -1)); Assert.ThrowsException<ArgumentOutOfRangeException>(() => random.NextString(ArraySegment<char>.Empty, -1));
} }
} }

View File

@ -2,203 +2,191 @@
using System.Runtime.Intrinsics.Arm; using System.Runtime.Intrinsics.Arm;
using System.Runtime.Intrinsics.X86; using System.Runtime.Intrinsics.X86;
#endif #endif
using NUnit.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting;
using X10D.Core; using X10D.Core;
namespace X10D.Tests.Core; namespace X10D.Tests.Core;
[TestFixture] [TestClass]
internal class SpanTest public class SpanTest
{ {
[Test] [TestMethod]
public void Contains_ShouldReturnFalse_GivenReadOnlySpanWithNoMatchingElements_UsingByteEnum() public void Contains_ShouldReturnFalse_GivenReadOnlySpanWithNoMatchingElements_UsingByteEnum()
{
Assert.Multiple(() =>
{ {
ReadOnlySpan<EnumByte> span = stackalloc EnumByte[1] {EnumByte.B}; ReadOnlySpan<EnumByte> span = stackalloc EnumByte[1] {EnumByte.B};
Assert.That(span.Contains(EnumByte.A), Is.False);
Assert.That(span.Contains(EnumByte.C), Is.False); Assert.IsFalse(span.Contains(EnumByte.A));
}); Assert.IsFalse(span.Contains(EnumByte.C));
} }
[Test] [TestMethod]
public void Contains_ShouldReturnFalse_GivenReadOnlySpanWithNoMatchingElements_UsingInt16Enum() public void Contains_ShouldReturnFalse_GivenReadOnlySpanWithNoMatchingElements_UsingInt16Enum()
{
Assert.Multiple(() =>
{ {
ReadOnlySpan<EnumInt16> span = stackalloc EnumInt16[1] {EnumInt16.B}; ReadOnlySpan<EnumInt16> span = stackalloc EnumInt16[1] {EnumInt16.B};
Assert.That(span.Contains(EnumInt16.A), Is.False);
Assert.That(span.Contains(EnumInt16.C), Is.False); Assert.IsFalse(span.Contains(EnumInt16.A));
}); Assert.IsFalse(span.Contains(EnumInt16.C));
} }
[Test] [TestMethod]
public void Contains_ShouldReturnFalse_GivenReadOnlySpanWithNoMatchingElements_UsingInt32Enum() public void Contains_ShouldReturnFalse_GivenReadOnlySpanWithNoMatchingElements_UsingInt32Enum()
{
Assert.Multiple(() =>
{ {
ReadOnlySpan<EnumInt32> span = stackalloc EnumInt32[1] {EnumInt32.B}; ReadOnlySpan<EnumInt32> span = stackalloc EnumInt32[1] {EnumInt32.B};
Assert.That(span.Contains(EnumInt32.A), Is.False);
Assert.That(span.Contains(EnumInt32.C), Is.False); Assert.IsFalse(span.Contains(EnumInt32.A));
}); Assert.IsFalse(span.Contains(EnumInt32.C));
} }
[Test] [TestMethod]
public void Contains_ShouldReturnFalse_GivenReadOnlySpanWithNoMatchingElements_UsingInt64Enum() public void Contains_ShouldReturnFalse_GivenReadOnlySpanWithNoMatchingElements_UsingInt64Enum()
{
Assert.Multiple(() =>
{ {
ReadOnlySpan<EnumInt64> span = stackalloc EnumInt64[1] {EnumInt64.B}; ReadOnlySpan<EnumInt64> span = stackalloc EnumInt64[1] {EnumInt64.B};
Assert.That(span.Contains(EnumInt64.A), Is.False); Assert.IsFalse(span.Contains(EnumInt64.A));
Assert.That(span.Contains(EnumInt64.C), Is.False); Assert.IsFalse(span.Contains(EnumInt64.C));
});
} }
[Test] [TestMethod]
public void Contains_ShouldReturnTrue_GivenReadOnlySpanWithMatchingElements_UsingByteEnum() public void Contains_ShouldReturnTrue_GivenReadOnlySpanWithMatchingElements_UsingByteEnum()
{ {
ReadOnlySpan<EnumByte> span = stackalloc EnumByte[1] {EnumByte.B}; ReadOnlySpan<EnumByte> span = stackalloc EnumByte[1] {EnumByte.B};
Assert.That(span.Contains(EnumByte.B)); Assert.IsTrue(span.Contains(EnumByte.B));
} }
[Test] [TestMethod]
public void Contains_ShouldReturnTrue_GivenReadOnlySpanWithMatchingElements_UsingInt16Enum() public void Contains_ShouldReturnTrue_GivenReadOnlySpanWithMatchingElements_UsingInt16Enum()
{ {
ReadOnlySpan<EnumInt16> span = stackalloc EnumInt16[1] {EnumInt16.B}; ReadOnlySpan<EnumInt16> span = stackalloc EnumInt16[1] {EnumInt16.B};
Assert.That(span.Contains(EnumInt16.B)); Assert.IsTrue(span.Contains(EnumInt16.B));
} }
[Test] [TestMethod]
public void Contains_ShouldReturnTrue_GivenReadOnlySpanWithMatchingElements_UsingInt32Enum() public void Contains_ShouldReturnTrue_GivenReadOnlySpanWithMatchingElements_UsingInt32Enum()
{ {
ReadOnlySpan<EnumInt32> span = stackalloc EnumInt32[1] {EnumInt32.B}; ReadOnlySpan<EnumInt32> span = stackalloc EnumInt32[1] {EnumInt32.B};
Assert.That(span.Contains(EnumInt32.B)); Assert.IsTrue(span.Contains(EnumInt32.B));
} }
[Test] [TestMethod]
public void Contains_ShouldReturnTrue_GivenReadOnlySpanWithMatchingElements_UsingInt64Enum() public void Contains_ShouldReturnTrue_GivenReadOnlySpanWithMatchingElements_UsingInt64Enum()
{ {
ReadOnlySpan<EnumInt64> span = stackalloc EnumInt64[1] {EnumInt64.B}; ReadOnlySpan<EnumInt64> span = stackalloc EnumInt64[1] {EnumInt64.B};
Assert.That(span.Contains(EnumInt64.B)); Assert.IsTrue(span.Contains(EnumInt64.B));
} }
[Test] [TestMethod]
public void Contains_ShouldReturnFalse_GivenSpanWithNoMatchingElements_UsingByteEnum() public void Contains_ShouldReturnFalse_GivenSpanWithNoMatchingElements_UsingByteEnum()
{
Assert.Multiple(() =>
{ {
Span<EnumByte> span = stackalloc EnumByte[1] {EnumByte.B}; Span<EnumByte> span = stackalloc EnumByte[1] {EnumByte.B};
Assert.That(span.Contains(EnumByte.A), Is.False); Assert.IsFalse(span.Contains(EnumByte.A));
Assert.That(span.Contains(EnumByte.C), Is.False); Assert.IsFalse(span.Contains(EnumByte.C));
});
} }
[Test] [TestMethod]
public void Contains_ShouldReturnFalse_GivenSpanWithNoMatchingElements_UsingInt16Enum() public void Contains_ShouldReturnFalse_GivenSpanWithNoMatchingElements_UsingInt16Enum()
{ {
Span<EnumInt16> span = stackalloc EnumInt16[1] {EnumInt16.B}; Span<EnumInt16> span = stackalloc EnumInt16[1] {EnumInt16.B};
Assert.That(span.Contains(EnumInt16.A), Is.False); Assert.IsFalse(span.Contains(EnumInt16.A));
Assert.That(span.Contains(EnumInt16.C), Is.False); Assert.IsFalse(span.Contains(EnumInt16.C));
} }
[Test] [TestMethod]
public void Contains_ShouldReturnFalse_GivenSpanWithNoMatchingElements_UsingInt32Enum() public void Contains_ShouldReturnFalse_GivenSpanWithNoMatchingElements_UsingInt32Enum()
{ {
Span<EnumInt32> span = stackalloc EnumInt32[1] {EnumInt32.B}; Span<EnumInt32> span = stackalloc EnumInt32[1] {EnumInt32.B};
Assert.That(span.Contains(EnumInt32.A), Is.False); Assert.IsFalse(span.Contains(EnumInt32.A));
Assert.That(span.Contains(EnumInt32.C), Is.False); Assert.IsFalse(span.Contains(EnumInt32.C));
} }
[Test] [TestMethod]
public void Contains_ShouldReturnFalse_GivenSpanWithNoMatchingElements_UsingInt64Enum() public void Contains_ShouldReturnFalse_GivenSpanWithNoMatchingElements_UsingInt64Enum()
{ {
Span<EnumInt64> span = stackalloc EnumInt64[1] {EnumInt64.B}; Span<EnumInt64> span = stackalloc EnumInt64[1] {EnumInt64.B};
Assert.That(span.Contains(EnumInt64.A), Is.False); Assert.IsFalse(span.Contains(EnumInt64.A));
Assert.That(span.Contains(EnumInt64.C), Is.False); Assert.IsFalse(span.Contains(EnumInt64.C));
} }
[Test] [TestMethod]
public void Contains_ShouldReturnTrue_GivenSpanWithMatchingElements_UsingByteEnum() public void Contains_ShouldReturnTrue_GivenSpanWithMatchingElements_UsingByteEnum()
{ {
Span<EnumByte> span = stackalloc EnumByte[1] {EnumByte.B}; Span<EnumByte> span = stackalloc EnumByte[1] {EnumByte.B};
Assert.That(span.Contains(EnumByte.B)); Assert.IsTrue(span.Contains(EnumByte.B));
} }
[Test] [TestMethod]
public void Contains_ShouldReturnTrue_GivenSpanWithMatchingElements_UsingInt16Enum() public void Contains_ShouldReturnTrue_GivenSpanWithMatchingElements_UsingInt16Enum()
{ {
Span<EnumInt16> span = stackalloc EnumInt16[1] {EnumInt16.B}; Span<EnumInt16> span = stackalloc EnumInt16[1] {EnumInt16.B};
Assert.That(span.Contains(EnumInt16.B)); Assert.IsTrue(span.Contains(EnumInt16.B));
} }
[Test] [TestMethod]
public void Contains_ShouldReturnTrue_GivenSpanWithMatchingElements_UsingInt32Enum() public void Contains_ShouldReturnTrue_GivenSpanWithMatchingElements_UsingInt32Enum()
{ {
Span<EnumInt32> span = stackalloc EnumInt32[1] {EnumInt32.B}; Span<EnumInt32> span = stackalloc EnumInt32[1] {EnumInt32.B};
Assert.That(span.Contains(EnumInt32.B)); Assert.IsTrue(span.Contains(EnumInt32.B));
} }
[Test] [TestMethod]
public void Contains_ShouldReturnTrue_GivenSpanWithMatchingElements_UsingInt64Enum() public void Contains_ShouldReturnTrue_GivenSpanWithMatchingElements_UsingInt64Enum()
{ {
Span<EnumInt64> span = stackalloc EnumInt64[1] {EnumInt64.B}; Span<EnumInt64> span = stackalloc EnumInt64[1] {EnumInt64.B};
Assert.That(span.Contains(EnumInt64.B)); Assert.IsTrue(span.Contains(EnumInt64.B));
} }
[Test] [TestMethod]
public void PackByte_ShouldThrowArgumentException_GivenSpanLengthGreaterThan8() public void PackByte_ShouldThrowArgumentException_GivenSpanLengthGreaterThan8()
{ {
Assert.Throws<ArgumentException>(() => Assert.ThrowsException<ArgumentException>(() =>
{ {
Span<bool> span = stackalloc bool[9]; Span<bool> span = stackalloc bool[9];
_ = span.PackByte(); return span.PackByte();
}); });
} }
[Test] [TestMethod]
public void PackInt16_ShouldThrowArgumentException_GivenSpanLengthGreaterThan16() public void PackInt16_ShouldThrowArgumentException_GivenSpanLengthGreaterThan16()
{ {
Assert.Throws<ArgumentException>(() => Assert.ThrowsException<ArgumentException>(() =>
{ {
Span<bool> span = stackalloc bool[17]; Span<bool> span = stackalloc bool[17];
_ = span.PackInt16(); return span.PackInt16();
}); });
} }
[Test] [TestMethod]
public void PackInt32_ShouldThrowArgumentException_GivenSpanLengthGreaterThan32() public void PackInt32_ShouldThrowArgumentException_GivenSpanLengthGreaterThan32()
{ {
Assert.Throws<ArgumentException>(() => Assert.ThrowsException<ArgumentException>(() =>
{ {
Span<bool> span = stackalloc bool[33]; Span<bool> span = stackalloc bool[33];
_ = span.PackInt32(); return span.PackInt32();
}); });
} }
[Test] [TestMethod]
public void PackInt64_ShouldThrowArgumentException_GivenSpanLengthGreaterThan64() public void PackInt64_ShouldThrowArgumentException_GivenSpanLengthGreaterThan64()
{ {
Assert.Throws<ArgumentException>(() => Assert.ThrowsException<ArgumentException>(() =>
{ {
Span<bool> span = stackalloc bool[65]; Span<bool> span = stackalloc bool[65];
_ = span.PackInt64(); return span.PackInt64();
}); });
} }
[Test] [TestMethod]
public void PackByteInternal_Fallback_ShouldReturnCorrectByte_GivenReadOnlySpan_Using() public void PackByteInternal_Fallback_ShouldReturnCorrectByte_GivenReadOnlySpan_Using()
{ {
const byte expected = 0b00110011; const byte expected = 0b00110011;
@ -206,11 +194,11 @@ internal class SpanTest
byte actual = span.PackByteInternal_Fallback(); byte actual = span.PackByteInternal_Fallback();
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
#if NET5_0_OR_GREATER #if NET5_0_OR_GREATER
[Test] [TestMethod]
public void PackByteInternal_Sse2_ShouldReturnCorrectByte_GivenReadOnlySpan_Using() public void PackByteInternal_Sse2_ShouldReturnCorrectByte_GivenReadOnlySpan_Using()
{ {
if (!Sse2.IsSupported) if (!Sse2.IsSupported)
@ -223,10 +211,10 @@ internal class SpanTest
byte actual = span.PackByteInternal_Sse2(); byte actual = span.PackByteInternal_Sse2();
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
[Test] [TestMethod]
public void PackByteInternal_AdvSimd_ShouldReturnCorrectByte_GivenReadOnlySpan_Using() public void PackByteInternal_AdvSimd_ShouldReturnCorrectByte_GivenReadOnlySpan_Using()
{ {
if (!AdvSimd.IsSupported) if (!AdvSimd.IsSupported)
@ -239,11 +227,11 @@ internal class SpanTest
byte actual = span.PackByteInternal_AdvSimd(); byte actual = span.PackByteInternal_AdvSimd();
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
#endif #endif
[Test] [TestMethod]
public void PackInt16_ShouldReturnSameAsPackByte_WhenSpanHasLength8() public void PackInt16_ShouldReturnSameAsPackByte_WhenSpanHasLength8()
{ {
ReadOnlySpan<bool> span = stackalloc bool[8] {true, true, false, false, true, true, false, false}; ReadOnlySpan<bool> span = stackalloc bool[8] {true, true, false, false, true, true, false, false};
@ -251,10 +239,10 @@ internal class SpanTest
short expected = span.PackByte(); short expected = span.PackByte();
short actual = span.PackInt16(); short actual = span.PackInt16();
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
[Test] [TestMethod]
public void PackInt16Internal_Fallback_ShouldReturnCorrectInt16_GivenReadOnlySpan() public void PackInt16Internal_Fallback_ShouldReturnCorrectInt16_GivenReadOnlySpan()
{ {
const short expected = 0b00101101_11010100; const short expected = 0b00101101_11010100;
@ -265,11 +253,11 @@ internal class SpanTest
short actual = span.PackInt16Internal_Fallback(); short actual = span.PackInt16Internal_Fallback();
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
#if NET5_0_OR_GREATER #if NET5_0_OR_GREATER
[Test] [TestMethod]
public void PackInt16Internal_Sse2_ShouldReturnCorrectInt16_GivenReadOnlySpan_Using() public void PackInt16Internal_Sse2_ShouldReturnCorrectInt16_GivenReadOnlySpan_Using()
{ {
if (!Sse2.IsSupported) if (!Sse2.IsSupported)
@ -285,11 +273,11 @@ internal class SpanTest
short actual = span.PackInt16Internal_Sse2(); short actual = span.PackInt16Internal_Sse2();
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
#endif #endif
[Test] [TestMethod]
public void PackInt32Internal_Fallback_ShouldReturnCorrectInt32_GivenReadOnlySpan() public void PackInt32Internal_Fallback_ShouldReturnCorrectInt32_GivenReadOnlySpan()
{ {
const int expected = 0b01010101_10101010_01010101_10101010; const int expected = 0b01010101_10101010_01010101_10101010;
@ -301,11 +289,11 @@ internal class SpanTest
int actual = span.PackInt32Internal_Fallback(); int actual = span.PackInt32Internal_Fallback();
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
#if NET5_0_OR_GREATER #if NET5_0_OR_GREATER
[Test] [TestMethod]
public void PackInt32Internal_Sse2_ShouldReturnCorrectInt32_GivenReadOnlySpan() public void PackInt32Internal_Sse2_ShouldReturnCorrectInt32_GivenReadOnlySpan()
{ {
if (!Sse2.IsSupported) if (!Sse2.IsSupported)
@ -322,10 +310,10 @@ internal class SpanTest
int actual = span.PackInt32Internal_Sse2(); int actual = span.PackInt32Internal_Sse2();
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
[Test] [TestMethod]
public void PackInt32Internal_Avx2_ShouldReturnCorrectInt32_GivenReadOnlySpan() public void PackInt32Internal_Avx2_ShouldReturnCorrectInt32_GivenReadOnlySpan()
{ {
if (!Avx2.IsSupported) if (!Avx2.IsSupported)
@ -342,10 +330,10 @@ internal class SpanTest
int actual = span.PackInt32Internal_Avx2(); int actual = span.PackInt32Internal_Avx2();
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
[Test] [TestMethod]
public void PackInt32Internal_AdvSimd_ShouldReturnCorrectInt32_GivenReadOnlySpan() public void PackInt32Internal_AdvSimd_ShouldReturnCorrectInt32_GivenReadOnlySpan()
{ {
if (!AdvSimd.IsSupported) if (!AdvSimd.IsSupported)
@ -362,11 +350,11 @@ internal class SpanTest
int actual = span.PackInt32Internal_AdvSimd(); int actual = span.PackInt32Internal_AdvSimd();
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
#endif #endif
[Test] [TestMethod]
public void PackInt32_ShouldReturnSameAsPackByte_WhenSpanHasLength8_UsingReadOnlySpan() public void PackInt32_ShouldReturnSameAsPackByte_WhenSpanHasLength8_UsingReadOnlySpan()
{ {
ReadOnlySpan<bool> span = stackalloc bool[8] {true, true, false, false, true, true, false, false}; ReadOnlySpan<bool> span = stackalloc bool[8] {true, true, false, false, true, true, false, false};
@ -374,10 +362,10 @@ internal class SpanTest
int expected = span.PackByte(); int expected = span.PackByte();
int actual = span.PackInt32(); int actual = span.PackInt32();
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
[Test] [TestMethod]
public void PackInt32_ShouldReturnSameAsPackByte_WhenSpanHasLength8_UsingSpan() public void PackInt32_ShouldReturnSameAsPackByte_WhenSpanHasLength8_UsingSpan()
{ {
Span<bool> span = stackalloc bool[8] {true, true, false, false, true, true, false, false}; Span<bool> span = stackalloc bool[8] {true, true, false, false, true, true, false, false};
@ -385,10 +373,10 @@ internal class SpanTest
int expected = span.PackByte(); int expected = span.PackByte();
int actual = span.PackInt32(); int actual = span.PackInt32();
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
[Test] [TestMethod]
public void PackInt32_ShouldReturnSameAsPackInt16_WhenSpanHasLength16_UsingReadOnlySpan() public void PackInt32_ShouldReturnSameAsPackInt16_WhenSpanHasLength16_UsingReadOnlySpan()
{ {
ReadOnlySpan<bool> span = stackalloc bool[16] ReadOnlySpan<bool> span = stackalloc bool[16]
@ -399,10 +387,10 @@ internal class SpanTest
int expected = span.PackInt16(); int expected = span.PackInt16();
int actual = span.PackInt32(); int actual = span.PackInt32();
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
[Test] [TestMethod]
public void PackInt32_ShouldReturnSameAsPackInt16_WhenSpanHasLength16_UsingSpan() public void PackInt32_ShouldReturnSameAsPackInt16_WhenSpanHasLength16_UsingSpan()
{ {
Span<bool> span = stackalloc bool[16] Span<bool> span = stackalloc bool[16]
@ -413,10 +401,10 @@ internal class SpanTest
int expected = span.PackInt16(); int expected = span.PackInt16();
int actual = span.PackInt32(); int actual = span.PackInt32();
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
[Test] [TestMethod]
public void PackInt64_ShouldReturnCorrectInt64_GivenReadOnlySpan() public void PackInt64_ShouldReturnCorrectInt64_GivenReadOnlySpan()
{ {
const long expected = 0b01010101_11010110_01101001_11010110_00010010_10010111_00101100_10100101; const long expected = 0b01010101_11010110_01101001_11010110_00010010_10010111_00101100_10100101;
@ -430,10 +418,10 @@ internal class SpanTest
long actual = span.PackInt64(); long actual = span.PackInt64();
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
[Test] [TestMethod]
public void PackInt64_ShouldReturnCorrectInt64_GivenSpan() public void PackInt64_ShouldReturnCorrectInt64_GivenSpan()
{ {
const long expected = 0b01010101_11010110_01101001_11010110_00010010_10010111_00101100_10100101; const long expected = 0b01010101_11010110_01101001_11010110_00010010_10010111_00101100_10100101;
@ -447,10 +435,10 @@ internal class SpanTest
long actual = span.PackInt64(); long actual = span.PackInt64();
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
[Test] [TestMethod]
public void PackInt64_ShouldReturnSameAsPackByte_WhenSpanHasLength8_UsingReadOnlySpan() public void PackInt64_ShouldReturnSameAsPackByte_WhenSpanHasLength8_UsingReadOnlySpan()
{ {
ReadOnlySpan<bool> span = stackalloc bool[8] {true, true, false, false, true, true, false, false}; ReadOnlySpan<bool> span = stackalloc bool[8] {true, true, false, false, true, true, false, false};
@ -458,10 +446,10 @@ internal class SpanTest
long expected = span.PackByte(); long expected = span.PackByte();
long actual = span.PackInt64(); long actual = span.PackInt64();
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
[Test] [TestMethod]
public void PackInt64_ShouldReturnSameAsPackByte_WhenSpanHasLength8_UsingSpan() public void PackInt64_ShouldReturnSameAsPackByte_WhenSpanHasLength8_UsingSpan()
{ {
Span<bool> span = stackalloc bool[8] {true, true, false, false, true, true, false, false}; Span<bool> span = stackalloc bool[8] {true, true, false, false, true, true, false, false};
@ -469,10 +457,10 @@ internal class SpanTest
long expected = span.PackByte(); long expected = span.PackByte();
long actual = span.PackInt64(); long actual = span.PackInt64();
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
[Test] [TestMethod]
public void PackInt64_ShouldReturnSameAsPackInt16_WhenSpanHasLength16_UsingReadOnlySpan() public void PackInt64_ShouldReturnSameAsPackInt16_WhenSpanHasLength16_UsingReadOnlySpan()
{ {
ReadOnlySpan<bool> span = stackalloc bool[16] ReadOnlySpan<bool> span = stackalloc bool[16]
@ -483,10 +471,10 @@ internal class SpanTest
long expected = span.PackInt16(); long expected = span.PackInt16();
long actual = span.PackInt64(); long actual = span.PackInt64();
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
[Test] [TestMethod]
public void PackInt64_ShouldReturnSameAsPackInt16_WhenSpanHasLength16_UsingSpan() public void PackInt64_ShouldReturnSameAsPackInt16_WhenSpanHasLength16_UsingSpan()
{ {
Span<bool> span = stackalloc bool[16] Span<bool> span = stackalloc bool[16]
@ -497,10 +485,10 @@ internal class SpanTest
long expected = span.PackInt16(); long expected = span.PackInt16();
long actual = span.PackInt64(); long actual = span.PackInt64();
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
[Test] [TestMethod]
public void PackInt64_ShouldReturnSameAsPackInt32_WhenSpanHasLength16_UsingReadOnlySpan() public void PackInt64_ShouldReturnSameAsPackInt32_WhenSpanHasLength16_UsingReadOnlySpan()
{ {
ReadOnlySpan<bool> span = stackalloc bool[32] ReadOnlySpan<bool> span = stackalloc bool[32]
@ -512,10 +500,10 @@ internal class SpanTest
long expected = span.PackInt32(); long expected = span.PackInt32();
long actual = span.PackInt64(); long actual = span.PackInt64();
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
[Test] [TestMethod]
public void PackInt64_ShouldReturnSameAsPackInt32_WhenSpanHasLength16_UsingSpan() public void PackInt64_ShouldReturnSameAsPackInt32_WhenSpanHasLength16_UsingSpan()
{ {
Span<bool> span = stackalloc bool[32] Span<bool> span = stackalloc bool[32]
@ -527,10 +515,10 @@ internal class SpanTest
long expected = span.PackInt32(); long expected = span.PackInt32();
long actual = span.PackInt64(); long actual = span.PackInt64();
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
[Test] [TestMethod]
public void PackInt64_ShouldFallbackAndReturnCorrectValue_GivenNonPowerOfTwoLength_UsingReadOnlySpan() public void PackInt64_ShouldFallbackAndReturnCorrectValue_GivenNonPowerOfTwoLength_UsingReadOnlySpan()
{ {
const long expected = 0b00000000_00000000_00000000_00000000_00000000_00000000_00000001_01010011; const long expected = 0b00000000_00000000_00000000_00000000_00000000_00000000_00000001_01010011;
@ -538,10 +526,10 @@ internal class SpanTest
long actual = span.PackInt64(); long actual = span.PackInt64();
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
[Test] [TestMethod]
public void PackInt64_ShouldFallbackAndReturnCorrectValue_GivenNonPowerOfTwoLength_UsingSpan() public void PackInt64_ShouldFallbackAndReturnCorrectValue_GivenNonPowerOfTwoLength_UsingSpan()
{ {
const long expected = 0b00000000_00000000_00000000_00000000_00000000_00000000_00000001_01010011; const long expected = 0b00000000_00000000_00000000_00000000_00000000_00000000_00000001_01010011;
@ -549,7 +537,7 @@ internal class SpanTest
long actual = span.PackInt64(); long actual = span.PackInt64();
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
private enum EnumByte : byte private enum EnumByte : byte

View File

@ -1,193 +1,167 @@
using System.Drawing; using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;
using X10D.Drawing; using X10D.Drawing;
namespace X10D.Tests.Drawing; namespace X10D.Tests.Drawing;
[TestFixture] [TestClass]
internal class CircleFTests public class CircleFTests
{ {
[Test] [TestMethod]
public void Area_ShouldBePiRadiusRadius_GivenUnitCircle() public void Area_ShouldBePiRadiusRadius_GivenUnitCircle()
{ {
var unitCircle = CircleF.Unit; var unitCircle = CircleF.Unit;
Assert.That(unitCircle.Area, Is.EqualTo(MathF.PI)); Assert.AreEqual(MathF.PI, unitCircle.Area);
} }
[Test] [TestMethod]
public void Circumference_ShouldBe2PiRadius_GivenUnitCircle() public void Circumference_ShouldBe2PiRadius_GivenUnitCircle()
{ {
var unitCircle = CircleF.Unit; var unitCircle = CircleF.Unit;
Assert.That(unitCircle.Circumference, Is.EqualTo(2 * MathF.PI).Within(1e-6f)); Assert.AreEqual(2 * MathF.PI, unitCircle.Circumference, 1e-6f);
} }
[Test] [TestMethod]
public void CompareTo_ShouldBeNegativeOne_GivenUnitCircleAndEmpty() public void CompareTo_ShouldBeNegativeOne_GivenUnitCircleAndEmpty()
{ {
Assert.That(CircleF.Empty.CompareTo(CircleF.Unit), Is.EqualTo(-1)); Assert.AreEqual(-1, CircleF.Empty.CompareTo(CircleF.Unit));
} }
[Test] [TestMethod]
public void CompareTo_ShouldBeOne_GivenUnitCircleAndEmpty() public void CompareTo_ShouldBeOne_GivenUnitCircleAndEmpty()
{ {
Assert.That(CircleF.Unit.CompareTo(CircleF.Empty), Is.EqualTo(1)); Assert.AreEqual(1, CircleF.Unit.CompareTo(CircleF.Empty));
} }
[Test] [TestMethod]
public void CompareTo_ShouldBeNegativeOne_GivenEmptyCircleAndUnitCircleAsObject() public void CompareTo_ShouldBeNegativeOne_GivenEmptyCircleAndUnitCircleAsObject()
{ {
Assert.That(CircleF.Empty.CompareTo((object)CircleF.Unit), Is.EqualTo(-1)); Assert.AreEqual(-1, CircleF.Empty.CompareTo((object)CircleF.Unit));
} }
[Test] [TestMethod]
public void CompareTo_ShouldBeOne_GivenNull() public void CompareTo_ShouldBeOne_GivenNull()
{ {
Assert.That(CircleF.Unit.CompareTo(null), Is.EqualTo(1)); Assert.AreEqual(1, CircleF.Unit.CompareTo(null));
} }
[Test] [TestMethod]
public void CompareTo_ShouldBeZero_GivenUnitCircle() public void CompareTo_ShouldBeZero_GivenUnitCircle()
{ {
var unitCircle = CircleF.Unit; var unitCircle = CircleF.Unit;
Assert.That(unitCircle.CompareTo(unitCircle), Is.Zero); Assert.AreEqual(0, unitCircle.CompareTo(unitCircle));
} }
[Test] [TestMethod]
public void CompareTo_ShouldThrowArgumentException_GivenInvalidType() public void CompareTo_ShouldThrowArgumentException_GivenInvalidType()
{ {
Assert.Throws<ArgumentException>(() => _ = CircleF.Unit.CompareTo(new object())); Assert.ThrowsException<ArgumentException>(() => CircleF.Unit.CompareTo(new object()));
} }
[Test] [TestMethod]
public void Diameter_ShouldBe2_GivenUnitCircle() public void Diameter_ShouldBe2_GivenUnitCircle()
{ {
Assert.That(CircleF.Unit.Diameter, Is.EqualTo(2.0f).Within(1e-6f)); Assert.AreEqual(2.0f, CircleF.Unit.Diameter, 1e-6f);
} }
[Test] [TestMethod]
public void Equals_ShouldBeTrue_GivenTwoUnitCircles() public void Equals_ShouldBeTrue_GivenTwoUnitCircles()
{ {
var unitCircle1 = CircleF.Unit; var unitCircle1 = CircleF.Unit;
var unitCircle2 = CircleF.Unit; var unitCircle2 = CircleF.Unit;
Assert.Multiple(() => Assert.AreEqual(unitCircle1, unitCircle2);
{ Assert.IsTrue(unitCircle1 == unitCircle2);
Assert.That(unitCircle2, Is.EqualTo(unitCircle1)); Assert.IsFalse(unitCircle1 != unitCircle2);
Assert.That(unitCircle1, Is.EqualTo(unitCircle2));
Assert.That(unitCircle1 == unitCircle2);
Assert.That(unitCircle2 == unitCircle1);
});
} }
[Test] [TestMethod]
public void Equals_ShouldBeTrue_GivenUnitCirclesAsObjects() public void Equals_ShouldBeTrue_GivenUnitCirclesAsObjects()
{ {
CircleF unitCircle1 = CircleF.Unit; CircleF unitCircle1 = CircleF.Unit;
object unitCircle2 = CircleF.Unit; object unitCircle2 = CircleF.Unit;
Assert.Multiple(() => Assert.AreEqual(unitCircle1, unitCircle2);
{ Assert.IsTrue(unitCircle1.Equals(unitCircle2));
Assert.That(unitCircle2, Is.EqualTo(unitCircle1));
Assert.That(unitCircle1, Is.EqualTo(unitCircle2));
});
} }
[Test] [TestMethod]
public void Equals_ShouldBeFalse_GivenDifferentCircles() public void Equals_ShouldBeFalse_GivenDifferentCircles()
{ {
Assert.Multiple(() => Assert.AreNotEqual(CircleF.Unit, CircleF.Empty);
{ Assert.IsFalse(CircleF.Unit == CircleF.Empty);
Assert.That(CircleF.Empty, Is.Not.EqualTo(CircleF.Unit)); Assert.IsTrue(CircleF.Unit != CircleF.Empty);
Assert.That(CircleF.Unit, Is.Not.EqualTo(CircleF.Empty));
Assert.That(CircleF.Empty != CircleF.Unit);
Assert.That(CircleF.Unit != CircleF.Empty);
});
} }
[Test] [TestMethod]
public void Equals_ShouldBeFalse_GivenDifferentObjects() public void Equals_ShouldBeFalse_GivenDifferentObjects()
{ {
Assert.That(CircleF.Empty, Is.Not.EqualTo(null)); Assert.AreNotEqual((object?)null, CircleF.Empty);
Assert.That(CircleF.Empty.Equals(null), Is.False); Assert.IsFalse(CircleF.Empty.Equals(null));
} }
[Test] [TestMethod]
public void GetHashCode_ShouldBeCorrect_GivenEmptyCircle() public void GetHashCode_ShouldBeCorrect_GivenEmptyCircle()
{ {
// this test is pretty pointless, it exists only for code coverage purposes // this test is pretty pointless, it exists only for code coverage purposes
int hashCode = CircleF.Empty.GetHashCode(); int hashCode = CircleF.Empty.GetHashCode();
Assert.That(CircleF.Empty.GetHashCode(), Is.EqualTo(hashCode)); Assert.AreEqual(hashCode, CircleF.Empty.GetHashCode());
} }
[Test] [TestMethod]
public void GetHashCode_ShouldBeCorrect_GivenUnitCircle() public void GetHashCode_ShouldBeCorrect_GivenUnitCircle()
{ {
// this test is pretty pointless, it exists only for code coverage purposes // this test is pretty pointless, it exists only for code coverage purposes
int hashCode = CircleF.Unit.GetHashCode(); int hashCode = CircleF.Unit.GetHashCode();
Assert.That(CircleF.Unit.GetHashCode(), Is.EqualTo(hashCode)); Assert.AreEqual(hashCode, CircleF.Unit.GetHashCode());
} }
[Test] [TestMethod]
public void op_Explicit_ShouldReturnEquivalentCircle_GivenCircle() public void op_Explicit_ShouldReturnEquivalentCircle_GivenCircle()
{ {
CircleF unitCircle = CircleF.Unit; CircleF unitCircle = CircleF.Unit;
Circle converted = (Circle)unitCircle; Circle converted = (Circle)unitCircle;
Assert.Multiple(() => Assert.AreEqual(unitCircle, converted);
{ Assert.AreEqual(unitCircle.Radius, converted.Radius);
Assert.That(converted, Is.EqualTo((Circle)unitCircle)); Assert.AreEqual(unitCircle.Center, converted.Center);
Assert.That(converted == (Circle)unitCircle);
Assert.That(converted.Radius, Is.EqualTo(unitCircle.Radius));
Assert.That((PointF)converted.Center, Is.EqualTo(unitCircle.Center));
});
} }
[Test] [TestMethod]
public void op_GreaterThan_True_GivenUnitAndEmptyCircle() public void op_GreaterThan_True_GivenUnitAndEmptyCircle()
{ {
Assert.That(CircleF.Unit, Is.GreaterThan(CircleF.Empty)); Assert.IsTrue(CircleF.Unit > CircleF.Empty);
Assert.That(CircleF.Unit, Is.GreaterThanOrEqualTo(CircleF.Empty)); Assert.IsTrue(CircleF.Unit >= CircleF.Empty);
Assert.IsFalse(CircleF.Unit < CircleF.Empty);
Assert.That(CircleF.Unit > CircleF.Empty); Assert.IsFalse(CircleF.Unit <= CircleF.Empty);
Assert.That(CircleF.Unit >= CircleF.Empty);
} }
[Test] [TestMethod]
public void op_Implicit_ShouldReturnEquivalentCircle_GivenCircle() public void op_Implicit_ShouldReturnEquivalentCircle_GivenCircle()
{ {
Circle unitCircle = Circle.Unit; Circle unitCircle = Circle.Unit;
CircleF converted = unitCircle; CircleF converted = unitCircle;
Assert.Multiple(() => Assert.AreEqual(unitCircle, converted);
{ Assert.AreEqual(unitCircle.Radius, converted.Radius);
Assert.That(converted, Is.EqualTo((CircleF)unitCircle)); Assert.AreEqual(unitCircle.Center, converted.Center);
Assert.That(converted == unitCircle);
Assert.That(converted.Radius, Is.EqualTo(unitCircle.Radius));
Assert.That(converted.Center, Is.EqualTo((PointF)unitCircle.Center));
});
} }
[Test] [TestMethod]
public void op_LessThan_True_GivenEmptyAndUnitCircle() public void op_LessThan_True_GivenEmptyAndUnitCircle()
{ {
Assert.Multiple(() => Assert.IsTrue(CircleF.Empty < CircleF.Unit);
{ Assert.IsTrue(CircleF.Empty <= CircleF.Unit);
Assert.That(CircleF.Empty, Is.LessThan(CircleF.Unit)); Assert.IsFalse(CircleF.Empty > CircleF.Unit);
Assert.That(CircleF.Empty, Is.LessThanOrEqualTo(CircleF.Unit)); Assert.IsFalse(CircleF.Empty >= CircleF.Unit);
Assert.That(CircleF.Empty < CircleF.Unit);
Assert.That(CircleF.Empty <= CircleF.Unit);
});
} }
[Test] [TestMethod]
public void Radius_ShouldBe0_GivenEmptyCircle() public void Radius_ShouldBe0_GivenEmptyCircle()
{ {
Assert.That(CircleF.Empty.Radius, Is.EqualTo(0.0f).Within(1e-6f)); Assert.AreEqual(0.0f, CircleF.Empty.Radius, 1e-6f);
} }
[Test] [TestMethod]
public void Radius_ShouldBe1_GivenUnitCircle() public void Radius_ShouldBe1_GivenUnitCircle()
{ {
Assert.That(CircleF.Unit.Radius, Is.EqualTo(1.0f).Within(1e-6f)); Assert.AreEqual(1.0f, CircleF.Unit.Radius, 1e-6f);
} }
} }

View File

@ -1,161 +1,145 @@
using NUnit.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting;
using X10D.Drawing; using X10D.Drawing;
namespace X10D.Tests.Drawing; namespace X10D.Tests.Drawing;
[TestFixture] [TestClass]
internal class CircleTests public class CircleTests
{ {
[Test] [TestMethod]
public void Area_ShouldBePiRadiusRadius_GivenUnitCircle() public void Area_ShouldBePiRadiusRadius_GivenUnitCircle()
{ {
var unitCircle = Circle.Unit; var unitCircle = Circle.Unit;
Assert.That(unitCircle.Area, Is.EqualTo(MathF.PI * unitCircle.Radius * unitCircle.Radius)); Assert.AreEqual(MathF.PI * unitCircle.Radius * unitCircle.Radius, unitCircle.Area);
} }
[Test] [TestMethod]
public void Circumference_ShouldBe2PiRadius_GivenUnitCircle() public void Circumference_ShouldBe2PiRadius_GivenUnitCircle()
{ {
var unitCircle = Circle.Unit; var unitCircle = Circle.Unit;
Assert.That(unitCircle.Circumference, Is.EqualTo(2.0f * MathF.PI * unitCircle.Radius).Within(1e-6f)); Assert.AreEqual(2.0f * MathF.PI * unitCircle.Radius, unitCircle.Circumference, 1e-6f);
} }
[Test] [TestMethod]
public void CompareTo_ShouldBeNegativeOne_GivenUnitCircleAndEmpty() public void CompareTo_ShouldBeNegativeOne_GivenUnitCircleAndEmpty()
{ {
Assert.That(Circle.Empty.CompareTo(Circle.Unit), Is.EqualTo(-1)); Assert.AreEqual(-1, Circle.Empty.CompareTo(Circle.Unit));
} }
[Test] [TestMethod]
public void CompareTo_ShouldBeOne_GivenUnitCircleAndEmpty() public void CompareTo_ShouldBeOne_GivenUnitCircleAndEmpty()
{ {
Assert.That(Circle.Unit.CompareTo(Circle.Empty), Is.EqualTo(1)); Assert.AreEqual(1, Circle.Unit.CompareTo(Circle.Empty));
} }
[Test] [TestMethod]
public void CompareTo_ShouldBeNegativeOne_GivenEmptyCircleAndUnitCircleAsObject() public void CompareTo_ShouldBeNegativeOne_GivenEmptyCircleAndUnitCircleAsObject()
{ {
Assert.That(Circle.Empty.CompareTo((object)Circle.Unit), Is.EqualTo(-1)); Assert.AreEqual(-1, Circle.Empty.CompareTo((object)Circle.Unit));
} }
[Test] [TestMethod]
public void CompareTo_ShouldBeOne_GivenNull() public void CompareTo_ShouldBeOne_GivenNull()
{ {
Assert.That(Circle.Unit.CompareTo(null), Is.EqualTo(1)); Assert.AreEqual(1, Circle.Unit.CompareTo(null));
} }
[Test] [TestMethod]
public void CompareTo_ShouldBeZero_GivenUnitCircle() public void CompareTo_ShouldBeZero_GivenUnitCircle()
{ {
var unitCircle = Circle.Unit; var unitCircle = Circle.Unit;
Assert.That(unitCircle.CompareTo(unitCircle), Is.Zero); Assert.AreEqual(0, unitCircle.CompareTo(unitCircle));
} }
[Test] [TestMethod]
public void CompareTo_ShouldThrowArgumentException_GivenInvalidType() public void CompareTo_ShouldThrowArgumentException_GivenInvalidType()
{ {
Assert.Throws<ArgumentException>(() => _ = Circle.Unit.CompareTo(new object())); Assert.ThrowsException<ArgumentException>(() => Circle.Unit.CompareTo(new object()));
} }
[Test] [TestMethod]
public void Diameter_ShouldBe2_GivenUnitCircle() public void Diameter_ShouldBe2_GivenUnitCircle()
{ {
Assert.That(Circle.Unit.Diameter, Is.EqualTo(2.0f).Within(1e-6f)); Assert.AreEqual(2.0f, Circle.Unit.Diameter, 1e-6f);
} }
[Test] [TestMethod]
public void Equals_ShouldBeTrue_GivenTwoUnitCircles() public void Equals_ShouldBeTrue_GivenTwoUnitCircles()
{ {
var unitCircle1 = Circle.Unit; var unitCircle1 = Circle.Unit;
var unitCircle2 = Circle.Unit; var unitCircle2 = Circle.Unit;
Assert.Multiple(() => Assert.AreEqual(unitCircle1, unitCircle2);
{ Assert.IsTrue(unitCircle1 == unitCircle2);
Assert.That(unitCircle2, Is.EqualTo(unitCircle1)); Assert.IsFalse(unitCircle1 != unitCircle2);
Assert.That(unitCircle1, Is.EqualTo(unitCircle2));
});
} }
[Test] [TestMethod]
public void Equals_ShouldBeTrue_GivenUnitCirclesAsObjects() public void Equals_ShouldBeTrue_GivenUnitCirclesAsObjects()
{ {
Circle unitCircle1 = Circle.Unit; Circle unitCircle1 = Circle.Unit;
object unitCircle2 = Circle.Unit; object unitCircle2 = Circle.Unit;
Assert.Multiple(() => Assert.AreEqual(unitCircle1, unitCircle2);
{ Assert.IsTrue(unitCircle1.Equals(unitCircle2));
Assert.That(unitCircle2, Is.EqualTo(unitCircle1));
Assert.That(unitCircle1, Is.EqualTo(unitCircle2));
});
} }
[Test] [TestMethod]
public void Equals_ShouldBeFalse_GivenDifferentCircles() public void Equals_ShouldBeFalse_GivenDifferentCircles()
{ {
Assert.Multiple(() => Assert.AreNotEqual(Circle.Unit, Circle.Empty);
{ Assert.IsFalse(Circle.Unit == Circle.Empty);
Assert.That(Circle.Empty, Is.Not.EqualTo(Circle.Unit)); Assert.IsTrue(Circle.Unit != Circle.Empty);
Assert.That(Circle.Unit, Is.Not.EqualTo(Circle.Empty));
Assert.That(Circle.Empty != Circle.Unit);
Assert.That(Circle.Unit != Circle.Empty);
});
} }
[Test] [TestMethod]
public void Equals_ShouldBeFalse_GivenDifferentObjects() public void Equals_ShouldBeFalse_GivenDifferentObjects()
{ {
Assert.That(Circle.Empty, Is.Not.EqualTo(null)); Assert.AreNotEqual((object?)null, Circle.Empty);
Assert.That(Circle.Empty.Equals(null), Is.False); Assert.IsFalse(Circle.Empty.Equals(null));
} }
[Test] [TestMethod]
public void GetHashCode_ShouldBeCorrect_GivenEmptyCircle() public void GetHashCode_ShouldBeCorrect_GivenEmptyCircle()
{ {
// this test is pretty pointless, it exists only for code coverage purposes // this test is pretty pointless, it exists only for code coverage purposes
int hashCode = Circle.Empty.GetHashCode(); int hashCode = Circle.Empty.GetHashCode();
Assert.That(Circle.Empty.GetHashCode(), Is.EqualTo(hashCode)); Assert.AreEqual(hashCode, Circle.Empty.GetHashCode());
} }
[Test] [TestMethod]
public void GetHashCode_ShouldBeCorrect_GivenUnitCircle() public void GetHashCode_ShouldBeCorrect_GivenUnitCircle()
{ {
// this test is pretty pointless, it exists only for code coverage purposes // this test is pretty pointless, it exists only for code coverage purposes
int hashCode = Circle.Unit.GetHashCode(); int hashCode = Circle.Unit.GetHashCode();
Assert.That(Circle.Unit.GetHashCode(), Is.EqualTo(hashCode)); Assert.AreEqual(hashCode, Circle.Unit.GetHashCode());
} }
[Test] [TestMethod]
public void op_GreaterThan_True_GivenUnitAndEmptyCircle() public void op_GreaterThan_True_GivenUnitAndEmptyCircle()
{ {
Assert.Multiple(() => Assert.IsTrue(Circle.Unit > Circle.Empty);
{ Assert.IsTrue(Circle.Unit >= Circle.Empty);
Assert.That(Circle.Unit, Is.GreaterThan(Circle.Empty)); Assert.IsFalse(Circle.Unit < Circle.Empty);
Assert.That(Circle.Unit, Is.GreaterThanOrEqualTo(Circle.Empty)); Assert.IsFalse(Circle.Unit <= Circle.Empty);
Assert.That(Circle.Unit > Circle.Empty);
Assert.That(Circle.Unit >= Circle.Empty);
});
} }
[Test] [TestMethod]
public void op_LessThan_True_GivenEmptyAndUnitCircle() public void op_LessThan_True_GivenEmptyAndUnitCircle()
{ {
Assert.Multiple(() => Assert.IsTrue(Circle.Empty < Circle.Unit);
{ Assert.IsTrue(Circle.Empty <= Circle.Unit);
Assert.That(Circle.Empty, Is.LessThan(Circle.Unit)); Assert.IsFalse(Circle.Empty > Circle.Unit);
Assert.That(Circle.Empty, Is.LessThanOrEqualTo(Circle.Unit)); Assert.IsFalse(Circle.Empty >= Circle.Unit);
Assert.That(Circle.Empty < Circle.Unit);
Assert.That(Circle.Empty <= Circle.Unit);
});
} }
[Test] [TestMethod]
public void Radius_ShouldBe0_GivenEmptyCircle() public void Radius_ShouldBe0_GivenEmptyCircle()
{ {
Assert.That(Circle.Empty.Radius, Is.Zero); Assert.AreEqual(0, Circle.Empty.Radius);
} }
[Test] [TestMethod]
public void Radius_ShouldBe1_GivenUnitCircle() public void Radius_ShouldBe1_GivenUnitCircle()
{ {
Assert.That(Circle.Unit.Radius, Is.EqualTo(1)); Assert.AreEqual(1, Circle.Unit.Radius);
} }
} }

View File

@ -1,11 +1,11 @@
using System.Drawing; using System.Drawing;
using NUnit.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting;
using X10D.Drawing; using X10D.Drawing;
namespace X10D.Tests.Drawing; namespace X10D.Tests.Drawing;
[TestFixture] [TestClass]
internal class ColorTests public class ColorTests
{ {
private static readonly Color Black = Color.FromArgb(0, 0, 0); private static readonly Color Black = Color.FromArgb(0, 0, 0);
private static readonly Color White = Color.FromArgb(255, 255, 255); private static readonly Color White = Color.FromArgb(255, 255, 255);
@ -16,278 +16,251 @@ internal class ColorTests
private static readonly Color Magenta = Color.FromArgb(255, 0, 255); private static readonly Color Magenta = Color.FromArgb(255, 0, 255);
private static readonly Color Yellow = Color.FromArgb(255, 255, 0); private static readonly Color Yellow = Color.FromArgb(255, 255, 0);
[Test] [TestMethod]
public void Deconstruct_ShouldDeconstructColor_GivenColor() public void Deconstruct_ShouldDeconstructColor_GivenColor()
{ {
(byte r, byte g, byte b) = Black; (byte r, byte g, byte b) = Black;
Assert.Multiple(() => Assert.AreEqual(0, r);
{ Assert.AreEqual(0, g);
Assert.That(r, Is.Zero); Assert.AreEqual(0, b);
Assert.That(g, Is.Zero);
Assert.That(b, Is.Zero);
});
(byte a, r, g, b) = Black; (byte a, r, g, b) = Black;
Assert.Multiple(() => Assert.AreEqual(255, a);
{ Assert.AreEqual(0, r);
Assert.That(a, Is.EqualTo(255)); Assert.AreEqual(0, g);
Assert.That(r, Is.Zero); Assert.AreEqual(0, b);
Assert.That(g, Is.Zero);
Assert.That(b, Is.Zero);
});
(r, g, b) = Red; (r, g, b) = Red;
Assert.Multiple(() => Assert.AreEqual(255, r);
{ Assert.AreEqual(0, g);
Assert.That(r, Is.EqualTo(255)); Assert.AreEqual(0, b);
Assert.That(g, Is.Zero);
Assert.That(b, Is.Zero);
});
(a, r, g, b) = Red; (a, r, g, b) = Red;
Assert.Multiple(() => Assert.AreEqual(255, a);
{ Assert.AreEqual(255, r);
Assert.That(a, Is.EqualTo(255)); Assert.AreEqual(0, g);
Assert.That(r, Is.EqualTo(255)); Assert.AreEqual(0, b);
Assert.That(g, Is.Zero);
Assert.That(b, Is.Zero);
});
(r, g, b) = Green; (r, g, b) = Green;
Assert.Multiple(() => Assert.AreEqual(0, r);
{ Assert.AreEqual(255, g);
Assert.That(r, Is.Zero); Assert.AreEqual(0, b);
Assert.That(g, Is.EqualTo(255));
Assert.That(b, Is.Zero);
});
(a, r, g, b) = Green; (a, r, g, b) = Green;
Assert.Multiple(() => Assert.AreEqual(255, a);
{ Assert.AreEqual(0, r);
Assert.That(a, Is.EqualTo(255)); Assert.AreEqual(255, g);
Assert.That(r, Is.Zero); Assert.AreEqual(0, b);
Assert.That(g, Is.EqualTo(255));
Assert.That(b, Is.Zero);
});
(r, g, b) = Blue; (r, g, b) = Blue;
Assert.Multiple(() => Assert.AreEqual(0, r);
{ Assert.AreEqual(0, g);
Assert.That(r, Is.Zero); Assert.AreEqual(255, b);
Assert.That(g, Is.Zero);
Assert.That(b, Is.EqualTo(255));
});
(a, r, g, b) = Blue; (a, r, g, b) = Blue;
Assert.Multiple(() => Assert.AreEqual(255, a);
{ Assert.AreEqual(0, r);
Assert.That(a, Is.EqualTo(255)); Assert.AreEqual(0, g);
Assert.That(r, Is.Zero); Assert.AreEqual(255, b);
Assert.That(g, Is.Zero);
Assert.That(b, Is.EqualTo(255));
});
} }
[Test] [TestMethod]
public void GetClosestConsoleColor_ShouldReturnClosestColor_GivenValidColor() public void GetClosestConsoleColor_ShouldReturnClosestColor_GivenValidColor()
{ {
Assert.Multiple(() => Assert.AreEqual(ConsoleColor.White, Color.Transparent.GetClosestConsoleColor());
{ Assert.AreEqual(ConsoleColor.White, Color.AliceBlue.GetClosestConsoleColor());
Assert.That(Color.Transparent.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); Assert.AreEqual(ConsoleColor.White, Color.AntiqueWhite.GetClosestConsoleColor());
Assert.That(Color.AliceBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); Assert.AreEqual(ConsoleColor.Cyan, Color.Aqua.GetClosestConsoleColor());
Assert.That(Color.AntiqueWhite.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); Assert.AreEqual(ConsoleColor.DarkGray, Color.Aquamarine.GetClosestConsoleColor());
Assert.That(Color.Aqua.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Cyan)); Assert.AreEqual(ConsoleColor.White, Color.Azure.GetClosestConsoleColor());
Assert.That(Color.Aquamarine.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); Assert.AreEqual(ConsoleColor.White, Color.Beige.GetClosestConsoleColor());
Assert.That(Color.Azure.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); Assert.AreEqual(ConsoleColor.White, Color.Bisque.GetClosestConsoleColor());
Assert.That(Color.Beige.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); Assert.AreEqual(ConsoleColor.Black, Color.Black.GetClosestConsoleColor());
Assert.That(Color.Bisque.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); Assert.AreEqual(ConsoleColor.White, Color.BlanchedAlmond.GetClosestConsoleColor());
Assert.That(Color.Black.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Black)); Assert.AreEqual(ConsoleColor.Blue, Color.Blue.GetClosestConsoleColor());
Assert.That(Color.BlanchedAlmond.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); Assert.AreEqual(ConsoleColor.DarkMagenta, Color.BlueViolet.GetClosestConsoleColor());
Assert.That(Color.Blue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Blue)); Assert.AreEqual(ConsoleColor.DarkRed, Color.Brown.GetClosestConsoleColor());
Assert.That(Color.BlueViolet.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkMagenta)); Assert.AreEqual(ConsoleColor.DarkGray, Color.BurlyWood.GetClosestConsoleColor());
Assert.That(Color.Brown.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkRed)); Assert.AreEqual(ConsoleColor.Gray, Color.CadetBlue.GetClosestConsoleColor());
Assert.That(Color.BurlyWood.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); Assert.AreEqual(ConsoleColor.Yellow, Color.Chartreuse.GetClosestConsoleColor());
Assert.That(Color.CadetBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Gray)); Assert.AreEqual(ConsoleColor.DarkYellow, Color.Chocolate.GetClosestConsoleColor());
Assert.That(Color.Chartreuse.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Yellow)); Assert.AreEqual(ConsoleColor.DarkYellow, Color.Coral.GetClosestConsoleColor());
Assert.That(Color.Chocolate.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkYellow)); Assert.AreEqual(ConsoleColor.DarkGray, Color.CornflowerBlue.GetClosestConsoleColor());
Assert.That(Color.Coral.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkYellow)); Assert.AreEqual(ConsoleColor.White, Color.Cornsilk.GetClosestConsoleColor());
Assert.That(Color.CornflowerBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); Assert.AreEqual(ConsoleColor.Red, Color.Crimson.GetClosestConsoleColor());
Assert.That(Color.Cornsilk.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); Assert.AreEqual(ConsoleColor.Cyan, Color.Cyan.GetClosestConsoleColor());
Assert.That(Color.Crimson.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Red)); Assert.AreEqual(ConsoleColor.DarkBlue, Color.DarkBlue.GetClosestConsoleColor());
Assert.That(Color.Cyan.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Cyan)); Assert.AreEqual(ConsoleColor.DarkCyan, Color.DarkCyan.GetClosestConsoleColor());
Assert.That(Color.DarkBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkBlue)); Assert.AreEqual(ConsoleColor.DarkYellow, Color.DarkGoldenrod.GetClosestConsoleColor());
Assert.That(Color.DarkCyan.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkCyan)); Assert.AreEqual(ConsoleColor.DarkGray, Color.DarkGray.GetClosestConsoleColor());
Assert.That(Color.DarkGoldenrod.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkYellow)); Assert.AreEqual(ConsoleColor.DarkGreen, Color.DarkGreen.GetClosestConsoleColor());
Assert.That(Color.DarkGray.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); Assert.AreEqual(ConsoleColor.DarkGray, Color.DarkKhaki.GetClosestConsoleColor());
Assert.That(Color.DarkGreen.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGreen)); Assert.AreEqual(ConsoleColor.DarkMagenta, Color.DarkMagenta.GetClosestConsoleColor());
Assert.That(Color.DarkKhaki.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); Assert.AreEqual(ConsoleColor.Gray, Color.DarkOliveGreen.GetClosestConsoleColor());
Assert.That(Color.DarkMagenta.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkMagenta)); Assert.AreEqual(ConsoleColor.DarkYellow, Color.DarkOrange.GetClosestConsoleColor());
Assert.That(Color.DarkOliveGreen.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Gray)); Assert.AreEqual(ConsoleColor.DarkMagenta, Color.DarkOrchid.GetClosestConsoleColor());
Assert.That(Color.DarkOrange.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkYellow)); Assert.AreEqual(ConsoleColor.DarkRed, Color.DarkRed.GetClosestConsoleColor());
Assert.That(Color.DarkOrchid.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkMagenta)); Assert.AreEqual(ConsoleColor.DarkGray, Color.DarkSalmon.GetClosestConsoleColor());
Assert.That(Color.DarkRed.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkRed)); Assert.AreEqual(ConsoleColor.DarkGray, Color.DarkSeaGreen.GetClosestConsoleColor());
Assert.That(Color.DarkSalmon.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); Assert.AreEqual(ConsoleColor.Gray, Color.DarkSlateBlue.GetClosestConsoleColor());
Assert.That(Color.DarkSeaGreen.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); Assert.AreEqual(ConsoleColor.DarkGreen, Color.DarkSlateGray.GetClosestConsoleColor());
Assert.That(Color.DarkSlateBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Gray)); Assert.AreEqual(ConsoleColor.Cyan, Color.DarkTurquoise.GetClosestConsoleColor());
Assert.That(Color.DarkSlateGray.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGreen)); Assert.AreEqual(ConsoleColor.DarkMagenta, Color.DarkViolet.GetClosestConsoleColor());
Assert.That(Color.DarkTurquoise.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Cyan)); Assert.AreEqual(ConsoleColor.Magenta, Color.DeepPink.GetClosestConsoleColor());
Assert.That(Color.DarkViolet.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkMagenta)); Assert.AreEqual(ConsoleColor.Cyan, Color.DeepSkyBlue.GetClosestConsoleColor());
Assert.That(Color.DeepPink.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Magenta)); Assert.AreEqual(ConsoleColor.Gray, Color.DimGray.GetClosestConsoleColor());
Assert.That(Color.DeepSkyBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Cyan)); Assert.AreEqual(ConsoleColor.Cyan, Color.DodgerBlue.GetClosestConsoleColor());
Assert.That(Color.DimGray.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Gray)); Assert.AreEqual(ConsoleColor.DarkRed, Color.Firebrick.GetClosestConsoleColor());
Assert.That(Color.DodgerBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Cyan)); Assert.AreEqual(ConsoleColor.White, Color.FloralWhite.GetClosestConsoleColor());
Assert.That(Color.Firebrick.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkRed)); Assert.AreEqual(ConsoleColor.Green, Color.ForestGreen.GetClosestConsoleColor());
Assert.That(Color.FloralWhite.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); Assert.AreEqual(ConsoleColor.Magenta, Color.Fuchsia.GetClosestConsoleColor());
Assert.That(Color.ForestGreen.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Green)); Assert.AreEqual(ConsoleColor.White, Color.Gainsboro.GetClosestConsoleColor());
Assert.That(Color.Fuchsia.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Magenta)); Assert.AreEqual(ConsoleColor.White, Color.GhostWhite.GetClosestConsoleColor());
Assert.That(Color.Gainsboro.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); Assert.AreEqual(ConsoleColor.Yellow, Color.Gold.GetClosestConsoleColor());
Assert.That(Color.GhostWhite.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); Assert.AreEqual(ConsoleColor.DarkYellow, Color.Goldenrod.GetClosestConsoleColor());
Assert.That(Color.Gold.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Yellow)); Assert.AreEqual(ConsoleColor.Gray, Color.Gray.GetClosestConsoleColor());
Assert.That(Color.Goldenrod.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkYellow)); Assert.AreEqual(ConsoleColor.Green, Color.Green.GetClosestConsoleColor());
Assert.That(Color.Gray.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Gray)); Assert.AreEqual(ConsoleColor.Yellow, Color.GreenYellow.GetClosestConsoleColor());
Assert.That(Color.Green.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Green)); Assert.AreEqual(ConsoleColor.White, Color.Honeydew.GetClosestConsoleColor());
Assert.That(Color.GreenYellow.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Yellow)); Assert.AreEqual(ConsoleColor.DarkGray, Color.HotPink.GetClosestConsoleColor());
Assert.That(Color.Honeydew.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); Assert.AreEqual(ConsoleColor.Gray, Color.IndianRed.GetClosestConsoleColor());
Assert.That(Color.HotPink.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); Assert.AreEqual(ConsoleColor.DarkMagenta, Color.Indigo.GetClosestConsoleColor());
Assert.That(Color.IndianRed.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Gray)); Assert.AreEqual(ConsoleColor.White, Color.Ivory.GetClosestConsoleColor());
Assert.That(Color.Indigo.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkMagenta)); Assert.AreEqual(ConsoleColor.DarkGray, Color.Khaki.GetClosestConsoleColor());
Assert.That(Color.Ivory.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); Assert.AreEqual(ConsoleColor.White, Color.Lavender.GetClosestConsoleColor());
Assert.That(Color.Khaki.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); Assert.AreEqual(ConsoleColor.White, Color.LavenderBlush.GetClosestConsoleColor());
Assert.That(Color.Lavender.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); Assert.AreEqual(ConsoleColor.Yellow, Color.LawnGreen.GetClosestConsoleColor());
Assert.That(Color.LavenderBlush.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); Assert.AreEqual(ConsoleColor.White, Color.LemonChiffon.GetClosestConsoleColor());
Assert.That(Color.LawnGreen.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Yellow)); Assert.AreEqual(ConsoleColor.DarkGray, Color.LightBlue.GetClosestConsoleColor());
Assert.That(Color.LemonChiffon.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); Assert.AreEqual(ConsoleColor.DarkGray, Color.LightCoral.GetClosestConsoleColor());
Assert.That(Color.LightBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); Assert.AreEqual(ConsoleColor.White, Color.LightCyan.GetClosestConsoleColor());
Assert.That(Color.LightCoral.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); Assert.AreEqual(ConsoleColor.White, Color.LightGoldenrodYellow.GetClosestConsoleColor());
Assert.That(Color.LightCyan.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); Assert.AreEqual(ConsoleColor.DarkGray, Color.LightGreen.GetClosestConsoleColor());
Assert.That(Color.LightGoldenrodYellow.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); Assert.AreEqual(ConsoleColor.DarkGray, Color.LightGray.GetClosestConsoleColor());
Assert.That(Color.LightGreen.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); Assert.AreEqual(ConsoleColor.DarkGray, Color.LightPink.GetClosestConsoleColor());
Assert.That(Color.LightGray.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); Assert.AreEqual(ConsoleColor.DarkGray, Color.LightSalmon.GetClosestConsoleColor());
Assert.That(Color.LightPink.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); Assert.AreEqual(ConsoleColor.DarkCyan, Color.LightSeaGreen.GetClosestConsoleColor());
Assert.That(Color.LightSalmon.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); Assert.AreEqual(ConsoleColor.DarkGray, Color.LightSkyBlue.GetClosestConsoleColor());
Assert.That(Color.LightSeaGreen.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkCyan)); Assert.AreEqual(ConsoleColor.Gray, Color.LightSlateGray.GetClosestConsoleColor());
Assert.That(Color.LightSkyBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); Assert.AreEqual(ConsoleColor.DarkGray, Color.LightSteelBlue.GetClosestConsoleColor());
Assert.That(Color.LightSlateGray.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Gray)); Assert.AreEqual(ConsoleColor.White, Color.LightYellow.GetClosestConsoleColor());
Assert.That(Color.LightSteelBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); Assert.AreEqual(ConsoleColor.Green, Color.Lime.GetClosestConsoleColor());
Assert.That(Color.LightYellow.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); Assert.AreEqual(ConsoleColor.Green, Color.LimeGreen.GetClosestConsoleColor());
Assert.That(Color.Lime.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Green)); Assert.AreEqual(ConsoleColor.White, Color.Linen.GetClosestConsoleColor());
Assert.That(Color.LimeGreen.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Green)); Assert.AreEqual(ConsoleColor.Magenta, Color.Magenta.GetClosestConsoleColor());
Assert.That(Color.Linen.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); Assert.AreEqual(ConsoleColor.DarkRed, Color.Maroon.GetClosestConsoleColor());
Assert.That(Color.Magenta.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Magenta)); Assert.AreEqual(ConsoleColor.DarkGray, Color.MediumAquamarine.GetClosestConsoleColor());
Assert.That(Color.Maroon.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkRed)); Assert.AreEqual(ConsoleColor.Blue, Color.MediumBlue.GetClosestConsoleColor());
Assert.That(Color.MediumAquamarine.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); Assert.AreEqual(ConsoleColor.DarkGray, Color.MediumOrchid.GetClosestConsoleColor());
Assert.That(Color.MediumBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Blue)); Assert.AreEqual(ConsoleColor.DarkGray, Color.MediumPurple.GetClosestConsoleColor());
Assert.That(Color.MediumOrchid.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); Assert.AreEqual(ConsoleColor.DarkCyan, Color.MediumSeaGreen.GetClosestConsoleColor());
Assert.That(Color.MediumPurple.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); Assert.AreEqual(ConsoleColor.DarkGray, Color.MediumSlateBlue.GetClosestConsoleColor());
Assert.That(Color.MediumSeaGreen.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkCyan)); Assert.AreEqual(ConsoleColor.Cyan, Color.MediumSpringGreen.GetClosestConsoleColor());
Assert.That(Color.MediumSlateBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); Assert.AreEqual(ConsoleColor.Cyan, Color.MediumTurquoise.GetClosestConsoleColor());
Assert.That(Color.MediumSpringGreen.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Cyan)); Assert.AreEqual(ConsoleColor.DarkMagenta, Color.MediumVioletRed.GetClosestConsoleColor());
Assert.That(Color.MediumTurquoise.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Cyan)); Assert.AreEqual(ConsoleColor.DarkBlue, Color.MidnightBlue.GetClosestConsoleColor());
Assert.That(Color.MediumVioletRed.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkMagenta)); Assert.AreEqual(ConsoleColor.White, Color.MintCream.GetClosestConsoleColor());
Assert.That(Color.MidnightBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkBlue)); Assert.AreEqual(ConsoleColor.White, Color.MistyRose.GetClosestConsoleColor());
Assert.That(Color.MintCream.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); Assert.AreEqual(ConsoleColor.White, Color.Moccasin.GetClosestConsoleColor());
Assert.That(Color.MistyRose.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); Assert.AreEqual(ConsoleColor.White, Color.NavajoWhite.GetClosestConsoleColor());
Assert.That(Color.Moccasin.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); Assert.AreEqual(ConsoleColor.DarkBlue, Color.Navy.GetClosestConsoleColor());
Assert.That(Color.NavajoWhite.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); Assert.AreEqual(ConsoleColor.White, Color.OldLace.GetClosestConsoleColor());
Assert.That(Color.Navy.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkBlue)); Assert.AreEqual(ConsoleColor.Gray, Color.Olive.GetClosestConsoleColor());
Assert.That(Color.OldLace.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); Assert.AreEqual(ConsoleColor.Gray, Color.OliveDrab.GetClosestConsoleColor());
Assert.That(Color.Olive.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Gray)); Assert.AreEqual(ConsoleColor.DarkYellow, Color.Orange.GetClosestConsoleColor());
Assert.That(Color.OliveDrab.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Gray)); Assert.AreEqual(ConsoleColor.Red, Color.OrangeRed.GetClosestConsoleColor());
Assert.That(Color.Orange.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkYellow)); Assert.AreEqual(ConsoleColor.DarkGray, Color.Orchid.GetClosestConsoleColor());
Assert.That(Color.OrangeRed.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Red)); Assert.AreEqual(ConsoleColor.White, Color.PaleGoldenrod.GetClosestConsoleColor());
Assert.That(Color.Orchid.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); Assert.AreEqual(ConsoleColor.DarkGray, Color.PaleGreen.GetClosestConsoleColor());
Assert.That(Color.PaleGoldenrod.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); Assert.AreEqual(ConsoleColor.White, Color.PaleTurquoise.GetClosestConsoleColor());
Assert.That(Color.PaleGreen.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); Assert.AreEqual(ConsoleColor.DarkGray, Color.PaleVioletRed.GetClosestConsoleColor());
Assert.That(Color.PaleTurquoise.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); Assert.AreEqual(ConsoleColor.White, Color.PapayaWhip.GetClosestConsoleColor());
Assert.That(Color.PaleVioletRed.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); Assert.AreEqual(ConsoleColor.White, Color.PeachPuff.GetClosestConsoleColor());
Assert.That(Color.PapayaWhip.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); Assert.AreEqual(ConsoleColor.DarkYellow, Color.Peru.GetClosestConsoleColor());
Assert.That(Color.PeachPuff.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); Assert.AreEqual(ConsoleColor.White, Color.Pink.GetClosestConsoleColor());
Assert.That(Color.Peru.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkYellow)); Assert.AreEqual(ConsoleColor.DarkGray, Color.Plum.GetClosestConsoleColor());
Assert.That(Color.Pink.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); Assert.AreEqual(ConsoleColor.DarkGray, Color.PowderBlue.GetClosestConsoleColor());
Assert.That(Color.Plum.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); Assert.AreEqual(ConsoleColor.DarkMagenta, Color.Purple.GetClosestConsoleColor());
Assert.That(Color.PowderBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray));
Assert.That(Color.Purple.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkMagenta));
#if NET6_0_OR_GREATER #if NET6_0_OR_GREATER
Assert.That(Color.RebeccaPurple.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkMagenta)); Assert.AreEqual(ConsoleColor.DarkMagenta, Color.RebeccaPurple.GetClosestConsoleColor());
#endif #endif
Assert.That(Color.Red.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Red)); Assert.AreEqual(ConsoleColor.Red, Color.Red.GetClosestConsoleColor());
Assert.That(Color.RosyBrown.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); Assert.AreEqual(ConsoleColor.DarkGray, Color.RosyBrown.GetClosestConsoleColor());
Assert.That(Color.RoyalBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkCyan)); Assert.AreEqual(ConsoleColor.DarkCyan, Color.RoyalBlue.GetClosestConsoleColor());
Assert.That(Color.SaddleBrown.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkRed)); Assert.AreEqual(ConsoleColor.DarkRed, Color.SaddleBrown.GetClosestConsoleColor());
Assert.That(Color.Salmon.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); Assert.AreEqual(ConsoleColor.DarkGray, Color.Salmon.GetClosestConsoleColor());
Assert.That(Color.SandyBrown.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkYellow)); Assert.AreEqual(ConsoleColor.DarkYellow, Color.SandyBrown.GetClosestConsoleColor());
Assert.That(Color.SeaGreen.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkCyan)); Assert.AreEqual(ConsoleColor.DarkCyan, Color.SeaGreen.GetClosestConsoleColor());
Assert.That(Color.SeaShell.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); Assert.AreEqual(ConsoleColor.White, Color.SeaShell.GetClosestConsoleColor());
Assert.That(Color.Sienna.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkRed)); Assert.AreEqual(ConsoleColor.DarkRed, Color.Sienna.GetClosestConsoleColor());
Assert.That(Color.Silver.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); Assert.AreEqual(ConsoleColor.DarkGray, Color.Silver.GetClosestConsoleColor());
Assert.That(Color.SkyBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); Assert.AreEqual(ConsoleColor.DarkGray, Color.SkyBlue.GetClosestConsoleColor());
Assert.That(Color.SlateBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Gray)); Assert.AreEqual(ConsoleColor.Gray, Color.SlateBlue.GetClosestConsoleColor());
Assert.That(Color.SlateGray.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Gray)); Assert.AreEqual(ConsoleColor.Gray, Color.SlateGray.GetClosestConsoleColor());
Assert.That(Color.Snow.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); Assert.AreEqual(ConsoleColor.White, Color.Snow.GetClosestConsoleColor());
Assert.That(Color.SpringGreen.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkCyan)); Assert.AreEqual(ConsoleColor.DarkCyan, Color.SpringGreen.GetClosestConsoleColor());
Assert.That(Color.SteelBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Gray)); Assert.AreEqual(ConsoleColor.Gray, Color.SteelBlue.GetClosestConsoleColor());
Assert.That(Color.Tan.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); Assert.AreEqual(ConsoleColor.DarkGray, Color.Tan.GetClosestConsoleColor());
Assert.That(Color.Teal.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkCyan)); Assert.AreEqual(ConsoleColor.DarkCyan, Color.Teal.GetClosestConsoleColor());
Assert.That(Color.Thistle.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); Assert.AreEqual(ConsoleColor.DarkGray, Color.Thistle.GetClosestConsoleColor());
Assert.That(Color.Tomato.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkYellow)); Assert.AreEqual(ConsoleColor.DarkYellow, Color.Tomato.GetClosestConsoleColor());
Assert.That(Color.Turquoise.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Cyan)); Assert.AreEqual(ConsoleColor.Cyan, Color.Turquoise.GetClosestConsoleColor());
Assert.That(Color.Violet.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray)); Assert.AreEqual(ConsoleColor.DarkGray, Color.Violet.GetClosestConsoleColor());
Assert.That(Color.Wheat.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); Assert.AreEqual(ConsoleColor.White, Color.Wheat.GetClosestConsoleColor());
Assert.That(Color.White.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); Assert.AreEqual(ConsoleColor.White, Color.White.GetClosestConsoleColor());
Assert.That(Color.WhiteSmoke.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White)); Assert.AreEqual(ConsoleColor.White, Color.WhiteSmoke.GetClosestConsoleColor());
Assert.That(Color.Yellow.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Yellow)); Assert.AreEqual(ConsoleColor.Yellow, Color.Yellow.GetClosestConsoleColor());
Assert.That(Color.YellowGreen.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Gray)); Assert.AreEqual(ConsoleColor.Gray, Color.YellowGreen.GetClosestConsoleColor());
});
} }
[Test] [TestMethod]
public void Inverted_ShouldReturnInvertedColor() public void Inverted_ShouldReturnInvertedColor()
{ {
Assert.That(Black.Inverted(), Is.EqualTo(White)); Assert.AreEqual(White, Black.Inverted());
Assert.That(White.Inverted(), Is.EqualTo(Black)); Assert.AreEqual(Black, White.Inverted());
Assert.That(Cyan.Inverted(), Is.EqualTo(Red)); Assert.AreEqual(Red, Cyan.Inverted());
Assert.That(Red.Inverted(), Is.EqualTo(Cyan)); Assert.AreEqual(Cyan, Red.Inverted());
Assert.That(Magenta.Inverted(), Is.EqualTo(Green)); Assert.AreEqual(Green, Magenta.Inverted());
Assert.That(Green.Inverted(), Is.EqualTo(Magenta)); Assert.AreEqual(Magenta, Green.Inverted());
Assert.That(Blue.Inverted(), Is.EqualTo(Yellow)); Assert.AreEqual(Yellow, Blue.Inverted());
Assert.That(Yellow.Inverted(), Is.EqualTo(Blue)); Assert.AreEqual(Blue, Yellow.Inverted());
} }
[Test] [TestMethod]
public void Inverted_ShouldIgnoreAlpha() public void Inverted_ShouldIgnoreAlpha()
{ {
Color expected = Color.FromArgb(255, 0, 0, 0); Color expected = Color.FromArgb(255, 0, 0, 0);
Color actual = Color.FromArgb(255, 255, 255, 255).Inverted(); Color actual = Color.FromArgb(255, 255, 255, 255).Inverted();
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
[Test] [TestMethod]
public void WithA0_ShouldReturnSameColor_GivenWhite() public void WithA0_ShouldReturnSameColor_GivenWhite()
{ {
Color transparent = Color.FromArgb(0, 255, 255, 255); Color transparent = Color.FromArgb(0, 255, 255, 255);
Assert.That(White.WithA(0), Is.EqualTo(transparent)); Assert.AreEqual(transparent, White.WithA(0));
Assert.That(transparent.WithA(0), Is.EqualTo(transparent)); Assert.AreEqual(transparent, transparent.WithA(0));
} }
[Test] [TestMethod]
public void WithB0_ShouldReturnYellow_GivenWhite() public void WithB0_ShouldReturnYellow_GivenWhite()
{ {
Assert.That(White.WithB(0), Is.EqualTo(Yellow)); Assert.AreEqual(Yellow, White.WithB(0));
Assert.That(Yellow.WithB(0), Is.EqualTo(Yellow)); Assert.AreEqual(Yellow, Yellow.WithB(0));
} }
[Test] [TestMethod]
public void WithG0_ShouldReturnMagenta_GivenWhite() public void WithG0_ShouldReturnMagenta_GivenWhite()
{ {
Assert.That(White.WithG(0), Is.EqualTo(Magenta)); Assert.AreEqual(Magenta, White.WithG(0));
Assert.That(Magenta.WithG(0), Is.EqualTo(Magenta)); Assert.AreEqual(Magenta, Magenta.WithG(0));
} }
[Test] [TestMethod]
public void WithR0_ShouldReturnCyan_GivenWhite() public void WithR0_ShouldReturnCyan_GivenWhite()
{ {
Assert.That(White.WithR(0), Is.EqualTo(Cyan)); Assert.AreEqual(Cyan, White.WithR(0));
Assert.That(Cyan.WithR(0), Is.EqualTo(Cyan)); Assert.AreEqual(Cyan, Cyan.WithR(0));
} }
} }

View File

@ -1,82 +1,82 @@
using System.Numerics; using System.Numerics;
using NUnit.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting;
using X10D.Drawing; using X10D.Drawing;
namespace X10D.Tests.Drawing; namespace X10D.Tests.Drawing;
[TestFixture] [TestClass]
internal class CuboidTests public class CuboidTests
{ {
[Test] [TestMethod]
public void Corners_ShouldBeCorrect_GivenCubeOfSize1() public void Corners_ShouldBeCorrect_GivenCubeOfSize1()
{ {
Cuboid cube = Cuboid.Cube; Cuboid cube = Cuboid.Cube;
Assert.That(cube.FrontTopRight, Is.EqualTo(new Vector3(0.5f, 0.5f, -0.5f))); Assert.AreEqual(new Vector3(0.5f, 0.5f, -0.5f), cube.FrontTopRight);
Assert.That(cube.FrontTopLeft, Is.EqualTo(new Vector3(-0.5f, 0.5f, -0.5f))); Assert.AreEqual(new Vector3(-0.5f, 0.5f, -0.5f), cube.FrontTopLeft);
Assert.That(cube.FrontBottomRight, Is.EqualTo(new Vector3(0.5f, -0.5f, -0.5f))); Assert.AreEqual(new Vector3(0.5f, -0.5f, -0.5f), cube.FrontBottomRight);
Assert.That(cube.FrontBottomLeft, Is.EqualTo(new Vector3(-0.5f, -0.5f, -0.5f))); Assert.AreEqual(new Vector3(-0.5f, -0.5f, -0.5f), cube.FrontBottomLeft);
Assert.That(cube.BackTopRight, Is.EqualTo(new Vector3(0.5f, 0.5f, 0.5f))); Assert.AreEqual(new Vector3(0.5f, 0.5f, 0.5f), cube.BackTopRight);
Assert.That(cube.BackTopLeft, Is.EqualTo(new Vector3(-0.5f, 0.5f, 0.5f))); Assert.AreEqual(new Vector3(-0.5f, 0.5f, 0.5f), cube.BackTopLeft);
Assert.That(cube.BackBottomRight, Is.EqualTo(new Vector3(0.5f, -0.5f, 0.5f))); Assert.AreEqual(new Vector3(0.5f, -0.5f, 0.5f), cube.BackBottomRight);
Assert.That(cube.BackBottomLeft, Is.EqualTo(new Vector3(-0.5f, -0.5f, 0.5f))); Assert.AreEqual(new Vector3(-0.5f, -0.5f, 0.5f), cube.BackBottomLeft);
} }
[Test] [TestMethod]
public void Equals_ShouldBeTrue_GivenTwoCubesOfSize1() public void Equals_ShouldBeTrue_GivenTwoCubesOfSize1()
{ {
var cube1 = Cuboid.Cube; var cube1 = Cuboid.Cube;
var cube2 = Cuboid.Cube; var cube2 = Cuboid.Cube;
Assert.That(cube1, Is.EqualTo(cube2)); Assert.AreEqual(cube1, cube2);
Assert.That(cube2, Is.EqualTo(cube1)); Assert.IsTrue(cube1 == cube2);
Assert.That(cube1 == cube2); Assert.IsFalse(cube1 != cube2);
Assert.That(cube2 == cube1);
} }
[Test] [TestMethod]
public void Equals_ShouldBeFalse_GivenDifferentCubes() public void Equals_ShouldBeFalse_GivenDifferentCubes()
{ {
Assert.That(Cuboid.Empty, Is.Not.EqualTo(Cuboid.Cube)); Assert.AreNotEqual(Cuboid.Cube, Cuboid.Empty);
Assert.That(Cuboid.Empty != Cuboid.Cube); Assert.IsFalse(Cuboid.Cube == Cuboid.Empty);
Assert.IsTrue(Cuboid.Cube != Cuboid.Empty);
} }
[Test] [TestMethod]
public void Equals_ShouldBeFalse_GivenDifferentObjects() public void Equals_ShouldBeFalse_GivenDifferentObjects()
{ {
Assert.That(Cuboid.Cube.Equals(null), Is.False); Assert.IsFalse(Cuboid.Cube.Equals(null));
} }
[Test] [TestMethod]
public void GetHashCode_ShouldBeCorrect_GivenEmptyCircle() public void GetHashCode_ShouldBeCorrect_GivenEmptyCircle()
{ {
// this test is pretty pointless, it exists only for code coverage purposes // this test is pretty pointless, it exists only for code coverage purposes
int hashCode = Cuboid.Empty.GetHashCode(); int hashCode = Cuboid.Empty.GetHashCode();
Assert.That(Cuboid.Empty.GetHashCode(), Is.EqualTo(hashCode)); Assert.AreEqual(hashCode, Cuboid.Empty.GetHashCode());
} }
[Test] [TestMethod]
public void GetHashCode_ShouldBeCorrect_GivenCubeOfSize1() public void GetHashCode_ShouldBeCorrect_GivenCubeOfSize1()
{ {
// this test is pretty pointless, it exists only for code coverage purposes // this test is pretty pointless, it exists only for code coverage purposes
int hashCode = Cuboid.Cube.GetHashCode(); int hashCode = Cuboid.Cube.GetHashCode();
Assert.That(Cuboid.Cube.GetHashCode(), Is.EqualTo(hashCode)); Assert.AreEqual(hashCode, Cuboid.Cube.GetHashCode());
} }
[Test] [TestMethod]
public void Size_ShouldBeOne_GivenCubeOfSize1() public void Size_ShouldBeOne_GivenCubeOfSize1()
{ {
Assert.That(Cuboid.Cube.Size, Is.EqualTo(Vector3.One)); Assert.AreEqual(Vector3.One, Cuboid.Cube.Size);
} }
[Test] [TestMethod]
public void Size_ShouldBeOne_GivenRotatedCube() public void Size_ShouldBeOne_GivenRotatedCube()
{ {
Assert.That(new Cuboid(0, 0, 0, 1, 1, 1, 90, 0, 0).Size, Is.EqualTo(Vector3.One)); Assert.AreEqual(Vector3.One, new Cuboid(0, 0, 0, 1, 1, 1, 90, 0, 0).Size);
} }
[Test] [TestMethod]
public void Volume_ShouldBe1_GivenCubeOfSize1() public void Volume_ShouldBe1_GivenCubeOfSize1()
{ {
Assert.That(Cuboid.Cube.Volume, Is.EqualTo(1.0f).Within(1e-6f)); Assert.AreEqual(1.0f, Cuboid.Cube.Volume, 1e-6f);
} }
} }

View File

@ -1,171 +1,156 @@
using System.Drawing; using System.Drawing;
using System.Numerics; using System.Numerics;
using NUnit.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting;
using X10D.Drawing; using X10D.Drawing;
namespace X10D.Tests.Drawing; namespace X10D.Tests.Drawing;
[TestFixture] [TestClass]
internal class EllipseFTests public class EllipseFTests
{ {
[Test] [TestMethod]
public void Area_ShouldBePiRadiusRadius_GivenUnitEllipse() public void Area_ShouldBePiRadiusRadius_GivenUnitEllipse()
{ {
var unitEllipse = EllipseF.Unit; var unitEllipse = EllipseF.Unit;
Assert.That(unitEllipse.Area, Is.EqualTo(MathF.PI).Within(1e-6f)); Assert.AreEqual(MathF.PI, unitEllipse.Area, 1e-6f);
} }
[Test] [TestMethod]
public void ApproximateCircumference_ShouldBe2PiRadius_GivenUnitEllipse() public void ApproximateCircumference_ShouldBe2PiRadius_GivenUnitEllipse()
{ {
var unitEllipse = EllipseF.Unit; var unitEllipse = EllipseF.Unit;
Assert.That(unitEllipse.ApproximateCircumference, Is.EqualTo(2 * MathF.PI).Within(1e-6f)); Assert.AreEqual(2 * MathF.PI, unitEllipse.ApproximateCircumference, 1e-6f);
} }
[Test] [TestMethod]
public void Constructor_ShouldGiveCorrectEllipse() public void Constructor_ShouldGiveCorrectEllipse()
{ {
var ellipse = new EllipseF(PointF.Empty, new SizeF(2, 1)); var ellipse = new EllipseF(PointF.Empty, new SizeF(2, 1));
Assert.That(ellipse.Center, Is.EqualTo(new PointF(0, 0))); Assert.AreEqual(new PointF(0, 0), ellipse.Center);
Assert.That(ellipse.Radius, Is.EqualTo(new SizeF(2, 1))); Assert.AreEqual(new SizeF(2, 1), ellipse.Radius);
ellipse = new EllipseF(0, 0, 2, 1); ellipse = new EllipseF(0, 0, 2, 1);
Assert.That(ellipse.Center, Is.EqualTo(new PointF(0, 0))); Assert.AreEqual(new PointF(0, 0), ellipse.Center);
Assert.That(ellipse.Radius, Is.EqualTo(new SizeF(2, 1))); Assert.AreEqual(new SizeF(2, 1), ellipse.Radius);
ellipse = new EllipseF(PointF.Empty, new Vector2(2, 1)); ellipse = new EllipseF(PointF.Empty, new Vector2(2, 1));
Assert.That(ellipse.Center, Is.EqualTo(new PointF(0, 0))); Assert.AreEqual(new PointF(0, 0), ellipse.Center);
Assert.That(ellipse.Radius, Is.EqualTo(new SizeF(2, 1))); Assert.AreEqual(new SizeF(2, 1), ellipse.Radius);
ellipse = new EllipseF(Vector2.Zero, new Vector2(2, 1)); ellipse = new EllipseF(Vector2.Zero, new Vector2(2, 1));
Assert.That(ellipse.Center, Is.EqualTo(new PointF(0, 0))); Assert.AreEqual(new PointF(0, 0), ellipse.Center);
Assert.That(ellipse.Radius, Is.EqualTo(new SizeF(2, 1))); Assert.AreEqual(new SizeF(2, 1), ellipse.Radius);
} }
[Test] [TestMethod]
public void Equals_ShouldBeTrue_GivenTwoUnitEllipses() public void Equals_ShouldBeTrue_GivenTwoUnitEllipses()
{ {
var unitEllipse1 = EllipseF.Unit; var unitEllipse1 = EllipseF.Unit;
var unitEllipse2 = EllipseF.Unit; var unitEllipse2 = EllipseF.Unit;
Assert.That(unitEllipse2, Is.EqualTo(unitEllipse1)); Assert.AreEqual(unitEllipse1, unitEllipse2);
Assert.That(unitEllipse1, Is.EqualTo(unitEllipse2)); Assert.IsTrue(unitEllipse1 == unitEllipse2);
Assert.That(unitEllipse2 == unitEllipse1); Assert.IsFalse(unitEllipse1 != unitEllipse2);
Assert.That(unitEllipse1 == unitEllipse2);
} }
[Test] [TestMethod]
public void Equals_ShouldBeFalse_GivenDifferentEllipses() public void Equals_ShouldBeFalse_GivenDifferentEllipses()
{ {
Assert.That(EllipseF.Empty, Is.Not.EqualTo(EllipseF.Unit)); Assert.AreNotEqual(EllipseF.Unit, EllipseF.Empty);
Assert.That(EllipseF.Empty != EllipseF.Unit); Assert.IsFalse(EllipseF.Unit == EllipseF.Empty);
Assert.IsTrue(EllipseF.Unit != EllipseF.Empty);
} }
[Test] [TestMethod]
public void Equals_ShouldBeFalse_GivenDifferentObjects() public void Equals_ShouldBeFalse_GivenDifferentObjects()
{ {
Assert.That(EllipseF.Unit, Is.Not.EqualTo(null)); Assert.IsFalse(EllipseF.Unit.Equals(null));
Assert.That(EllipseF.Unit.Equals(null), Is.False);
} }
[Test] [TestMethod]
public void GetHashCode_ShouldBeCorrect_GivenEmptyEllipse() public void GetHashCode_ShouldBeCorrect_GivenEmptyEllipse()
{ {
// this test is pretty pointless, it exists only for code coverage purposes // this test is pretty pointless, it exists only for code coverage purposes
int hashCode = EllipseF.Empty.GetHashCode(); int hashCode = EllipseF.Empty.GetHashCode();
Assert.That(EllipseF.Empty.GetHashCode(), Is.EqualTo(hashCode)); Assert.AreEqual(hashCode, EllipseF.Empty.GetHashCode());
} }
[Test] [TestMethod]
public void GetHashCode_ShouldBeCorrect_GivenUnitEllipse() public void GetHashCode_ShouldBeCorrect_GivenUnitEllipse()
{ {
// this test is pretty pointless, it exists only for code coverage purposes // this test is pretty pointless, it exists only for code coverage purposes
int hashCode = EllipseF.Unit.GetHashCode(); int hashCode = EllipseF.Unit.GetHashCode();
Assert.That(EllipseF.Unit.GetHashCode(), Is.EqualTo(hashCode)); Assert.AreEqual(hashCode, EllipseF.Unit.GetHashCode());
} }
[Test] [TestMethod]
public void HorizontalRadius_ShouldBe0_GivenEmptyEllipse() public void HorizontalRadius_ShouldBe0_GivenEmptyEllipse()
{ {
Assert.That(EllipseF.Empty.HorizontalRadius, Is.Zero); Assert.AreEqual(0, EllipseF.Empty.HorizontalRadius);
} }
[Test] [TestMethod]
public void HorizontalRadius_ShouldBe1_GivenUnitEllipse() public void HorizontalRadius_ShouldBe1_GivenUnitEllipse()
{ {
Assert.That(EllipseF.Unit.HorizontalRadius, Is.EqualTo(1)); Assert.AreEqual(1, EllipseF.Unit.HorizontalRadius);
} }
[Test] [TestMethod]
public void op_Explicit_ShouldReturnEquivalentEllipse_GivenEllipse() public void op_Explicit_ShouldReturnEquivalentEllipse_GivenEllipse()
{ {
EllipseF unitEllipse = EllipseF.Unit; EllipseF unitEllipse = EllipseF.Unit;
Ellipse converted = (Ellipse)unitEllipse; Ellipse converted = (Ellipse)unitEllipse;
Assert.Multiple(() => Assert.AreEqual(unitEllipse, converted);
{ Assert.AreEqual(unitEllipse.HorizontalRadius, converted.HorizontalRadius);
Assert.That(converted, Is.EqualTo((Ellipse)unitEllipse)); Assert.AreEqual(unitEllipse.VerticalRadius, converted.VerticalRadius);
Assert.That(converted == unitEllipse); Assert.AreEqual(unitEllipse.Center, converted.Center);
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));
});
} }
[Test] [TestMethod]
public void op_Implicit_ShouldReturnEquivalentEllipse_GivenCircle() public void op_Implicit_ShouldReturnEquivalentEllipse_GivenCircle()
{ {
Circle unitCircle = Circle.Unit; Circle unitCircle = Circle.Unit;
EllipseF converted = unitCircle; EllipseF converted = unitCircle;
Assert.Multiple(() => Assert.AreEqual(unitCircle, converted);
{ Assert.AreEqual(unitCircle.Radius, converted.HorizontalRadius);
Assert.That(converted, Is.EqualTo((EllipseF)unitCircle)); Assert.AreEqual(unitCircle.Radius, converted.VerticalRadius);
Assert.That(converted == unitCircle); Assert.AreEqual(unitCircle.Center, converted.Center);
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));
});
} }
[Test] [TestMethod]
public void op_Implicit_ShouldReturnEquivalentEllipse_GivenCircleF() public void op_Implicit_ShouldReturnEquivalentEllipse_GivenCircleF()
{ {
CircleF unitCircle = CircleF.Unit; CircleF unitCircle = CircleF.Unit;
EllipseF converted = unitCircle; EllipseF converted = unitCircle;
Assert.Multiple(() => Assert.AreEqual(unitCircle, converted);
{ Assert.AreEqual(unitCircle.Radius, converted.HorizontalRadius);
Assert.That(converted, Is.EqualTo((EllipseF)unitCircle)); Assert.AreEqual(unitCircle.Radius, converted.VerticalRadius);
Assert.That(converted.HorizontalRadius, Is.EqualTo(unitCircle.Radius)); Assert.AreEqual(unitCircle.Center, converted.Center);
Assert.That(converted.VerticalRadius, Is.EqualTo(unitCircle.Radius));
Assert.That(converted.Center, Is.EqualTo(unitCircle.Center));
});
} }
[Test] [TestMethod]
public void op_Implicit_ShouldReturnEquivalentEllipse_GivenEllipse() public void op_Implicit_ShouldReturnEquivalentEllipse_GivenEllipse()
{ {
Ellipse unitEllipse = Ellipse.Unit; Ellipse unitEllipse = Ellipse.Unit;
EllipseF converted = unitEllipse; EllipseF converted = unitEllipse;
Assert.Multiple(() => Assert.AreEqual(unitEllipse, converted);
{ Assert.AreEqual(unitEllipse.HorizontalRadius, converted.HorizontalRadius);
Assert.That(converted, Is.EqualTo((EllipseF)unitEllipse)); Assert.AreEqual(unitEllipse.VerticalRadius, converted.VerticalRadius);
Assert.That(converted.HorizontalRadius, Is.EqualTo(unitEllipse.HorizontalRadius)); Assert.AreEqual(unitEllipse.Center, converted.Center);
Assert.That(converted.VerticalRadius, Is.EqualTo(unitEllipse.VerticalRadius));
Assert.That(converted.Center, Is.EqualTo((PointF)unitEllipse.Center));
});
} }
[Test] [TestMethod]
public void VerticalRadius_ShouldBe0_GivenEmptyEllipse() public void VerticalRadius_ShouldBe0_GivenEmptyEllipse()
{ {
Assert.That(EllipseF.Empty.VerticalRadius, Is.Zero); Assert.AreEqual(0, EllipseF.Empty.VerticalRadius);
} }
[Test] [TestMethod]
public void VerticalRadius_ShouldBe1_GivenUnitEllipse() public void VerticalRadius_ShouldBe1_GivenUnitEllipse()
{ {
Assert.That(EllipseF.Unit.VerticalRadius, Is.EqualTo(1)); Assert.AreEqual(1, EllipseF.Unit.VerticalRadius);
} }
} }

View File

@ -1,128 +1,111 @@
using System.Drawing; using System.Drawing;
using NUnit.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting;
using X10D.Drawing; using X10D.Drawing;
namespace X10D.Tests.Drawing; namespace X10D.Tests.Drawing;
[TestFixture] [TestClass]
internal class EllipseTests public class EllipseTests
{ {
[Test] [TestMethod]
public void Area_ShouldBePiRadiusRadius_GivenUnitEllipse() public void Area_ShouldBePiRadiusRadius_GivenUnitEllipse()
{ {
var unitEllipse = Ellipse.Unit; var unitEllipse = Ellipse.Unit;
Assert.That(unitEllipse.Area, Is.EqualTo(MathF.PI).Within(1e-6f)); Assert.AreEqual(MathF.PI, unitEllipse.Area, 1e-6f);
} }
[Test] [TestMethod]
public void ApproximateCircumference_ShouldBe2PiRadius_GivenUnitEllipse() public void ApproximateCircumference_ShouldBe2PiRadius_GivenUnitEllipse()
{ {
var unitEllipse = Ellipse.Unit; var unitEllipse = Ellipse.Unit;
Assert.That(unitEllipse.ApproximateCircumference, Is.EqualTo(2.0f * MathF.PI).Within(1e-6f)); Assert.AreEqual(2 * MathF.PI, unitEllipse.ApproximateCircumference, 1e-6f);
} }
[Test] [TestMethod]
public void Constructor_ShouldGiveCorrectEllipse() public void Constructor_ShouldGiveCorrectEllipse()
{ {
var ellipse = new Ellipse(Point.Empty, new Size(2, 1)); var ellipse = new Ellipse(Point.Empty, new Size(2, 1));
Assert.Multiple(() => Assert.AreEqual(new Point(0, 0), ellipse.Center);
{ Assert.AreEqual(new Size(2, 1), ellipse.Radius);
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); ellipse = new Ellipse(0, 0, 2, 1);
Assert.Multiple(() => Assert.AreEqual(new Point(0, 0), ellipse.Center);
{ Assert.AreEqual(new Size(2, 1), ellipse.Radius);
Assert.That(ellipse.Center, Is.EqualTo(new Point(0, 0)));
Assert.That(ellipse.Radius, Is.EqualTo(new Size(2, 1)));
});
} }
[Test] [TestMethod]
public void Equals_ShouldBeTrue_GivenTwoUnitEllipses() public void Equals_ShouldBeTrue_GivenTwoUnitEllipses()
{ {
var unitEllipse1 = Ellipse.Unit; var unitEllipse1 = Ellipse.Unit;
var unitEllipse2 = Ellipse.Unit; var unitEllipse2 = Ellipse.Unit;
Assert.Multiple(() => Assert.AreEqual(unitEllipse1, unitEllipse2);
{ Assert.IsTrue(unitEllipse1 == unitEllipse2);
Assert.That(unitEllipse2, Is.EqualTo(unitEllipse1)); Assert.IsFalse(unitEllipse1 != unitEllipse2);
Assert.That(unitEllipse1, Is.EqualTo(unitEllipse2));
Assert.That(unitEllipse2 == unitEllipse1);
Assert.That(unitEllipse1 == unitEllipse2);
});
} }
[Test] [TestMethod]
public void Equals_ShouldBeFalse_GivenDifferentEllipses() public void Equals_ShouldBeFalse_GivenDifferentEllipses()
{ {
Assert.Multiple(() => Assert.AreNotEqual(Ellipse.Unit, Ellipse.Empty);
{ Assert.IsFalse(Ellipse.Unit == Ellipse.Empty);
Assert.That(Ellipse.Empty, Is.Not.EqualTo(Ellipse.Unit)); Assert.IsTrue(Ellipse.Unit != Ellipse.Empty);
Assert.That(Ellipse.Unit, Is.Not.EqualTo(Ellipse.Empty));
Assert.That(Ellipse.Empty != Ellipse.Unit);
Assert.That(Ellipse.Unit != Ellipse.Empty);
});
} }
[Test] [TestMethod]
public void Equals_ShouldBeFalse_GivenDifferentObjects() public void Equals_ShouldBeFalse_GivenDifferentObjects()
{ {
Assert.That(Ellipse.Unit.Equals(null), Is.False); Assert.IsFalse(Ellipse.Unit.Equals(null));
} }
[Test] [TestMethod]
public void GetHashCode_ShouldBeCorrect_GivenEmptyEllipse() public void GetHashCode_ShouldBeCorrect_GivenEmptyEllipse()
{ {
// this test is pretty pointless, it exists only for code coverage purposes // this test is pretty pointless, it exists only for code coverage purposes
int hashCode = Ellipse.Empty.GetHashCode(); int hashCode = Ellipse.Empty.GetHashCode();
Assert.That(Ellipse.Empty.GetHashCode(), Is.EqualTo(hashCode)); Assert.AreEqual(hashCode, Ellipse.Empty.GetHashCode());
} }
[Test] [TestMethod]
public void GetHashCode_ShouldBeCorrect_GivenUnitEllipse() public void GetHashCode_ShouldBeCorrect_GivenUnitEllipse()
{ {
// this test is pretty pointless, it exists only for code coverage purposes // this test is pretty pointless, it exists only for code coverage purposes
int hashCode = Ellipse.Unit.GetHashCode(); int hashCode = Ellipse.Unit.GetHashCode();
Assert.That(Ellipse.Unit.GetHashCode(), Is.EqualTo(hashCode)); Assert.AreEqual(hashCode, Ellipse.Unit.GetHashCode());
} }
[Test] [TestMethod]
public void HorizontalRadius_ShouldBe0_GivenEmptyEllipse() public void HorizontalRadius_ShouldBe0_GivenEmptyEllipse()
{ {
Assert.That(Ellipse.Empty.HorizontalRadius, Is.Zero); Assert.AreEqual(0, Ellipse.Empty.HorizontalRadius);
} }
[Test] [TestMethod]
public void HorizontalRadius_ShouldBe1_GivenUnitEllipse() public void HorizontalRadius_ShouldBe1_GivenUnitEllipse()
{ {
Assert.That(Ellipse.Unit.HorizontalRadius, Is.EqualTo(1)); Assert.AreEqual(1, Ellipse.Unit.HorizontalRadius);
} }
[Test] [TestMethod]
public void op_Implicit_ShouldReturnEquivalentEllipse_GivenCircle() public void op_Implicit_ShouldReturnEquivalentEllipse_GivenCircle()
{ {
Circle unitCircle = Circle.Unit; Circle unitCircle = Circle.Unit;
Ellipse converted = unitCircle; Ellipse converted = unitCircle;
Assert.Multiple(() => Assert.AreEqual(unitCircle, converted);
{ Assert.AreEqual(unitCircle.Radius, converted.HorizontalRadius);
Assert.That(converted, Is.EqualTo((Ellipse)unitCircle)); Assert.AreEqual(unitCircle.Radius, converted.VerticalRadius);
Assert.That(converted.HorizontalRadius, Is.EqualTo(unitCircle.Radius)); Assert.AreEqual(unitCircle.Center, converted.Center);
Assert.That(converted.VerticalRadius, Is.EqualTo(unitCircle.Radius));
Assert.That(converted.Center, Is.EqualTo(unitCircle.Center));
});
} }
[Test] [TestMethod]
public void VerticalRadius_ShouldBe0_GivenEmptyEllipse() public void VerticalRadius_ShouldBe0_GivenEmptyEllipse()
{ {
Assert.That(Ellipse.Empty.VerticalRadius, Is.Zero); Assert.AreEqual(0, Ellipse.Empty.VerticalRadius);
} }
[Test] [TestMethod]
public void VerticalRadius_ShouldBe1_GivenUnitEllipse() public void VerticalRadius_ShouldBe1_GivenUnitEllipse()
{ {
Assert.That(Ellipse.Unit.VerticalRadius, Is.EqualTo(1)); Assert.AreEqual(1, Ellipse.Unit.VerticalRadius);
} }
} }

View File

@ -1,115 +1,116 @@
using System.Drawing; using System.Drawing;
using System.Numerics; using System.Numerics;
using NUnit.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting;
using X10D.Drawing; using X10D.Drawing;
namespace X10D.Tests.Drawing; namespace X10D.Tests.Drawing;
[TestFixture] [TestClass]
internal class Line3DTests public class Line3DTests
{ {
[Test] [TestMethod]
public void CompareTo_ShouldBeNegativeOne_GivenEmptyAndOne() public void CompareTo_ShouldBeNegativeOne_GivenEmptyAndOne()
{ {
Assert.That(Line3D.Empty.CompareTo(Line3D.One), Is.EqualTo(-1)); Assert.AreEqual(-1, Line3D.Empty.CompareTo(Line3D.One));
} }
[Test] [TestMethod]
public void CompareTo_ShouldBeNegativeOne_GivenEmptyLineAndOneLineAsObject() public void CompareTo_ShouldBeNegativeOne_GivenEmptyLineAndOneLineAsObject()
{ {
Assert.That(Line3D.Empty.CompareTo((object)Line3D.One), Is.EqualTo(-1)); Assert.AreEqual(-1, Line3D.Empty.CompareTo((object)Line3D.One));
} }
[Test] [TestMethod]
public void CompareTo_ShouldBeOne_GivenNull() public void CompareTo_ShouldBeOne_GivenNull()
{ {
Assert.That(Line3D.One.CompareTo(null), Is.EqualTo(1)); Assert.AreEqual(1, Line3D.One.CompareTo(null));
} }
[Test] [TestMethod]
public void CompareTo_ShouldBeOne_GivenOneAndEmpty() public void CompareTo_ShouldBeOne_GivenOneAndEmpty()
{ {
Assert.That(Line3D.One.CompareTo(Line3D.Empty), Is.EqualTo(1)); Assert.AreEqual(1, Line3D.One.CompareTo(Line3D.Empty));
} }
[Test] [TestMethod]
public void CompareTo_ShouldBeZero_GivenUnitLine() public void CompareTo_ShouldBeZero_GivenUnitLine()
{ {
var unitLine3D = Line3D.One; var unitLine3D = Line3D.One;
Assert.That(unitLine3D.CompareTo(unitLine3D), Is.Zero); Assert.AreEqual(0, unitLine3D.CompareTo(unitLine3D));
} }
[Test] [TestMethod]
public void CompareTo_ShouldThrowArgumentException_GivenInvalidType() public void CompareTo_ShouldThrowArgumentException_GivenInvalidType()
{ {
Assert.Throws<ArgumentException>(() => _ = Line3D.Empty.CompareTo(new object())); Assert.ThrowsException<ArgumentException>(() => Line3D.Empty.CompareTo(new object()));
} }
[Test] [TestMethod]
public void Length_ShouldBe0_GivenEmptyLine() public void Length_ShouldBe0_GivenEmptyLine()
{ {
Assert.That(Line3D.Empty.Length, Is.Zero); Assert.AreEqual(0.0f, Line3D.Empty.Length);
} }
[Test] [TestMethod]
public void Length_ShouldBe1_GivenUnitXLine() public void Length_ShouldBe1_GivenUnitXLine()
{ {
Assert.That(Line3D.UnitX.Length, Is.EqualTo(1.0f).Within(1e-6f)); Assert.AreEqual(1.0f, Line3D.UnitX.Length, 1e-6f);
} }
[Test] [TestMethod]
public void Length_ShouldBe1_GivenUnitYLine() public void Length_ShouldBe1_GivenUnitYLine()
{ {
Assert.That(Line3D.UnitY.Length, Is.EqualTo(1.0f).Within(1e-6f)); Assert.AreEqual(1.0f, Line3D.UnitY.Length, 1e-6f);
} }
[Test] [TestMethod]
public void Length_ShouldBe1_GivenUnitZLine() public void Length_ShouldBe1_GivenUnitZLine()
{ {
Assert.That(Line3D.UnitZ.Length, Is.EqualTo(1.0f).Within(1e-6f)); Assert.AreEqual(1.0f, Line3D.UnitZ.Length, 1e-6f);
} }
[Test] [TestMethod]
public void Equals_ShouldBeTrue_GivenTwoUnitLines() public void Equals_ShouldBeTrue_GivenTwoUnitLines()
{ {
Line3D first = Line3D.One; Line3D first = Line3D.One;
Line3D second = Line3D.One; Line3D second = Line3D.One;
Assert.That(second, Is.EqualTo(first)); Assert.AreEqual(first, second);
Assert.That(second == first); Assert.IsTrue(first == second);
Assert.IsFalse(first != second);
} }
[Test] [TestMethod]
public void Equals_ShouldBeFalse_GivenDifferentLines() public void Equals_ShouldBeFalse_GivenDifferentLines()
{ {
Assert.That(Line3D.Empty, Is.Not.EqualTo(Line3D.One)); Assert.AreNotEqual(Line3D.One, Line3D.Empty);
Assert.That(Line3D.Empty != Line3D.One); Assert.IsFalse(Line3D.One == Line3D.Empty);
Assert.IsTrue(Line3D.One != Line3D.Empty);
} }
[Test] [TestMethod]
public void Equals_ShouldBeFalse_GivenDifferentObjects() public void Equals_ShouldBeFalse_GivenDifferentObjects()
{ {
Assert.That(Line3D.One, Is.Not.EqualTo(null)); Assert.IsFalse(Line3D.One.Equals(null));
Assert.That(Line3D.One.Equals(null), Is.False);
} }
[Test] [TestMethod]
public void GetHashCode_ShouldBeCorrect_GivenEmptyLine() public void GetHashCode_ShouldBeCorrect_GivenEmptyLine()
{ {
// this test is pretty pointless, it exists only for code coverage purposes // this test is pretty pointless, it exists only for code coverage purposes
int hashCode = Line3D.Empty.GetHashCode(); int hashCode = Line3D.Empty.GetHashCode();
Assert.That(Line3D.Empty.GetHashCode(), Is.EqualTo(hashCode)); Assert.AreEqual(hashCode, Line3D.Empty.GetHashCode());
} }
[Test] [TestMethod]
public void GetHashCode_ShouldBeCorrect_GivenUnitLine() public void GetHashCode_ShouldBeCorrect_GivenUnitLine()
{ {
// this test is pretty pointless, it exists only for code coverage purposes // this test is pretty pointless, it exists only for code coverage purposes
int hashCode = Line3D.One.GetHashCode(); int hashCode = Line3D.One.GetHashCode();
Assert.That(Line3D.One.GetHashCode(), Is.EqualTo(hashCode)); Assert.AreEqual(hashCode, Line3D.One.GetHashCode());
} }
[Test] [TestMethod]
public void op_Explicit_ShouldReturnEquivalentLine_GivenLine() public void op_Explicit_ShouldReturnEquivalentLine_GivenLine()
{ {
Line3D oneLine = new Line3D(Vector3.Zero, Vector3.UnitX + Vector3.UnitY); Line3D oneLine = new Line3D(Vector3.Zero, Vector3.UnitX + Vector3.UnitY);
@ -118,15 +119,12 @@ internal class Line3DTests
var expectedStart = new Point((int)oneLine.Start.X, (int)oneLine.Start.Y); var expectedStart = new Point((int)oneLine.Start.X, (int)oneLine.Start.Y);
var expectedEnd = new Point((int)oneLine.End.X, (int)oneLine.End.Y); var expectedEnd = new Point((int)oneLine.End.X, (int)oneLine.End.Y);
Assert.Multiple(() => Assert.AreEqual(oneLine.Length, converted.Length);
{ Assert.AreEqual(expectedStart, converted.Start);
Assert.That(converted.Length, Is.EqualTo(oneLine.Length)); Assert.AreEqual(expectedEnd, converted.End);
Assert.That(converted.Start, Is.EqualTo(expectedStart));
Assert.That(converted.End, Is.EqualTo(expectedEnd));
});
} }
[Test] [TestMethod]
public void op_Explicit_ShouldReturnEquivalentLineF_GivenLine() public void op_Explicit_ShouldReturnEquivalentLineF_GivenLine()
{ {
Line3D oneLine = new Line3D(Vector3.Zero, Vector3.UnitX + Vector3.UnitY); Line3D oneLine = new Line3D(Vector3.Zero, Vector3.UnitX + Vector3.UnitY);
@ -135,25 +133,21 @@ internal class Line3DTests
var expectedStart = new PointF(oneLine.Start.X, oneLine.Start.Y); var expectedStart = new PointF(oneLine.Start.X, oneLine.Start.Y);
var expectedEnd = new PointF(oneLine.End.X, oneLine.End.Y); var expectedEnd = new PointF(oneLine.End.X, oneLine.End.Y);
Assert.Multiple(() => Assert.AreEqual(oneLine.Length, converted.Length);
{ Assert.AreEqual(expectedStart, converted.Start);
Assert.That(converted.Length, Is.EqualTo(oneLine.Length)); Assert.AreEqual(expectedEnd, converted.End);
Assert.That(converted.Start, Is.EqualTo(expectedStart));
Assert.That(converted.End, Is.EqualTo(expectedEnd));
});
} }
[Test] [TestMethod]
public void op_GreaterThan_True_GivenUnitAndEmptyCircle() public void op_GreaterThan_True_GivenUnitAndEmptyCircle()
{ {
Assert.That(Line3D.One, Is.GreaterThan(Line3D.Empty)); Assert.IsTrue(Line3D.One > Line3D.Empty);
Assert.That(Line3D.One, Is.GreaterThanOrEqualTo(Line3D.Empty)); Assert.IsTrue(Line3D.One >= Line3D.Empty);
Assert.IsFalse(Line3D.One < Line3D.Empty);
Assert.That(Line3D.One > Line3D.Empty); Assert.IsFalse(Line3D.One <= Line3D.Empty);
Assert.That(Line3D.One >= Line3D.Empty);
} }
[Test] [TestMethod]
public void op_Implicit_ShouldReturnEquivalentLine_GivenLine() public void op_Implicit_ShouldReturnEquivalentLine_GivenLine()
{ {
Line oneLine = Line.One; Line oneLine = Line.One;
@ -162,16 +156,13 @@ internal class Line3DTests
var expectedStart = new Vector3(oneLine.Start.X, oneLine.Start.Y, 0.0f); var expectedStart = new Vector3(oneLine.Start.X, oneLine.Start.Y, 0.0f);
var expectedEnd = new Vector3(oneLine.End.X, oneLine.End.Y, 0.0f); var expectedEnd = new Vector3(oneLine.End.X, oneLine.End.Y, 0.0f);
Assert.Multiple(() => Assert.AreEqual(oneLine, converted);
{ Assert.AreEqual(oneLine.Length, converted.Length);
Assert.That(converted, Is.EqualTo((Line3D)oneLine)); Assert.AreEqual(expectedStart, converted.Start);
Assert.That(converted.Length, Is.EqualTo(oneLine.Length)); Assert.AreEqual(expectedEnd, converted.End);
Assert.That(converted.Start, Is.EqualTo(expectedStart));
Assert.That(converted.End, Is.EqualTo(expectedEnd));
});
} }
[Test] [TestMethod]
public void op_Implicit_ShouldReturnEquivalentLine_GivenLineF() public void op_Implicit_ShouldReturnEquivalentLine_GivenLineF()
{ {
LineF oneLine = LineF.One; LineF oneLine = LineF.One;
@ -180,22 +171,18 @@ internal class Line3DTests
var expectedStart = new Vector3(oneLine.Start.X, oneLine.Start.Y, 0.0f); var expectedStart = new Vector3(oneLine.Start.X, oneLine.Start.Y, 0.0f);
var expectedEnd = new Vector3(oneLine.End.X, oneLine.End.Y, 0.0f); var expectedEnd = new Vector3(oneLine.End.X, oneLine.End.Y, 0.0f);
Assert.Multiple(() => Assert.AreEqual(oneLine, converted);
{ Assert.AreEqual(oneLine.Length, converted.Length);
Assert.That(converted, Is.EqualTo((Line3D)oneLine)); Assert.AreEqual(expectedStart, converted.Start);
Assert.That(converted == oneLine); Assert.AreEqual(expectedEnd, converted.End);
Assert.That(converted.Length, Is.EqualTo(oneLine.Length));
Assert.That(converted.Start, Is.EqualTo(expectedStart));
Assert.That(converted.End, Is.EqualTo(expectedEnd));
});
} }
[Test] [TestMethod]
public void op_LessThan_True_GivenEmptyAndUnitCircle() public void op_LessThan_True_GivenEmptyAndUnitCircle()
{ {
Assert.That(Line3D.Empty, Is.LessThan(Line3D.One)); Assert.IsTrue(Line3D.Empty < Line3D.One);
Assert.That(Line3D.Empty, Is.LessThanOrEqualTo(Line3D.One)); Assert.IsTrue(Line3D.Empty <= Line3D.One);
Assert.That(Line3D.Empty < Line3D.One); Assert.IsFalse(Line3D.Empty > Line3D.One);
Assert.That(Line3D.Empty <= Line3D.One); Assert.IsFalse(Line3D.Empty >= Line3D.One);
} }
} }

View File

@ -1,163 +1,146 @@
using System.Drawing; using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;
using X10D.Drawing; using X10D.Drawing;
namespace X10D.Tests.Drawing; namespace X10D.Tests.Drawing;
[TestFixture] [TestClass]
internal class LineFTests public class LineFTests
{ {
[Test] [TestMethod]
public void CompareTo_ShouldBeNegativeOne_GivenEmptyAndOne() public void CompareTo_ShouldBeNegativeOne_GivenEmptyAndOne()
{ {
Assert.That(LineF.Empty.CompareTo(LineF.One), Is.EqualTo(-1)); Assert.AreEqual(-1, LineF.Empty.CompareTo(LineF.One));
} }
[Test] [TestMethod]
public void CompareTo_ShouldBeNegativeOne_GivenEmptyLineAndOneLineAsObject() public void CompareTo_ShouldBeNegativeOne_GivenEmptyLineAndOneLineAsObject()
{ {
Assert.That(LineF.Empty.CompareTo((object)LineF.One), Is.EqualTo(-1)); Assert.AreEqual(-1, LineF.Empty.CompareTo((object)LineF.One));
} }
[Test] [TestMethod]
public void CompareTo_ShouldBeOne_GivenNull() public void CompareTo_ShouldBeOne_GivenNull()
{ {
Assert.That(LineF.One.CompareTo(null), Is.EqualTo(1)); Assert.AreEqual(1, LineF.One.CompareTo(null));
} }
[Test] [TestMethod]
public void CompareTo_ShouldBeOne_GivenOneAndEmpty() public void CompareTo_ShouldBeOne_GivenOneAndEmpty()
{ {
Assert.That(LineF.One.CompareTo(LineF.Empty), Is.EqualTo(1)); Assert.AreEqual(1, LineF.One.CompareTo(LineF.Empty));
} }
[Test] [TestMethod]
public void CompareTo_ShouldBeZero_GivenUnitLine() public void CompareTo_ShouldBeZero_GivenUnitLine()
{ {
Assert.That(LineF.One.CompareTo(LineF.One), Is.Zero); var unitLineF = LineF.One;
Assert.AreEqual(0, unitLineF.CompareTo(unitLineF));
} }
[Test] [TestMethod]
public void CompareTo_ShouldThrowArgumentException_GivenInvalidType() public void CompareTo_ShouldThrowArgumentException_GivenInvalidType()
{ {
Assert.Throws<ArgumentException>(() => _ = LineF.Empty.CompareTo(new object())); Assert.ThrowsException<ArgumentException>(() => LineF.Empty.CompareTo(new object()));
} }
[Test] [TestMethod]
public void Length_ShouldBe0_GivenEmptyLine() public void Length_ShouldBe0_GivenEmptyLine()
{ {
Assert.That(LineF.Empty.Length, Is.Zero); Assert.AreEqual(0.0f, LineF.Empty.Length);
} }
[Test] [TestMethod]
public void Length_ShouldBe1_GivenUnitXLine() public void Length_ShouldBe1_GivenUnitXLine()
{ {
Assert.That(LineF.UnitX.Length, Is.EqualTo(1.0f).Within(1e-6f)); Assert.AreEqual(1.0f, LineF.UnitX.Length, 1e-6f);
} }
[Test] [TestMethod]
public void Length_ShouldBe1_GivenUnitYLine() public void Length_ShouldBe1_GivenUnitYLine()
{ {
Assert.That(LineF.UnitY.Length, Is.EqualTo(1.0f).Within(1e-6f)); Assert.AreEqual(1.0f, LineF.UnitY.Length, 1e-6f);
} }
[Test] [TestMethod]
public void Equals_ShouldBeTrue_GivenTwoUnitLines() public void Equals_ShouldBeTrue_GivenTwoUnitLines()
{ {
LineF first = LineF.One; LineF first = LineF.One;
LineF second = LineF.One; LineF second = LineF.One;
Assert.Multiple(() => Assert.AreEqual(first, second);
{ Assert.IsTrue(first == second);
Assert.That(second, Is.EqualTo(first)); Assert.IsFalse(first != second);
Assert.That(first, Is.EqualTo(second));
Assert.That(second == first);
Assert.That(first == second);
});
} }
[Test] [TestMethod]
public void Equals_ShouldBeFalse_GivenDifferentLines() public void Equals_ShouldBeFalse_GivenDifferentLines()
{ {
Assert.Multiple(() => Assert.AreNotEqual(LineF.One, LineF.Empty);
{ Assert.IsFalse(LineF.One == LineF.Empty);
Assert.That(LineF.Empty, Is.Not.EqualTo(LineF.One)); Assert.IsTrue(LineF.One != LineF.Empty);
Assert.That(LineF.One, Is.Not.EqualTo(LineF.Empty));
Assert.That(LineF.Empty != LineF.One);
Assert.That(LineF.One != LineF.Empty);
});
} }
[Test] [TestMethod]
public void Equals_ShouldBeFalse_GivenDifferentObjects() public void Equals_ShouldBeFalse_GivenDifferentObjects()
{ {
Assert.That(LineF.One, Is.Not.EqualTo(null)); Assert.IsFalse(LineF.One.Equals(null));
Assert.That(LineF.One.Equals(null), Is.False);
} }
[Test] [TestMethod]
public void GetHashCode_ShouldBeCorrect_GivenEmptyLine() public void GetHashCode_ShouldBeCorrect_GivenEmptyLine()
{ {
// this test is pretty pointless, it exists only for code coverage purposes // this test is pretty pointless, it exists only for code coverage purposes
int hashCode = LineF.Empty.GetHashCode(); int hashCode = LineF.Empty.GetHashCode();
Assert.That(LineF.Empty.GetHashCode(), Is.EqualTo(hashCode)); Assert.AreEqual(hashCode, LineF.Empty.GetHashCode());
} }
[Test] [TestMethod]
public void GetHashCode_ShouldBeCorrect_GivenUnitLine() public void GetHashCode_ShouldBeCorrect_GivenUnitLine()
{ {
// this test is pretty pointless, it exists only for code coverage purposes // this test is pretty pointless, it exists only for code coverage purposes
int hashCode = LineF.One.GetHashCode(); int hashCode = LineF.One.GetHashCode();
Assert.That(LineF.One.GetHashCode(), Is.EqualTo(hashCode)); Assert.AreEqual(hashCode, LineF.One.GetHashCode());
} }
[Test] [TestMethod]
public void op_Explicit_ShouldReturnEquivalentLine_GivenLine() public void op_Explicit_ShouldReturnEquivalentLine_GivenLine()
{ {
LineF oneLine = LineF.One; LineF oneLine = LineF.One;
Line converted = (Line)oneLine; Line converted = (Line)oneLine;
Assert.Multiple(() => Assert.AreEqual(oneLine, converted);
{ Assert.AreEqual(oneLine.Length, converted.Length);
Assert.That(converted, Is.EqualTo((Line)oneLine)); Assert.AreEqual(oneLine.Start, converted.Start);
Assert.That(converted == oneLine); Assert.AreEqual(oneLine.End, converted.End);
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));
});
} }
[Test] [TestMethod]
public void op_GreaterThan_True_GivenUnitAndEmptyCircle() public void op_GreaterThan_True_GivenUnitAndEmptyCircle()
{ {
Assert.That(LineF.One, Is.GreaterThan(LineF.Empty)); Assert.IsTrue(LineF.One > LineF.Empty);
Assert.That(LineF.One, Is.GreaterThanOrEqualTo(LineF.Empty)); Assert.IsTrue(LineF.One >= LineF.Empty);
Assert.That(LineF.One > LineF.Empty); Assert.IsFalse(LineF.One < LineF.Empty);
Assert.That(LineF.One >= LineF.Empty); Assert.IsFalse(LineF.One <= LineF.Empty);
} }
[Test] [TestMethod]
public void op_Implicit_ShouldReturnEquivalentLine_GivenLine() public void op_Implicit_ShouldReturnEquivalentLine_GivenLine()
{ {
Line oneLine = Line.One; Line oneLine = Line.One;
LineF converted = oneLine; LineF converted = oneLine;
Assert.Multiple(() => Assert.AreEqual(oneLine, converted);
{ Assert.AreEqual(oneLine.Length, converted.Length);
Assert.That(converted, Is.EqualTo((LineF)oneLine)); Assert.AreEqual(oneLine.Start, converted.Start);
Assert.That(converted == oneLine); Assert.AreEqual(oneLine.End, converted.End);
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));
});
} }
[Test] [TestMethod]
public void op_LessThan_True_GivenEmptyAndUnitCircle() public void op_LessThan_True_GivenEmptyAndUnitCircle()
{ {
Assert.That(LineF.Empty, Is.LessThan(LineF.One)); Assert.IsTrue(LineF.Empty < LineF.One);
Assert.That(LineF.Empty, Is.LessThanOrEqualTo(LineF.One)); Assert.IsTrue(LineF.Empty <= LineF.One);
Assert.That(LineF.Empty < LineF.One); Assert.IsFalse(LineF.Empty > LineF.One);
Assert.That(LineF.Empty <= LineF.One); Assert.IsFalse(LineF.Empty >= LineF.One);
} }
} }

View File

@ -1,131 +1,122 @@
using NUnit.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting;
using X10D.Drawing; using X10D.Drawing;
namespace X10D.Tests.Drawing; namespace X10D.Tests.Drawing;
[TestFixture] [TestClass]
internal class LineTests public class LineTests
{ {
[Test] [TestMethod]
public void CompareTo_ShouldBeNegativeOne_GivenEmptyAndOne() public void CompareTo_ShouldBeNegativeOne_GivenEmptyAndOne()
{ {
Assert.That(Line.Empty.CompareTo(Line.One), Is.EqualTo(-1)); Assert.AreEqual(-1, Line.Empty.CompareTo(Line.One));
} }
[Test] [TestMethod]
public void CompareTo_ShouldBeNegativeOne_GivenEmptyLineAndOneLineAsObject() public void CompareTo_ShouldBeNegativeOne_GivenEmptyLineAndOneLineAsObject()
{ {
Assert.That(Line.Empty.CompareTo((object)Line.One), Is.EqualTo(-1)); Assert.AreEqual(-1, Line.Empty.CompareTo((object)Line.One));
} }
[Test] [TestMethod]
public void CompareTo_ShouldBeOne_GivenNull() public void CompareTo_ShouldBeOne_GivenNull()
{ {
Assert.That(Line.One.CompareTo(null), Is.EqualTo(1)); Assert.AreEqual(1, Line.One.CompareTo(null));
} }
[Test] [TestMethod]
public void CompareTo_ShouldBeOne_GivenOneAndEmpty() public void CompareTo_ShouldBeOne_GivenOneAndEmpty()
{ {
Assert.That(Line.One.CompareTo(Line.Empty), Is.EqualTo(1)); Assert.AreEqual(1, Line.One.CompareTo(Line.Empty));
} }
[Test] [TestMethod]
public void CompareTo_ShouldBeZero_GivenUnitLine() public void CompareTo_ShouldBeZero_GivenUnitLine()
{ {
var unitLine = Line.One; var unitLine = Line.One;
Assert.That(unitLine.CompareTo(unitLine), Is.Zero); Assert.AreEqual(0, unitLine.CompareTo(unitLine));
} }
[Test] [TestMethod]
public void CompareTo_ShouldThrowArgumentException_GivenInvalidType() public void CompareTo_ShouldThrowArgumentException_GivenInvalidType()
{ {
Assert.Throws<ArgumentException>(() => _ = Line.Empty.CompareTo(new object())); Assert.ThrowsException<ArgumentException>(() => Line.Empty.CompareTo(new object()));
} }
[Test] [TestMethod]
public void Equals_ShouldBeTrue_GivenTwoUnitLines() public void Equals_ShouldBeTrue_GivenTwoUnitLines()
{ {
Line first = Line.One; Line first = Line.One;
Line second = Line.One; Line second = Line.One;
Assert.Multiple(() => Assert.AreEqual(first, second);
{ Assert.IsTrue(first == second);
Assert.That(second, Is.EqualTo(first)); Assert.IsFalse(first != second);
Assert.That(first, Is.EqualTo(second));
Assert.That(second == first);
Assert.That(first == second);
});
} }
[Test] [TestMethod]
public void Equals_ShouldBeFalse_GivenDifferentLines() public void Equals_ShouldBeFalse_GivenDifferentLines()
{ {
Assert.Multiple(() => Assert.AreNotEqual(Line.One, Line.Empty);
{ Assert.IsFalse(Line.One == Line.Empty);
Assert.That(Line.Empty, Is.Not.EqualTo(Line.One)); Assert.IsTrue(Line.One != Line.Empty);
Assert.That(Line.One, Is.Not.EqualTo(Line.Empty));
Assert.That(Line.Empty != Line.One);
Assert.That(Line.One != Line.Empty);
});
} }
[Test] [TestMethod]
public void Equals_ShouldBeFalse_GivenDifferentObjects() public void Equals_ShouldBeFalse_GivenDifferentObjects()
{ {
Assert.That(Line.One, Is.Not.EqualTo(null)); Assert.IsFalse(Line.One.Equals(null));
Assert.That(Line.One.Equals(null), Is.False);
} }
[Test] [TestMethod]
public void GetHashCode_ShouldBeCorrect_GivenEmptyLine() public void GetHashCode_ShouldBeCorrect_GivenEmptyLine()
{ {
// this test is pretty pointless, it exists only for code coverage purposes // this test is pretty pointless, it exists only for code coverage purposes
int hashCode = Line.Empty.GetHashCode(); int hashCode = Line.Empty.GetHashCode();
Assert.That(Line.Empty.GetHashCode(), Is.EqualTo(hashCode)); Assert.AreEqual(hashCode, Line.Empty.GetHashCode());
} }
[Test] [TestMethod]
public void GetHashCode_ShouldBeCorrect_GivenUnitLine() public void GetHashCode_ShouldBeCorrect_GivenUnitLine()
{ {
// this test is pretty pointless, it exists only for code coverage purposes // this test is pretty pointless, it exists only for code coverage purposes
int hashCode = Line.One.GetHashCode(); int hashCode = Line.One.GetHashCode();
Assert.That(Line.One.GetHashCode(), Is.EqualTo(hashCode)); Assert.AreEqual(hashCode, Line.One.GetHashCode());
} }
[Test] [TestMethod]
public void Length_ShouldBe0_GivenEmptyLine() public void Length_ShouldBe0_GivenEmptyLine()
{ {
Assert.That(Line.Empty.Length, Is.Zero); Assert.AreEqual(0.0f, Line.Empty.Length);
} }
[Test] [TestMethod]
public void Length_ShouldBe1_GivenUnitXLine() public void Length_ShouldBe1_GivenUnitXLine()
{ {
Assert.That(Line.UnitX.Length, Is.EqualTo(1.0f).Within(1e-6f)); Assert.AreEqual(1.0f, Line.UnitX.Length, 1e-6f);
} }
[Test] [TestMethod]
public void Length_ShouldBe1_GivenUnitYLine() public void Length_ShouldBe1_GivenUnitYLine()
{ {
Assert.That(Line.UnitY.Length, Is.EqualTo(1.0f).Within(1e-6f)); Assert.AreEqual(1.0f, Line.UnitY.Length, 1e-6f);
} }
[Test] [TestMethod]
public void op_GreaterThan_True_GivenUnitAndEmptyCircle() public void op_GreaterThan_True_GivenUnitAndEmptyCircle()
{ {
Assert.That(Line.One, Is.GreaterThan(Line.Empty)); Assert.IsTrue(Line.One > Line.Empty);
Assert.That(Line.One, Is.GreaterThanOrEqualTo(Line.Empty)); Assert.IsTrue(Line.One >= Line.Empty);
Assert.That(Line.One > Line.Empty); Assert.IsFalse(Line.One < Line.Empty);
Assert.That(Line.One >= Line.Empty); Assert.IsFalse(Line.One <= Line.Empty);
} }
[Test] [TestMethod]
public void op_LessThan_True_GivenEmptyAndUnitCircle() public void op_LessThan_True_GivenEmptyAndUnitCircle()
{ {
Assert.That(Line.Empty, Is.LessThan(Line.One)); Assert.IsTrue(Line.Empty < Line.One);
Assert.That(Line.Empty, Is.LessThanOrEqualTo(Line.One)); Assert.IsTrue(Line.Empty <= Line.One);
Assert.That(Line.Empty < Line.One); Assert.IsFalse(Line.Empty > Line.One);
Assert.That(Line.Empty <= Line.One); Assert.IsFalse(Line.Empty >= Line.One);
} }
} }

View File

@ -1,5 +1,5 @@
using System.Drawing; using System.Drawing;
using NUnit.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting;
#if !NET6_0_OR_GREATER #if !NET6_0_OR_GREATER
using X10D.Core; using X10D.Core;
#endif #endif
@ -7,74 +7,59 @@ using X10D.Drawing;
namespace X10D.Tests.Drawing; namespace X10D.Tests.Drawing;
[TestFixture] [TestClass]
internal class PointFTests public class PointFTests
{ {
[Test] [TestMethod]
public void IsOnLine_ShouldReturnTrue_GivenPointOnLine() public void IsOnLine_ShouldReturnTrue_GivenPointOnLine()
{ {
var point = new PointF(1.0f, 0.0f); var point = new PointF(1.0f, 0.0f);
var line = new LineF(PointF.Empty, new PointF(2.0f, 0.0f)); var line = new LineF(PointF.Empty, new PointF(2.0f, 0.0f));
Assert.Multiple(() => Assert.IsTrue(point.IsOnLine(line));
{ Assert.IsTrue(point.IsOnLine(line.Start, line.End));
Assert.That(point.IsOnLine(line)); Assert.IsTrue(point.IsOnLine(line.Start.ToVector2(), line.End.ToVector2()));
Assert.That(point.IsOnLine(line.Start, line.End));
Assert.That(point.IsOnLine(line.Start.ToVector2(), line.End.ToVector2()));
});
} }
[Test] [TestMethod]
public void IsOnLine_ShouldReturnFalse_GivenPointNotOnLine() public void IsOnLine_ShouldReturnFalse_GivenPointNotOnLine()
{ {
var point = new PointF(1.0f, 1.0f); var point = new PointF(1.0f, 1.0f);
var line = new LineF(PointF.Empty, new PointF(2.0f, 0.0f)); var line = new LineF(PointF.Empty, new PointF(2.0f, 0.0f));
Assert.Multiple(() => Assert.IsFalse(point.IsOnLine(line));
{ Assert.IsFalse(point.IsOnLine(line.Start, line.End));
Assert.That(point.IsOnLine(line), Is.False); Assert.IsFalse(point.IsOnLine(line.Start.ToVector2(), line.End.ToVector2()));
Assert.That(point.IsOnLine(line.Start, line.End), Is.False);
Assert.That(point.IsOnLine(line.Start.ToVector2(), line.End.ToVector2()), Is.False);
});
} }
[Test] [TestMethod]
public void Round_ShouldRoundToNearestInteger_GivenNoParameters() public void Round_ShouldRoundToNearestInteger_GivenNoParameters()
{ {
var point = new PointF(1.5f, 2.6f); var point = new PointF(1.5f, 2.6f);
var rounded = point.Round(); var rounded = point.Round();
Assert.Multiple(() => Assert.AreEqual(2, rounded.X);
{ Assert.AreEqual(3, rounded.Y);
Assert.That(rounded.X, Is.EqualTo(2));
Assert.That(rounded.Y, Is.EqualTo(3));
});
} }
[Test] [TestMethod]
public void Round_ShouldRoundToNearest10_GivenPrecision10() public void Round_ShouldRoundToNearest10_GivenPrecision10()
{ {
var point = new PointF(1.5f, 25.2f); var point = new PointF(1.5f, 25.2f);
var rounded = point.Round(10); var rounded = point.Round(10);
Assert.Multiple(() => Assert.AreEqual(0, rounded.X);
{ Assert.AreEqual(30, rounded.Y);
Assert.That(rounded.X, Is.Zero);
Assert.That(rounded.Y, Is.EqualTo(30));
});
} }
[Test] [TestMethod]
public void ToSizeF_ShouldReturnSize_WithEquivalentMembers() public void ToSizeF_ShouldReturnSize_WithEquivalentMembers()
{ {
var random = new Random(); var random = new Random();
var point = new PointF(random.NextSingle(), random.NextSingle()); var point = new PointF(random.NextSingle(), random.NextSingle());
var size = point.ToSizeF(); var size = point.ToSizeF();
Assert.Multiple(() => Assert.AreEqual(point.X, size.Width, 1e-6f);
{ Assert.AreEqual(point.Y, size.Height, 1e-6f);
Assert.That(size.Width, Is.EqualTo(point.X).Within(1e-6f));
Assert.That(size.Height, Is.EqualTo(point.Y).Within(1e-6f));
});
} }
} }

View File

@ -1,79 +1,64 @@
using System.Drawing; using System.Drawing;
using NUnit.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting;
using X10D.Drawing; using X10D.Drawing;
namespace X10D.Tests.Drawing; namespace X10D.Tests.Drawing;
[TestFixture] [TestClass]
internal class PointTests public class PointTests
{ {
[Test] [TestMethod]
public void IsOnLine_ShouldReturnTrue_GivenPointOnLine() public void IsOnLine_ShouldReturnTrue_GivenPointOnLine()
{ {
var point = new Point(1, 0); var point = new Point(1, 0);
var line = new Line(Point.Empty, new Point(2, 0)); var line = new Line(Point.Empty, new Point(2, 0));
Assert.Multiple(() => Assert.IsTrue(point.IsOnLine(line));
{ Assert.IsTrue(point.IsOnLine(line.Start, line.End));
Assert.That(point.IsOnLine(line)); Assert.IsTrue(point.IsOnLine(line.Start.ToVector2(), line.End.ToVector2()));
Assert.That(point.IsOnLine(line.Start, line.End));
Assert.That(point.IsOnLine(line.Start.ToVector2(), line.End.ToVector2()));
});
} }
[Test] [TestMethod]
public void IsOnLine_ShouldReturnFalse_GivenPointNotOnLine() public void IsOnLine_ShouldReturnFalse_GivenPointNotOnLine()
{ {
var point = new Point(1, 1); var point = new Point(1, 1);
var line = new Line(Point.Empty, new Point(2, 0)); var line = new Line(Point.Empty, new Point(2, 0));
Assert.Multiple(() => Assert.IsFalse(point.IsOnLine(line));
{ Assert.IsFalse(point.IsOnLine(line.Start, line.End));
Assert.That(point.IsOnLine(line), Is.False); Assert.IsFalse(point.IsOnLine(line.Start.ToVector2(), line.End.ToVector2()));
Assert.That(point.IsOnLine(line.Start, line.End), Is.False);
Assert.That(point.IsOnLine(line.Start.ToVector2(), line.End.ToVector2()), Is.False);
});
} }
[Test] [TestMethod]
public void ToSize_ShouldReturnSize_WithEquivalentMembers() public void ToSize_ShouldReturnSize_WithEquivalentMembers()
{ {
var random = new Random(); var random = new Random();
var point = new Point(random.Next(), random.Next()); var point = new Point(random.Next(), random.Next());
var size = point.ToSize(); var size = point.ToSize();
Assert.Multiple(() => Assert.AreEqual(point.X, size.Width);
{ Assert.AreEqual(point.Y, size.Height);
Assert.That(size.Width, Is.EqualTo(point.X));
Assert.That(size.Height, Is.EqualTo(point.Y));
});
} }
[Test] [TestMethod]
public void ToSizeF_ShouldReturnSize_WithEquivalentMembers() public void ToSizeF_ShouldReturnSize_WithEquivalentMembers()
{ {
var random = new Random(); var random = new Random();
var point = new Point(random.Next(), random.Next()); var point = new Point(random.Next(), random.Next());
var size = point.ToSizeF(); var size = point.ToSizeF();
Assert.Multiple(() => Assert.AreEqual(point.X, size.Width, 1e-6f);
{ Assert.AreEqual(point.Y, size.Height, 1e-6f);
Assert.That(size.Width, Is.EqualTo(point.X).Within(1e-6f));
Assert.That(size.Height, Is.EqualTo(point.Y).Within(1e-6f));
});
} }
[Test] [TestMethod]
public void ToVector2_ShouldReturnVector_WithEquivalentMembers() public void ToVector2_ShouldReturnVector_WithEquivalentMembers()
{ {
var random = new Random(); var random = new Random();
var point = new Point(random.Next(), random.Next()); var point = new Point(random.Next(), random.Next());
var size = point.ToVector2(); var size = point.ToVector2();
Assert.Multiple(() => Assert.AreEqual(point.X, size.X, 1e-6f);
{ Assert.AreEqual(point.Y, size.Y, 1e-6f);
Assert.That(size.X, Is.EqualTo(point.X).Within(1e-6f));
Assert.That(size.Y, Is.EqualTo(point.Y).Within(1e-6f));
});
} }
} }

View File

@ -1,230 +1,228 @@
using System.Drawing; using System.Drawing;
using System.Numerics; using System.Numerics;
using NUnit.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting;
using X10D.Drawing; using X10D.Drawing;
namespace X10D.Tests.Drawing; namespace X10D.Tests.Drawing;
[TestFixture] [TestClass]
internal class PolygonFTests public class PolygonFTests
{ {
[Test] [TestMethod]
public void AddVertices_ShouldAddVertices() public void AddVertices_ShouldAddVertices()
{ {
var polygon = PolygonF.Empty; var polygon = PolygonF.Empty;
polygon.AddVertices(new[] {new PointF(1, 2), new PointF(3, 4)}); polygon.AddVertices(new[] {new PointF(1, 2), new PointF(3, 4)});
Assert.That(polygon.VertexCount, Is.EqualTo(2)); Assert.AreEqual(2, polygon.VertexCount);
// assert that the empty polygon was not modified // assert that the empty polygon was not modified
Assert.That(PolygonF.Empty.VertexCount, Is.Zero); Assert.AreEqual(0, PolygonF.Empty.VertexCount);
} }
[Test] [TestMethod]
public void AddVertices_ShouldThrowArgumentNullException_GivenNullEnumerableOfPointF() public void AddVertices_ShouldThrowArgumentNullException_GivenNullEnumerableOfPointF()
{ {
var polygon = PolygonF.Empty; var polygon = PolygonF.Empty;
IEnumerable<PointF> vertices = null!; IEnumerable<PointF> vertices = null!;
Assert.Throws<ArgumentNullException>(() => polygon.AddVertices(vertices)); Assert.ThrowsException<ArgumentNullException>(() => polygon.AddVertices(vertices));
} }
[Test] [TestMethod]
public void AddVertices_ShouldThrowArgumentNullException_GivenNullEnumerableOfVector2() public void AddVertices_ShouldThrowArgumentNullException_GivenNullEnumerableOfVector2()
{ {
var polygon = PolygonF.Empty; var polygon = PolygonF.Empty;
IEnumerable<Vector2> vertices = null!; IEnumerable<Vector2> vertices = null!;
Assert.Throws<ArgumentNullException>(() => polygon.AddVertices(vertices)); Assert.ThrowsException<ArgumentNullException>(() => polygon.AddVertices(vertices));
} }
[Test] [TestMethod]
public void ClearVertices_ShouldClearVertices() public void ClearVertices_ShouldClearVertices()
{ {
var polygon = PolygonF.Empty; var polygon = PolygonF.Empty;
polygon.AddVertices(new[] {new Vector2(1, 2), new Vector2(3, 4)}); polygon.AddVertices(new[] {new Vector2(1, 2), new Vector2(3, 4)});
Assert.That(polygon.VertexCount, Is.EqualTo(2)); Assert.AreEqual(2, polygon.VertexCount);
// assert that the empty polygon was not modified // assert that the empty polygon was not modified
Assert.That(PolygonF.Empty.VertexCount, Is.Zero); Assert.AreEqual(0, PolygonF.Empty.VertexCount);
polygon.ClearVertices(); polygon.ClearVertices();
Assert.That(polygon.VertexCount, Is.Zero); Assert.AreEqual(0, polygon.VertexCount);
} }
[Test] [TestMethod]
public void Constructor_ShouldPopulateVertices_GivenPolygon() public void Constructor_ShouldPopulateVertices_GivenPolygon()
{ {
var pointPolygon = new PolygonF(new[] {new PointF(1, 2), new PointF(3, 4)}); 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)}); var vectorPolygon = new PolygonF(new[] {new Vector2(1, 2), new Vector2(3, 4)});
Assert.That(pointPolygon.VertexCount, Is.EqualTo(2)); Assert.AreEqual(2, pointPolygon.VertexCount);
Assert.That(vectorPolygon.VertexCount, Is.EqualTo(2)); Assert.AreEqual(2, vectorPolygon.VertexCount);
} }
[Test] [TestMethod]
public void Constructor_ShouldThrowArgumentNullException_GivenNullEnumerableOfPointF() public void Constructor_ShouldThrowArgumentNullException_GivenNullEnumerableOfPointF()
{ {
IEnumerable<PointF> vertices = null!; IEnumerable<PointF> vertices = null!;
Assert.Throws<ArgumentNullException>(() => _ = new PolygonF(vertices)); Assert.ThrowsException<ArgumentNullException>(() => new PolygonF(vertices));
} }
[Test] [TestMethod]
public void Constructor_ShouldThrowArgumentNullException_GivenNullEnumerableOfVector2() public void Constructor_ShouldThrowArgumentNullException_GivenNullEnumerableOfVector2()
{ {
IEnumerable<Vector2> vertices = null!; IEnumerable<Vector2> vertices = null!;
Assert.Throws<ArgumentNullException>(() => _ = new PolygonF(vertices)); Assert.ThrowsException<ArgumentNullException>(() => new PolygonF(vertices));
} }
[Test] [TestMethod]
public void CopyConstructor_ShouldCopyVertices_GivenPolygon() public void CopyConstructor_ShouldCopyVertices_GivenPolygon()
{ {
var first = PolygonF.Empty; var first = PolygonF.Empty;
first.AddVertices(new[] {new PointF(1, 2), new PointF(3, 4)}); first.AddVertices(new[] {new PointF(1, 2), new PointF(3, 4)});
var second = new PolygonF(first); var second = new PolygonF(first);
Assert.That(first.VertexCount, Is.EqualTo(2)); Assert.AreEqual(2, first.VertexCount);
Assert.That(second.VertexCount, Is.EqualTo(2)); Assert.AreEqual(2, second.VertexCount);
// we cannot use CollectionAssert here for reasons I am not entirely sure of. // we cannot use CollectionAssert here for reasons I am not entirely sure of.
// it seems to dislike casting from IReadOnlyList<Point> to ICollection. but okay. // it seems to dislike casting from IReadOnlyList<Point> to ICollection. but okay.
CollectionAssert.AreEqual(first.Vertices, second.Vertices); Assert.IsTrue(first.Vertices.SequenceEqual(second.Vertices));
// assert that the empty polygon was not modified // assert that the empty polygon was not modified
Assert.That(PolygonF.Empty.VertexCount, Is.Zero); Assert.AreEqual(0, PolygonF.Empty.VertexCount);
} }
[Test] [TestMethod]
public void CopyConstructor_ShouldThrowArgumentNullException_GivenNullPolygonF() public void CopyConstructor_ShouldThrowArgumentNullException_GivenNullPolygonF()
{ {
PolygonF polygon = null!; PolygonF polygon = null!;
Assert.Throws<ArgumentNullException>(() => _ = new PolygonF(polygon)); Assert.ThrowsException<ArgumentNullException>(() => new PolygonF(polygon));
} }
[Test] [TestMethod]
public void Equals_ShouldBeTrue_GivenTwoEmptyPolygons() public void Equals_ShouldBeTrue_GivenTwoEmptyPolygons()
{ {
var first = PolygonF.Empty; var first = PolygonF.Empty;
var second = PolygonF.Empty; var second = PolygonF.Empty;
Assert.Multiple(() => Assert.AreEqual(first, second);
{ Assert.AreEqual(second, first);
Assert.That(second, Is.EqualTo(first)); Assert.IsTrue(first.Equals(second));
Assert.That(first, Is.EqualTo(second)); Assert.IsTrue(second.Equals(first));
Assert.That(second == first); Assert.IsTrue(first == second);
Assert.That(first == second); Assert.IsTrue(second == first);
}); Assert.IsFalse(first != second);
Assert.IsFalse(second != first);
} }
[Test] [TestMethod]
public void Equals_ShouldBeTrue_GivenTwoHexagons() public void Equals_ShouldBeTrue_GivenTwoHexagons()
{ {
PolygonF first = CreateHexagon(); PolygonF first = CreateHexagon();
PolygonF second = CreateHexagon(); PolygonF second = CreateHexagon();
Assert.Multiple(() => Assert.AreEqual(first, second);
{ Assert.AreEqual(second, first);
Assert.That(second, Is.EqualTo(first)); Assert.IsTrue(first.Equals(second));
Assert.That(first, Is.EqualTo(second)); Assert.IsTrue(second.Equals(first));
Assert.That(second == first); Assert.IsTrue(first == second);
Assert.That(first == second); Assert.IsTrue(second == first);
}); Assert.IsFalse(first != second);
Assert.IsFalse(second != first);
} }
[Test] [TestMethod]
public void Equals_ShouldBeFalse_GivenHexagonAndEmptyPolygon() public void Equals_ShouldBeFalse_GivenHexagonAndEmptyPolygon()
{ {
PolygonF first = CreateHexagon(); PolygonF first = CreateHexagon();
PolygonF second = PolygonF.Empty; PolygonF second = PolygonF.Empty;
Assert.Multiple(() => Assert.AreNotEqual(first, second);
{ Assert.AreNotEqual(second, first);
Assert.That(second, Is.Not.EqualTo(first)); Assert.IsFalse(first.Equals(second));
Assert.That(first, Is.Not.EqualTo(second)); Assert.IsFalse(second.Equals(first));
Assert.That(second != first); Assert.IsFalse(first == second);
Assert.That(first != second); Assert.IsFalse(second == first);
}); Assert.IsTrue(first != second);
Assert.IsTrue(second != first);
} }
[Test] [TestMethod]
public void FromPolygon_ShouldThrowArgumentNullException_GivenNullPolygonF() public void FromPolygon_ShouldThrowArgumentNullException_GivenNullPolygonF()
{ {
Assert.Throws<ArgumentNullException>(() => PolygonF.FromPolygon(null!)); Assert.ThrowsException<ArgumentNullException>(() => PolygonF.FromPolygon(null!));
} }
[Test] [TestMethod]
public void IsConvex_ShouldBeFalse_GivenEmptyPolygon() public void IsConvex_ShouldBeFalse_GivenEmptyPolygon()
{ {
Assert.That(PolygonF.Empty.IsConvex, Is.False); Assert.IsFalse(PolygonF.Empty.IsConvex);
} }
[Test] [TestMethod]
public void IsConvex_ShouldBeTrue_GivenHexagon() public void IsConvex_ShouldBeTrue_GivenHexagon()
{ {
Assert.That(CreateHexagon().IsConvex, Is.True); Assert.IsTrue(CreateHexagon().IsConvex);
} }
[Test] [TestMethod]
public void IsConvex_ShouldBeFalse_GivenConcavePolygon() public void IsConvex_ShouldBeFalse_GivenConcavePolygon()
{ {
Assert.That(CreateConcavePolygon().IsConvex, Is.False); Assert.IsFalse(CreateConcavePolygon().IsConvex);
} }
[Test] [TestMethod]
public void op_Explicit_ShouldReturnEquivalentCircle_GivenCircle() public void op_Explicit_ShouldReturnEquivalentCircle_GivenCircle()
{ {
PolygonF polygon = CreateHexagon(); PolygonF polygon = CreateHexagon();
Polygon converted = (Polygon)polygon; Polygon converted = (Polygon)polygon;
Assert.Multiple(() => Assert.AreEqual(polygon, converted);
{ Assert.AreEqual(polygon.IsConvex, converted.IsConvex);
Assert.That(converted, Is.EqualTo((Polygon)polygon)); Assert.AreEqual(polygon.VertexCount, converted.VertexCount);
Assert.That(converted.IsConvex, Is.EqualTo(polygon.IsConvex));
Assert.That(converted.VertexCount, Is.EqualTo(polygon.VertexCount)); Assert.IsTrue(polygon.Vertices.SequenceEqual(converted.Vertices.Select(p => (PointF)p)));
CollectionAssert.AreEqual(polygon.Vertices, converted.Vertices.Select(p => (PointF)p));
});
} }
[Test] [TestMethod]
public void op_Implicit_ShouldReturnEquivalentCircle_GivenCircle() public void op_Implicit_ShouldReturnEquivalentCircle_GivenCircle()
{ {
Polygon polygon = PolygonTests.CreateHexagon(); Polygon polygon = PolygonTests.CreateHexagon();
PolygonF converted = polygon; PolygonF converted = polygon;
Assert.Multiple(() => Assert.AreEqual(polygon, converted);
{ Assert.AreEqual(polygon.IsConvex, converted.IsConvex);
Assert.That(converted, Is.EqualTo((PolygonF)polygon)); Assert.AreEqual(polygon.VertexCount, converted.VertexCount);
Assert.That(converted == polygon);
Assert.That(converted.IsConvex, Is.EqualTo(polygon.IsConvex)); Assert.IsTrue(converted.Vertices.SequenceEqual(polygon.Vertices.Select(p => (PointF)p)));
Assert.That(converted.VertexCount, Is.EqualTo(polygon.VertexCount));
CollectionAssert.AreEqual(converted.Vertices, polygon.Vertices.Select(p => (PointF)p));
});
} }
[Test] [TestMethod]
public void PointCount_ShouldBe1_GivenPolygonFWith1Point() public void PointCount_ShouldBe1_GivenPolygonFWith1Point()
{ {
var polygon = new PolygonF(); var polygon = new PolygonF();
polygon.AddVertex(new Point(1, 1)); polygon.AddVertex(new Point(1, 1));
Assert.That(polygon.VertexCount, Is.EqualTo(1)); Assert.AreEqual(1, polygon.VertexCount);
// assert that the empty polygon was not modified // assert that the empty polygon was not modified
Assert.That(PolygonF.Empty.VertexCount, Is.Zero); Assert.AreEqual(0, PolygonF.Empty.VertexCount);
} }
[Test] [TestMethod]
public void PointCount_ShouldBe0_GivenEmptyPolygon() public void PointCount_ShouldBe0_GivenEmptyPolygon()
{ {
Assert.That(PolygonF.Empty.VertexCount, Is.Zero); Assert.AreEqual(0, PolygonF.Empty.VertexCount);
} }
[Test] [TestMethod]
public void GetHashCode_ShouldBeCorrect_GivenEmptyCircle() public void GetHashCode_ShouldBeCorrect_GivenEmptyCircle()
{ {
// this test is pretty pointless, it exists only for code coverage purposes // this test is pretty pointless, it exists only for code coverage purposes
int hashCode = PolygonF.Empty.GetHashCode(); int hashCode = PolygonF.Empty.GetHashCode();
Assert.That(PolygonF.Empty.GetHashCode(), Is.EqualTo(hashCode)); Assert.AreEqual(hashCode, PolygonF.Empty.GetHashCode());
} }
private static PolygonF CreateHexagon() internal static PolygonF CreateHexagon()
{ {
var hexagon = new PolygonF(); var hexagon = new PolygonF();
hexagon.AddVertex(new Vector2(0, 0)); hexagon.AddVertex(new Vector2(0, 0));
@ -236,7 +234,7 @@ internal class PolygonFTests
return hexagon; return hexagon;
} }
private static PolygonF CreateConcavePolygon() internal static PolygonF CreateConcavePolygon()
{ {
var hexagon = new PolygonF(); var hexagon = new PolygonF();
hexagon.AddVertex(new Vector2(0, 0)); hexagon.AddVertex(new Vector2(0, 0));

View File

@ -1,131 +1,136 @@
using System.Drawing; using System.Drawing;
using NUnit.Framework; using System.Numerics;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using X10D.Drawing; using X10D.Drawing;
namespace X10D.Tests.Drawing; namespace X10D.Tests.Drawing;
[TestFixture] [TestClass]
internal class PolygonTests public class PolygonTests
{ {
[Test] [TestMethod]
public void AddVertices_ShouldAddVertices() public void AddVertices_ShouldAddVertices()
{ {
var polygon = Polygon.Empty; var polygon = Polygon.Empty;
polygon.AddVertices(new[] {new Point(1, 2), new Point(3, 4)}); polygon.AddVertices(new[] {new Point(1, 2), new Point(3, 4)});
Assert.That(polygon.VertexCount, Is.EqualTo(2)); Assert.AreEqual(2, polygon.VertexCount);
// assert that the empty polygon was not modified // assert that the empty polygon was not modified
Assert.That(Polygon.Empty.VertexCount, Is.Zero); Assert.AreEqual(0, Polygon.Empty.VertexCount);
} }
[Test] [TestMethod]
public void AddVertices_ShouldThrowArgumentNullException_GivenNullEnumerable() public void AddVertices_ShouldThrowArgumentNullException_GivenNullEnumerable()
{ {
var polygon = Polygon.Empty; var polygon = Polygon.Empty;
IEnumerable<Point> vertices = null!; IEnumerable<Point> vertices = null!;
Assert.Throws<ArgumentNullException>(() => polygon.AddVertices(vertices)); Assert.ThrowsException<ArgumentNullException>(() => polygon.AddVertices(vertices));
} }
[Test] [TestMethod]
public void ClearVertices_ShouldClearVertices() public void ClearVertices_ShouldClearVertices()
{ {
var polygon = Polygon.Empty; var polygon = Polygon.Empty;
polygon.AddVertices(new[] {new Point(1, 2), new Point(3, 4)}); polygon.AddVertices(new[] {new Point(1, 2), new Point(3, 4)});
Assert.That(polygon.VertexCount, Is.EqualTo(2)); Assert.AreEqual(2, polygon.VertexCount);
// assert that the empty polygon was not modified // assert that the empty polygon was not modified
Assert.That(Polygon.Empty.VertexCount, Is.Zero); Assert.AreEqual(0, Polygon.Empty.VertexCount);
polygon.ClearVertices(); polygon.ClearVertices();
Assert.That(polygon.VertexCount, Is.Zero); Assert.AreEqual(0, polygon.VertexCount);
} }
[Test] [TestMethod]
public void Constructor_ShouldPopulateVertices_GivenPolygon() public void Constructor_ShouldPopulateVertices_GivenPolygon()
{ {
var pointPolygon = new Polygon(new[] {new Point(1, 2), new Point(3, 4)}); var pointPolygon = new Polygon(new[] {new Point(1, 2), new Point(3, 4)});
Assert.That(pointPolygon.VertexCount, Is.EqualTo(2)); Assert.AreEqual(2, pointPolygon.VertexCount);
} }
[Test] [TestMethod]
public void Constructor_ShouldThrowArgumentNullException_GivenNullEnumerableOfPoint() public void Constructor_ShouldThrowArgumentNullException_GivenNullEnumerableOfPoint()
{ {
IEnumerable<Point> vertices = null!; IEnumerable<Point> vertices = null!;
Assert.Throws<ArgumentNullException>(() => _ = new Polygon(vertices)); Assert.ThrowsException<ArgumentNullException>(() => new Polygon(vertices));
} }
[Test] [TestMethod]
public void CopyConstructor_ShouldCopyVertices_GivenPolygon() public void CopyConstructor_ShouldCopyVertices_GivenPolygon()
{ {
var first = Polygon.Empty; var first = Polygon.Empty;
first.AddVertices(new[] {new Point(1, 2), new Point(3, 4)}); first.AddVertices(new[] {new Point(1, 2), new Point(3, 4)});
var second = new Polygon(first); var second = new Polygon(first);
Assert.That(first.VertexCount, Is.EqualTo(2)); Assert.AreEqual(2, first.VertexCount);
Assert.That(second.VertexCount, Is.EqualTo(2)); Assert.AreEqual(2, second.VertexCount);
// we cannot use CollectionAssert here for reasons I am not entirely sure of. // we cannot use CollectionAssert here for reasons I am not entirely sure of.
// it seems to dislike casting from IReadOnlyList<Point> to ICollection. but okay. // it seems to dislike casting from IReadOnlyList<Point> to ICollection. but okay.
Assert.That(first.Vertices.SequenceEqual(second.Vertices)); Assert.IsTrue(first.Vertices.SequenceEqual(second.Vertices));
// assert that the empty polygon was not modified // assert that the empty polygon was not modified
Assert.That(Polygon.Empty.VertexCount, Is.Zero); Assert.AreEqual(0, Polygon.Empty.VertexCount);
} }
[Test] [TestMethod]
public void CopyConstructor_ShouldThrowArgumentNullException_GivenNullPolygon() public void CopyConstructor_ShouldThrowArgumentNullException_GivenNullPolygon()
{ {
Polygon polygon = null!; Polygon polygon = null!;
Assert.Throws<ArgumentNullException>(() => _ = new Polygon(polygon)); Assert.ThrowsException<ArgumentNullException>(() => new Polygon(polygon));
} }
[Test] [TestMethod]
public void Equals_ShouldBeTrue_GivenTwoEmptyPolygons() public void Equals_ShouldBeTrue_GivenTwoEmptyPolygons()
{ {
var first = Polygon.Empty; var first = Polygon.Empty;
var second = Polygon.Empty; var second = Polygon.Empty;
Assert.Multiple(() => Assert.AreEqual(first, second);
{ Assert.AreEqual(second, first);
Assert.That(second, Is.EqualTo(first)); Assert.IsTrue(first.Equals(second));
Assert.That(first, Is.EqualTo(second)); Assert.IsTrue(second.Equals(first));
Assert.That(second == first); Assert.IsTrue(first == second);
Assert.That(first == second); Assert.IsTrue(second == first);
}); Assert.IsFalse(first != second);
Assert.IsFalse(second != first);
} }
[Test] [TestMethod]
public void Equals_ShouldBeTrue_GivenTwoHexagons() public void Equals_ShouldBeTrue_GivenTwoHexagons()
{ {
Polygon first = CreateHexagon(); Polygon first = CreateHexagon();
Polygon second = CreateHexagon(); Polygon second = CreateHexagon();
Assert.Multiple(() => Assert.AreEqual(first, second);
{ Assert.AreEqual(second, first);
Assert.That(second, Is.EqualTo(first)); Assert.IsTrue(first.Equals(second));
Assert.That(first, Is.EqualTo(second)); Assert.IsTrue(second.Equals(first));
Assert.That(second == first); Assert.IsTrue(first == second);
Assert.That(first == second); Assert.IsTrue(second == first);
}); Assert.IsFalse(first != second);
Assert.IsFalse(second != first);
} }
[Test] [TestMethod]
public void Equals_ShouldBeFalse_GivenHexagonAndEmptyPolygon() public void Equals_ShouldBeFalse_GivenHexagonAndEmptyPolygon()
{ {
Polygon first = CreateHexagon(); Polygon first = CreateHexagon();
Polygon second = Polygon.Empty; Polygon second = Polygon.Empty;
Assert.Multiple(() => Assert.AreNotEqual(first, second);
{ Assert.AreNotEqual(second, first);
Assert.That(second, Is.Not.EqualTo(first)); Assert.IsFalse(first.Equals(second));
Assert.That(first, Is.Not.EqualTo(second)); Assert.IsFalse(second.Equals(first));
Assert.That(second != first); Assert.IsFalse(first == second);
Assert.That(first != second); Assert.IsFalse(second == first);
}); Assert.IsTrue(first != second);
Assert.IsTrue(second != first);
} }
[Test] [TestMethod]
public void FromPolygonF_ShouldReturnEquivalentPolygon_GivenPolygon() public void FromPolygonF_ShouldReturnEquivalentPolygon_GivenPolygon()
{ {
PolygonF hexagon = CreateHexagonF(); PolygonF hexagon = CreateHexagonF();
@ -133,57 +138,57 @@ internal class PolygonTests
Polygon expected = CreateHexagon(); Polygon expected = CreateHexagon();
Polygon actual = Polygon.FromPolygonF(hexagon); Polygon actual = Polygon.FromPolygonF(hexagon);
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
[Test] [TestMethod]
public void FromPolygonF_ShouldThrowArgumentNullException_GivenNullPolygon() public void FromPolygonF_ShouldThrowArgumentNullException_GivenNullPolygon()
{ {
Assert.Throws<ArgumentNullException>(() => Polygon.FromPolygonF(null!)); Assert.ThrowsException<ArgumentNullException>(() => Polygon.FromPolygonF(null!));
} }
[Test] [TestMethod]
public void IsConvex_ShouldBeFalse_GivenEmptyPolygon() public void IsConvex_ShouldBeFalse_GivenEmptyPolygon()
{ {
Assert.That(Polygon.Empty.IsConvex, Is.False); Assert.IsFalse(Polygon.Empty.IsConvex);
} }
[Test] [TestMethod]
public void IsConvex_ShouldBeTrue_GivenHexagon() public void IsConvex_ShouldBeTrue_GivenHexagon()
{ {
Assert.That(CreateHexagon().IsConvex); Assert.IsTrue(CreateHexagon().IsConvex);
} }
[Test] [TestMethod]
public void IsConvex_ShouldBeFalse_GivenConcavePolygon() public void IsConvex_ShouldBeFalse_GivenConcavePolygon()
{ {
Assert.That(CreateConcavePolygon().IsConvex, Is.False); Assert.IsFalse(CreateConcavePolygon().IsConvex);
} }
[Test] [TestMethod]
public void PointCount_ShouldBe1_GivenPolygonWith1Point() public void PointCount_ShouldBe1_GivenPolygonWith1Point()
{ {
var polygon = Polygon.Empty; var polygon = Polygon.Empty;
polygon.AddVertex(new Point(1, 1)); polygon.AddVertex(new Point(1, 1));
Assert.That(polygon.VertexCount, Is.EqualTo(1)); Assert.AreEqual(1, polygon.VertexCount);
// assert that the empty polygon was not modified // assert that the empty polygon was not modified
Assert.That(Polygon.Empty.VertexCount, Is.Zero); Assert.AreEqual(0, Polygon.Empty.VertexCount);
} }
[Test] [TestMethod]
public void PointCount_ShouldBe0_GivenEmptyPolygon() public void PointCount_ShouldBe0_GivenEmptyPolygon()
{ {
Assert.That(Polygon.Empty.VertexCount, Is.Zero); Assert.AreEqual(0, Polygon.Empty.VertexCount);
} }
[Test] [TestMethod]
public void GetHashCode_ShouldBeCorrect_GivenEmptyCircle() public void GetHashCode_ShouldBeCorrect_GivenEmptyCircle()
{ {
// this test is pretty pointless, it exists only for code coverage purposes // this test is pretty pointless, it exists only for code coverage purposes
int hashCode = Polygon.Empty.GetHashCode(); int hashCode = Polygon.Empty.GetHashCode();
Assert.That(Polygon.Empty.GetHashCode(), Is.EqualTo(hashCode)); Assert.AreEqual(hashCode, Polygon.Empty.GetHashCode());
} }
internal static Polygon CreateHexagon() internal static Polygon CreateHexagon()

View File

@ -1,221 +1,196 @@
using System.Numerics; using System.Numerics;
using NUnit.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting;
using X10D.Drawing; using X10D.Drawing;
namespace X10D.Tests.Drawing; namespace X10D.Tests.Drawing;
[TestFixture] [TestClass]
internal class PolyhedronTests public class PolyhedronTests
{ {
[Test] [TestMethod]
public void AddVertices_ShouldAddVertices() public void AddVertices_ShouldAddVertices()
{ {
var polyhedron = Polyhedron.Empty; var polyhedron = Polyhedron.Empty;
polyhedron.AddVertices(new[] {new Vector3(1, 2, 3), new Vector3(4, 5, 6)}); 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 that the empty polyhedron was not modified
Assert.That(Polyhedron.Empty.VertexCount, Is.Zero); Assert.AreEqual(0, Polyhedron.Empty.VertexCount);
});
} }
[Test] [TestMethod]
public void AddVertices_ShouldThrowArgumentNullException_GivenNullEnumerableOfVector3() public void AddVertices_ShouldThrowArgumentNullException_GivenNullEnumerableOfVector3()
{ {
var polygon = Polyhedron.Empty; var polygon = Polyhedron.Empty;
IEnumerable<Vector3> vertices = null!; IEnumerable<Vector3> vertices = null!;
Assert.Throws<ArgumentNullException>(() => polygon.AddVertices(vertices)); Assert.ThrowsException<ArgumentNullException>(() => polygon.AddVertices(vertices));
} }
[Test] [TestMethod]
public void ClearVertices_ShouldClearVertices() public void ClearVertices_ShouldClearVertices()
{ {
var polyhedron = Polyhedron.Empty; var polyhedron = Polyhedron.Empty;
polyhedron.AddVertices(new[] {new Vector3(1, 2, 3), new Vector3(4, 5, 6)}); polyhedron.AddVertices(new[] {new Vector3(1, 2, 3), new Vector3(4, 5, 6)});
Assert.Multiple(() => Assert.AreEqual(2, polyhedron.VertexCount);
{
Assert.That(polyhedron.VertexCount, Is.EqualTo(2));
// assert that the empty polyhedron was not modified // assert that the empty polyhedron was not modified
Assert.That(Polyhedron.Empty.VertexCount, Is.Zero); Assert.AreEqual(0, Polyhedron.Empty.VertexCount);
});
polyhedron.ClearVertices(); polyhedron.ClearVertices();
Assert.That(polyhedron.VertexCount, Is.Zero); Assert.AreEqual(0, polyhedron.VertexCount);
} }
[Test] [TestMethod]
public void Constructor_ShouldPopulateVertices_GivenPolyhedron() public void Constructor_ShouldPopulateVertices_GivenPolyhedron()
{ {
var polyhedron = new Polyhedron(new[] {new Vector3(1, 2, 3), new Vector3(4, 5, 6)}); var polyhedron = new Polyhedron(new[] {new Vector3(1, 2, 3), new Vector3(4, 5, 6)});
Assert.That(polyhedron.VertexCount, Is.EqualTo(2)); Assert.AreEqual(2, polyhedron.VertexCount);
} }
[Test] [TestMethod]
public void Constructor_ShouldThrowArgumentNullException_GivenNullEnumerableOfVector3() public void Constructor_ShouldThrowArgumentNullException_GivenNullEnumerableOfVector3()
{ {
IEnumerable<Vector3> vertices = null!; IEnumerable<Vector3> vertices = null!;
Assert.Throws<ArgumentNullException>(() => _ = new Polyhedron(vertices)); Assert.ThrowsException<ArgumentNullException>(() => new Polyhedron(vertices));
} }
[Test] [TestMethod]
public void CopyConstructor_ShouldCopyVertices_GivenPolyhedron() public void CopyConstructor_ShouldCopyVertices_GivenPolyhedron()
{ {
var first = Polyhedron.Empty; var first = Polyhedron.Empty;
first.AddVertices(new[] {new Vector3(1, 2, 3), new Vector3(4, 5, 6)}); first.AddVertices(new[] {new Vector3(1, 2, 3), new Vector3(4, 5, 6)});
var second = new Polyhedron(first); var second = new Polyhedron(first);
Assert.Multiple(() => 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. // we cannot use CollectionAssert here for reasons I am not entirely sure of.
// it seems to dislike casting from IReadOnlyList<Point> to ICollection. but okay. // it seems to dislike casting from IReadOnlyList<Point> to ICollection. but okay.
CollectionAssert.AreEqual(first.Vertices, second.Vertices); Assert.IsTrue(first.Vertices.SequenceEqual(second.Vertices));
// assert that the empty polyhedron was not modified // assert that the empty polyhedron was not modified
Assert.That(Polyhedron.Empty.VertexCount, Is.Zero); Assert.AreEqual(0, Polyhedron.Empty.VertexCount);
});
} }
[Test] [TestMethod]
public void Equals_ShouldBeTrue_GivenTwoEmptyPolyhedrons() public void Equals_ShouldBeTrue_GivenTwoEmptyPolyhedrons()
{ {
var first = Polyhedron.Empty; var first = Polyhedron.Empty;
var second = Polyhedron.Empty; var second = Polyhedron.Empty;
Assert.Multiple(() => Assert.AreEqual(first, second);
{ Assert.AreEqual(second, first);
Assert.That(second, Is.EqualTo(first)); Assert.IsTrue(first.Equals(second));
Assert.That(first, Is.EqualTo(second)); Assert.IsTrue(second.Equals(first));
}); Assert.IsTrue(first == second);
Assert.IsTrue(second == first);
Assert.IsFalse(first != second);
Assert.IsFalse(second != first);
} }
[Test] [TestMethod]
public void Equals_ShouldBeTrue_GivenTwoHexagons() public void Equals_ShouldBeTrue_GivenTwoHexagons()
{ {
Polyhedron first = CreateHexagonPolyhedron(); Polyhedron first = CreateHexagon();
Polyhedron second = CreateHexagonPolyhedron(); Polyhedron second = CreateHexagon();
Assert.Multiple(() => Assert.AreEqual(first, second);
{ Assert.AreEqual(second, first);
Assert.That(second, Is.EqualTo(first)); Assert.IsTrue(first.Equals(second));
Assert.That(first, Is.EqualTo(second)); Assert.IsTrue(second.Equals(first));
Assert.That(second == first); Assert.IsTrue(first == second);
Assert.That(first == second); Assert.IsTrue(second == first);
}); Assert.IsFalse(first != second);
Assert.IsFalse(second != first);
} }
[Test] [TestMethod]
public void Equals_ShouldBeFalse_GivenHexagonAndEmptyPolyhedron() public void Equals_ShouldBeFalse_GivenHexagonAndEmptyPolyhedron()
{ {
Polyhedron first = CreateHexagonPolyhedron(); Polyhedron first = CreateHexagon();
Polyhedron second = Polyhedron.Empty; Polyhedron second = Polyhedron.Empty;
Assert.Multiple(() => Assert.AreNotEqual(first, second);
{ Assert.AreNotEqual(second, first);
Assert.That(second, Is.Not.EqualTo(first)); Assert.IsFalse(first.Equals(second));
Assert.That(first, Is.Not.EqualTo(second)); Assert.IsFalse(second.Equals(first));
Assert.That(second != first); Assert.IsFalse(first == second);
Assert.That(first != second); Assert.IsFalse(second == first);
}); Assert.IsTrue(first != second);
Assert.IsTrue(second != first);
} }
[Test] [TestMethod]
public void FromPolygon_ShouldThrowArgumentNullException_GivenNullPolygonF() public void FromPolygon_ShouldThrowArgumentNullException_GivenNullPolygonF()
{ {
Assert.Throws<ArgumentNullException>(() => Polyhedron.FromPolygon(null!)); Assert.ThrowsException<ArgumentNullException>(() => Polyhedron.FromPolygon(null!));
} }
[Test] [TestMethod]
public void FromPolygonF_ShouldThrowArgumentNullException_GivenNullPolygonF() public void FromPolygonF_ShouldThrowArgumentNullException_GivenNullPolygonF()
{ {
Assert.Throws<ArgumentNullException>(() => Polyhedron.FromPolygonF(null!)); Assert.ThrowsException<ArgumentNullException>(() => Polyhedron.FromPolygonF(null!));
} }
[Test] [TestMethod]
public void op_Implicit_ShouldReturnEquivalentPolyhedron_GivenPolyhedron() public void op_Implicit_ShouldReturnEquivalentPolyhedron_GivenPolyhedron()
{ {
Polygon polygon = PolygonTests.CreateHexagon(); Polygon polygon = PolygonTests.CreateHexagon();
Polyhedron converted = polygon; Polyhedron converted = polygon;
Assert.Multiple(() => Assert.AreEqual(polygon, converted);
{ Assert.AreEqual(polygon.VertexCount, converted.VertexCount);
Assert.That(converted, Is.EqualTo((Polyhedron)polygon));
Assert.That(converted.VertexCount, Is.EqualTo(polygon.VertexCount));
CollectionAssert.AreEqual(converted.Vertices, polygon.Vertices.Select(p => Assert.IsTrue(converted.Vertices.SequenceEqual(polygon.Vertices.Select(p =>
{ {
var point = p.ToVector2(); var point = p.ToVector2();
return new Vector3(point.X, point.Y, 0); return new Vector3(point.X, point.Y, 0);
})); })));
});
} }
[Test] [TestMethod]
public void op_Implicit_ShouldReturnEquivalentPolyhedron_GivenPolyhedronF() public void op_Implicit_ShouldReturnEquivalentPolyhedron_GivenPolyhedronF()
{ {
PolygonF polygon = CreateHexagonPolygon(); PolygonF polygon = PolygonFTests.CreateHexagon();
Polyhedron converted = polygon; Polyhedron converted = polygon;
Assert.Multiple(() => Assert.AreEqual(polygon, converted);
Assert.AreEqual(polygon.VertexCount, converted.VertexCount);
Assert.IsTrue(converted.Vertices.SequenceEqual(polygon.Vertices.Select(v =>
{ {
Assert.That(converted, Is.EqualTo((Polyhedron)polygon)); var point = v.ToVector2();
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); return new Vector3(point.X, point.Y, 0);
})); })));
});
} }
[Test] [TestMethod]
public void PointCount_ShouldBe1_GivenPolyhedronWith1Point() public void PointCount_ShouldBe1_GivenPolyhedronWith1Point()
{ {
var polyhedron = new Polyhedron(); var polyhedron = new Polyhedron();
polyhedron.AddVertex(Vector3.One); polyhedron.AddVertex(Vector3.One);
Assert.Multiple(() => Assert.AreEqual(1, polyhedron.VertexCount);
{
Assert.That(polyhedron.VertexCount, Is.EqualTo(1));
// assert that the empty polyhedron was not modified // assert that the empty polyhedron was not modified
Assert.That(Polyhedron.Empty.VertexCount, Is.Zero); Assert.AreEqual(0, Polyhedron.Empty.VertexCount);
});
} }
[Test] [TestMethod]
public void PointCount_ShouldBe0_GivenEmptyPolyhedron() public void PointCount_ShouldBe0_GivenEmptyPolyhedron()
{ {
Assert.That(Polyhedron.Empty.VertexCount, Is.Zero); Assert.AreEqual(0, Polyhedron.Empty.VertexCount);
} }
[Test] [TestMethod]
public void GetHashCode_ShouldBeCorrect_GivenEmptyCircle() public void GetHashCode_ShouldBeCorrect_GivenEmptyCircle()
{ {
// this test is pretty pointless, it exists only for code coverage purposes // this test is pretty pointless, it exists only for code coverage purposes
int hashCode = Polyhedron.Empty.GetHashCode(); int hashCode = Polyhedron.Empty.GetHashCode();
Assert.That(Polyhedron.Empty.GetHashCode(), Is.EqualTo(hashCode)); Assert.AreEqual(hashCode, Polyhedron.Empty.GetHashCode());
} }
private static PolygonF CreateHexagonPolygon() internal static Polyhedron CreateHexagon()
{
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(); var hexagon = new Polyhedron();
hexagon.AddVertex(new Vector3(0, 0, 0)); hexagon.AddVertex(new Vector3(0, 0, 0));
@ -227,7 +202,7 @@ internal class PolyhedronTests
return hexagon; return hexagon;
} }
private static Polyhedron CreateConcavePolyhedron() internal static Polyhedron CreateConcavePolyhedron()
{ {
var hexagon = new Polyhedron(); var hexagon = new Polyhedron();
hexagon.AddVertex(new Vector3(0, 0, 0)); hexagon.AddVertex(new Vector3(0, 0, 0));

View File

@ -1,37 +1,37 @@
using System.Drawing; using System.Drawing;
using NUnit.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting;
using X10D.Drawing; using X10D.Drawing;
namespace X10D.Tests.Drawing; namespace X10D.Tests.Drawing;
[TestFixture] [TestClass]
internal class RandomTests public class RandomTests
{ {
[Test] [TestMethod]
public void NextColorArgb_ShouldReturn331515e5_GivenSeed1234() public void NextColorArgb_ShouldReturn331515e5_GivenSeed1234()
{ {
var random = new Random(1234); var random = new Random(1234);
Assert.That(random.NextColorArgb(), Is.EqualTo(Color.FromArgb(51, 21, 21, 229))); Assert.AreEqual(Color.FromArgb(51, 21, 21, 229), random.NextColorArgb());
} }
[Test] [TestMethod]
public void NextColorArgb_ShouldThrow_GivenNull() public void NextColorArgb_ShouldThrow_GivenNull()
{ {
Random random = null!; Random? random = null;
Assert.Throws<ArgumentNullException>(() => random.NextColorArgb()); Assert.ThrowsException<ArgumentNullException>(() => random!.NextColorArgb());
} }
[Test] [TestMethod]
public void NextColorRgb_ShouldReturn1515e5_GivenSeed1234() public void NextColorRgb_ShouldReturn1515e5_GivenSeed1234()
{ {
var random = new Random(1234); var random = new Random(1234);
Assert.That(random.NextColorRgb(), Is.EqualTo(Color.FromArgb(255, 21, 21, 229))); Assert.AreEqual(Color.FromArgb(255, 21, 21, 229), random.NextColorRgb());
} }
[Test] [TestMethod]
public void NextColorRgb_ShouldThrow_GivenNull() public void NextColorRgb_ShouldThrow_GivenNull()
{ {
Random random = null!; Random? random = null;
Assert.Throws<ArgumentNullException>(() => random.NextColorRgb()); Assert.ThrowsException<ArgumentNullException>(() => random!.NextColorRgb());
} }
} }

View File

@ -1,51 +1,42 @@
using System.Drawing; using System.Drawing;
using NUnit.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting;
using X10D.Drawing; using X10D.Drawing;
namespace X10D.Tests.Drawing; namespace X10D.Tests.Drawing;
[TestFixture] [TestClass]
internal class SizeTests public class SizeTests
{ {
[Test] [TestMethod]
public void ToPoint_ShouldReturnPoint_WithEquivalentMembers() public void ToPoint_ShouldReturnPoint_WithEquivalentMembers()
{ {
var random = new Random(); var random = new Random();
var size = new Size(random.Next(), random.Next()); var size = new Size(random.Next(), random.Next());
var point = size.ToPoint(); var point = size.ToPoint();
Assert.Multiple(() => Assert.AreEqual(size.Width, point.X);
{ Assert.AreEqual(size.Height, point.Y);
Assert.That(point.X, Is.EqualTo(size.Width));
Assert.That(point.Y, Is.EqualTo(size.Height));
});
} }
[Test] [TestMethod]
public void ToPointF_ShouldReturnPoint_WithEquivalentMembers() public void ToPointF_ShouldReturnPoint_WithEquivalentMembers()
{ {
var random = new Random(); var random = new Random();
var size = new Size(random.Next(), random.Next()); var size = new Size(random.Next(), random.Next());
var point = size.ToPointF(); var point = size.ToPointF();
Assert.Multiple(() => Assert.AreEqual(size.Width, point.X, 1e-6f);
{ Assert.AreEqual(size.Height, point.Y, 1e-6f);
Assert.That(point.X, Is.EqualTo(size.Width).Within(1e-6f));
Assert.That(point.Y, Is.EqualTo(size.Height).Within(1e-6f));
});
} }
[Test] [TestMethod]
public void ToVector2_ShouldReturnVector_WithEquivalentMembers() public void ToVector2_ShouldReturnVector_WithEquivalentMembers()
{ {
var random = new Random(); var random = new Random();
var point = new Size(random.Next(), random.Next()); var point = new Size(random.Next(), random.Next());
var size = point.ToVector2(); var size = point.ToVector2();
Assert.Multiple(() => Assert.AreEqual(point.Width, size.X, 1e-6f);
{ Assert.AreEqual(point.Height, size.Y, 1e-6f);
Assert.That(size.X, Is.EqualTo(point.Width).Within(1e-6f));
Assert.That(size.Y, Is.EqualTo(point.Height).Within(1e-6f));
});
} }
} }

View File

@ -1,142 +1,135 @@
using NUnit.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting;
using X10D.Drawing; using X10D.Drawing;
namespace X10D.Tests.Drawing; namespace X10D.Tests.Drawing;
[TestFixture] [TestClass]
internal class SphereTests public class SphereTests
{ {
[Test] [TestMethod]
public void Circumference_ShouldBe2PiRadius_GivenUnitCircle() public void Circumference_ShouldBe2PiRadius_GivenUnitCircle()
{ {
var unitSphere = Sphere.Unit; var unitSphere = Sphere.Unit;
Assert.That(unitSphere.Circumference, Is.EqualTo(2.0f * MathF.PI * unitSphere.Radius).Within(1e-6f)); Assert.AreEqual(2.0f * MathF.PI * unitSphere.Radius, unitSphere.Circumference, 1e-6f);
} }
[Test] [TestMethod]
public void CompareTo_ShouldBeNegativeOne_GivenUnitCircleAndEmpty() public void CompareTo_ShouldBeNegativeOne_GivenUnitCircleAndEmpty()
{ {
Assert.That(Sphere.Empty.CompareTo(Sphere.Unit), Is.EqualTo(-1)); Assert.AreEqual(-1, Sphere.Empty.CompareTo(Sphere.Unit));
} }
[Test] [TestMethod]
public void CompareTo_ShouldBeOne_GivenUnitCircleAndEmpty() public void CompareTo_ShouldBeOne_GivenUnitCircleAndEmpty()
{ {
Assert.That(Sphere.Unit.CompareTo(Sphere.Empty), Is.EqualTo(1)); Assert.AreEqual(1, Sphere.Unit.CompareTo(Sphere.Empty));
} }
[Test] [TestMethod]
public void CompareTo_ShouldBeNegativeOne_GivenEmptyCircleAndUnitCircleAsObject() public void CompareTo_ShouldBeNegativeOne_GivenEmptyCircleAndUnitCircleAsObject()
{ {
Assert.That(Sphere.Empty.CompareTo((object)Sphere.Unit), Is.EqualTo(-1)); Assert.AreEqual(-1, Sphere.Empty.CompareTo((object)Sphere.Unit));
} }
[Test] [TestMethod]
public void CompareTo_ShouldBeOne_GivenNull() public void CompareTo_ShouldBeOne_GivenNull()
{ {
Assert.That(Sphere.Unit.CompareTo(null), Is.EqualTo(1)); Assert.AreEqual(1, Sphere.Unit.CompareTo(null));
} }
[Test] [TestMethod]
public void CompareTo_ShouldBeZero_GivenUnitCircle() public void CompareTo_ShouldBeZero_GivenUnitCircle()
{ {
var unitCircle = Sphere.Unit; var unitCircle = Sphere.Unit;
Assert.That(unitCircle.CompareTo(unitCircle), Is.Zero); Assert.AreEqual(0, unitCircle.CompareTo(unitCircle));
} }
[Test] [TestMethod]
public void CompareTo_ShouldThrowArgumentException_GivenInvalidType() public void CompareTo_ShouldThrowArgumentException_GivenInvalidType()
{ {
Assert.Throws<ArgumentException>(() => _ = Sphere.Unit.CompareTo(new object())); Assert.ThrowsException<ArgumentException>(() => Sphere.Unit.CompareTo(new object()));
} }
[Test] [TestMethod]
public void Diameter_ShouldBe2_GivenUnitSphere() public void Diameter_ShouldBe2_GivenUnitSphere()
{ {
Assert.That(Sphere.Unit.Diameter, Is.EqualTo(2.0f).Within(1e-6f)); Assert.AreEqual(2.0f, Sphere.Unit.Diameter, 1e-6f);
} }
[Test] [TestMethod]
public void Equals_ShouldBeTrue_GivenTwoUnitCircles() public void Equals_ShouldBeTrue_GivenTwoUnitCircles()
{ {
var unitCircle1 = Sphere.Unit; var unitCircle1 = Sphere.Unit;
var unitCircle2 = Sphere.Unit; var unitCircle2 = Sphere.Unit;
Assert.AreEqual(unitCircle1, unitCircle2);
Assert.Multiple(() => Assert.IsTrue(unitCircle1 == unitCircle2);
{ Assert.IsFalse(unitCircle1 != unitCircle2);
Assert.That(unitCircle2, Is.EqualTo(unitCircle1));
Assert.That(unitCircle1, Is.EqualTo(unitCircle2));
Assert.That(unitCircle2 == unitCircle1);
Assert.That(unitCircle1 == unitCircle2);
});
} }
[Test] [TestMethod]
public void Equals_ShouldBeFalse_GivenDifferentObjects() public void Equals_ShouldBeFalse_GivenDifferentObjects()
{ {
Assert.That(Sphere.Unit, Is.Not.EqualTo(null)); Assert.IsFalse(Sphere.Unit.Equals(null));
Assert.That(Sphere.Unit.Equals(null), Is.False);
} }
[Test] [TestMethod]
public void Equals_ShouldBeFalse_GivenDifferentCircles() public void Equals_ShouldBeFalse_GivenDifferentCircles()
{ {
Assert.That(Sphere.Empty, Is.Not.EqualTo(Sphere.Unit)); Assert.AreNotEqual(Sphere.Unit, Sphere.Empty);
Assert.That(Sphere.Unit, Is.Not.EqualTo(Sphere.Empty)); Assert.IsFalse(Sphere.Unit == Sphere.Empty);
Assert.That(Sphere.Empty != Sphere.Unit); Assert.IsTrue(Sphere.Unit != Sphere.Empty);
Assert.That(Sphere.Unit != Sphere.Empty);
} }
[Test] [TestMethod]
public void GetHashCode_ShouldBeCorrect_GivenEmptyCircle() public void GetHashCode_ShouldBeCorrect_GivenEmptyCircle()
{ {
// this test is pretty pointless, it exists only for code coverage purposes // this test is pretty pointless, it exists only for code coverage purposes
int hashCode = Sphere.Empty.GetHashCode(); int hashCode = Sphere.Empty.GetHashCode();
Assert.That(Sphere.Empty.GetHashCode(), Is.EqualTo(hashCode)); Assert.AreEqual(hashCode, Sphere.Empty.GetHashCode());
} }
[Test] [TestMethod]
public void GetHashCode_ShouldBeCorrect_GivenUnitCircle() public void GetHashCode_ShouldBeCorrect_GivenUnitCircle()
{ {
// this test is pretty pointless, it exists only for code coverage purposes // this test is pretty pointless, it exists only for code coverage purposes
int hashCode = Sphere.Unit.GetHashCode(); int hashCode = Sphere.Unit.GetHashCode();
Assert.That(Sphere.Unit.GetHashCode(), Is.EqualTo(hashCode)); Assert.AreEqual(hashCode, Sphere.Unit.GetHashCode());
} }
[Test] [TestMethod]
public void op_GreaterThan_True_GivenUnitAndEmptyCircle() public void op_GreaterThan_True_GivenUnitAndEmptyCircle()
{ {
Assert.That(Sphere.Unit, Is.GreaterThan(Sphere.Empty)); Assert.IsTrue(Sphere.Unit > Sphere.Empty);
Assert.That(Sphere.Unit, Is.GreaterThanOrEqualTo(Sphere.Empty)); Assert.IsTrue(Sphere.Unit >= Sphere.Empty);
Assert.That(Sphere.Unit > Sphere.Empty); Assert.IsFalse(Sphere.Unit < Sphere.Empty);
Assert.That(Sphere.Unit >= Sphere.Empty); Assert.IsFalse(Sphere.Unit <= Sphere.Empty);
} }
[Test] [TestMethod]
public void op_LessThan_True_GivenEmptyAndUnitCircle() public void op_LessThan_True_GivenEmptyAndUnitCircle()
{ {
Assert.That(Sphere.Empty, Is.LessThan(Sphere.Unit)); Assert.IsTrue(Sphere.Empty < Sphere.Unit);
Assert.That(Sphere.Empty, Is.LessThanOrEqualTo(Sphere.Unit)); Assert.IsTrue(Sphere.Empty <= Sphere.Unit);
Assert.That(Sphere.Empty < Sphere.Unit); Assert.IsFalse(Sphere.Empty > Sphere.Unit);
Assert.That(Sphere.Empty <= Sphere.Unit); Assert.IsFalse(Sphere.Empty >= Sphere.Unit);
} }
[Test] [TestMethod]
public void Radius_ShouldBe0_GivenEmptySphere() public void Radius_ShouldBe0_GivenEmptySphere()
{ {
Assert.That(Sphere.Empty.Radius, Is.Zero); Assert.AreEqual(0, Sphere.Empty.Radius);
} }
[Test] [TestMethod]
public void Radius_ShouldBe1_GivenUnitSphere() public void Radius_ShouldBe1_GivenUnitSphere()
{ {
Assert.That(Sphere.Unit.Radius, Is.EqualTo(1)); Assert.AreEqual(1, Sphere.Unit.Radius);
} }
[Test] [TestMethod]
public void Volume_ShouldBe4Over3TimesPi_GivenUnitCircle() public void Volume_ShouldBe4Over3TimesPi_GivenUnitCircle()
{ {
var unitSphere = Sphere.Unit; var unitSphere = Sphere.Unit;
Assert.That(unitSphere.Volume, Is.EqualTo(4.0f / 3.0f * MathF.PI)); Assert.AreEqual(4.0f / 3.0f * MathF.PI, unitSphere.Volume);
} }
} }

View File

@ -1,14 +1,14 @@
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
using NUnit.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting;
using X10D.Hosting.DependencyInjection; using X10D.Hosting.DependencyInjection;
namespace X10D.Tests.Hosting; namespace X10D.Tests.Hosting;
[TestFixture] [TestClass]
internal class ServiceCollectionTests public class ServiceCollectionTests
{ {
[Test] [TestMethod]
public void AddHostedSingleton_ShouldRegisterServiceAsSingletonAndAsHostedService() public void AddHostedSingleton_ShouldRegisterServiceAsSingletonAndAsHostedService()
{ {
var services = new ServiceCollection(); var services = new ServiceCollection();
@ -19,38 +19,14 @@ internal class ServiceCollectionTests
var service = serviceProvider.GetService<TestService>(); var service = serviceProvider.GetService<TestService>();
var hostedService = serviceProvider.GetService<IHostedService>(); var hostedService = serviceProvider.GetService<IHostedService>();
Assert.Multiple(() => Assert.IsNotNull(service);
{ Assert.IsNotNull(hostedService);
Assert.That(service, Is.Not.Null); Assert.IsInstanceOfType(service, typeof(TestService));
Assert.That(hostedService, Is.Not.Null); Assert.IsInstanceOfType(hostedService, typeof(TestService));
Assert.IsAssignableFrom<TestService>(service); Assert.AreSame(service, hostedService);
Assert.IsAssignableFrom<TestService>(hostedService);
Assert.That(hostedService, Is.SameAs(service));
});
} }
[Test] [TestMethod]
public void AddHostedSingleton_ShouldRegisterServiceAsSingletonAndAsHostedService_GivenServiceAndImplTypes()
{
var services = new ServiceCollection();
services.AddHostedSingleton<ITestService, TestService>();
var serviceProvider = services.BuildServiceProvider();
var service = serviceProvider.GetService<ITestService>();
var hostedService = serviceProvider.GetService<IHostedService>();
Assert.Multiple(() =>
{
Assert.That(service, Is.Not.Null);
Assert.That(hostedService, Is.Not.Null);
Assert.IsAssignableFrom<TestService>(service);
Assert.IsAssignableFrom<TestService>(hostedService);
Assert.That(hostedService, Is.SameAs(service));
});
}
[Test]
public void AddHostedSingleton_ShouldRegisterServiceTypeAsSingletonAndAsHostedService() public void AddHostedSingleton_ShouldRegisterServiceTypeAsSingletonAndAsHostedService()
{ {
var services = new ServiceCollection(); var services = new ServiceCollection();
@ -61,48 +37,15 @@ internal class ServiceCollectionTests
var service = serviceProvider.GetService<TestService>(); var service = serviceProvider.GetService<TestService>();
var hostedService = serviceProvider.GetService<IHostedService>(); var hostedService = serviceProvider.GetService<IHostedService>();
Assert.Multiple(() => Assert.IsNotNull(service);
{ Assert.IsNotNull(hostedService);
Assert.That(service, Is.Not.Null); Assert.IsInstanceOfType(service, typeof(TestService));
Assert.That(hostedService, Is.Not.Null); Assert.IsInstanceOfType(hostedService, typeof(TestService));
Assert.IsAssignableFrom<TestService>(service); Assert.AreSame(service, hostedService);
Assert.IsAssignableFrom<TestService>(hostedService);
Assert.That(hostedService, Is.SameAs(service));
});
} }
[Test] private sealed class TestService : IHostedService
public void AddHostedSingleton_ShouldRegisterServiceTypeAsSingletonAndAsHostedService_GivenServiceAndImplTypes()
{ {
var services = new ServiceCollection();
services.AddHostedSingleton(typeof(ITestService), typeof(TestService));
var serviceProvider = services.BuildServiceProvider();
var service = serviceProvider.GetService<ITestService>();
var hostedService = serviceProvider.GetService<IHostedService>();
Assert.Multiple(() =>
{
Assert.That(service, Is.Not.Null);
Assert.That(hostedService, Is.Not.Null);
Assert.IsAssignableFrom<TestService>(service);
Assert.IsAssignableFrom<TestService>(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) public Task StartAsync(CancellationToken cancellationToken)
{ {
return Task.CompletedTask; return Task.CompletedTask;

View File

@ -1,32 +1,32 @@
using NUnit.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting;
using X10D.IO; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
[TestFixture] [TestClass]
internal class BooleanTests public class BooleanTests
{ {
[Test] [TestMethod]
public void GetBytes_ReturnsArrayContaining1() public void GetBytes_ReturnsArrayContaining1()
{ {
const bool value = true; const bool value = true;
CollectionAssert.AreEqual(new byte[] {1}, value.GetBytes()); CollectionAssert.AreEqual(new byte[] {1}, value.GetBytes());
} }
[Test] [TestMethod]
public void TryWriteBytes_ReturnsTrue_FillsSpanContaining1_GivenLargeEnoughSpan() public void TryWriteBytes_ReturnsTrue_FillsSpanContaining1_GivenLargeEnoughSpan()
{ {
const bool value = true; const bool value = true;
Span<byte> buffer = stackalloc byte[1]; Span<byte> buffer = stackalloc byte[1];
Assert.That(value.TryWriteBytes(buffer)); Assert.IsTrue(value.TryWriteBytes(buffer));
CollectionAssert.AreEqual(new byte[] {1}, buffer.ToArray()); CollectionAssert.AreEqual(new byte[] {1}, buffer.ToArray());
} }
[Test] [TestMethod]
public void TryWriteBytes_ReturnsFalse_GivenSmallSpan() public void TryWriteBytes_ReturnsFalse_GivenSmallSpan()
{ {
const bool value = true; const bool value = true;
Span<byte> buffer = stackalloc byte[0]; Span<byte> buffer = stackalloc byte[0];
Assert.That(value.TryWriteBytes(buffer), Is.False); Assert.IsFalse(value.TryWriteBytes(buffer));
} }
} }

View File

@ -1,32 +1,32 @@
using NUnit.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting;
using X10D.IO; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
[TestFixture] [TestClass]
internal class ByteTests public class ByteTests
{ {
[Test] [TestMethod]
public void GetBytes_ReturnsArrayContainingItself() public void GetBytes_ReturnsArrayContainingItself()
{ {
const byte value = 0xFF; const byte value = 0xFF;
CollectionAssert.AreEqual(new[] {value}, value.GetBytes()); CollectionAssert.AreEqual(new[] {value}, value.GetBytes());
} }
[Test] [TestMethod]
public void TryWriteBytes_ReturnsTrue_FillsSpanContainingItself_GivenLargeEnoughSpan() public void TryWriteBytes_ReturnsTrue_FillsSpanContainingItself_GivenLargeEnoughSpan()
{ {
const byte value = 0xFF; const byte value = 0xFF;
Span<byte> buffer = stackalloc byte[1]; Span<byte> buffer = stackalloc byte[1];
Assert.That(value.TryWriteBytes(buffer)); Assert.IsTrue(value.TryWriteBytes(buffer));
CollectionAssert.AreEqual(new[] {value}, buffer.ToArray()); CollectionAssert.AreEqual(new[] {value}, buffer.ToArray());
} }
[Test] [TestMethod]
public void TryWriteBytes_ReturnsFalse_GivenSmallSpan() public void TryWriteBytes_ReturnsFalse_GivenSmallSpan()
{ {
const byte value = 0x0F; const byte value = 0x0F;
Span<byte> buffer = stackalloc byte[0]; Span<byte> buffer = stackalloc byte[0];
Assert.That(value.TryWriteBytes(buffer), Is.False); Assert.IsFalse(value.TryWriteBytes(buffer));
} }
} }

View File

@ -1,19 +1,19 @@
using NUnit.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting;
using X10D.IO; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
[TestFixture] [TestClass]
internal class DirectoryInfoTests public class DirectoryInfoTests
{ {
[Test] [TestMethod]
public void Clear_ShouldClear_GivenValidDirectory() public void Clear_ShouldClear_GivenValidDirectory()
{ {
string tempDirectoryPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); string tempDirectoryPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
var tempDirectory = new DirectoryInfo(tempDirectoryPath); var tempDirectory = new DirectoryInfo(tempDirectoryPath);
tempDirectory.Create(); tempDirectory.Create();
Assert.That(tempDirectory.Exists); Assert.IsTrue(tempDirectory.Exists);
var file = new FileInfo(Path.Combine(tempDirectory.FullName, "file")); var file = new FileInfo(Path.Combine(tempDirectory.FullName, "file"));
file.Create().Close(); file.Create().Close();
@ -24,42 +24,34 @@ internal class DirectoryInfoTests
var childFile = new FileInfo(Path.Combine(childDirectory.FullName, "childFile")); var childFile = new FileInfo(Path.Combine(childDirectory.FullName, "childFile"));
childFile.Create().Close(); childFile.Create().Close();
Assert.Multiple(() => Assert.AreEqual(1, tempDirectory.GetFiles().Length);
{ Assert.AreEqual(1, tempDirectory.GetDirectories().Length);
Assert.That(tempDirectory.GetFiles(), Has.Length.EqualTo(1));
Assert.That(tempDirectory.GetDirectories(), Has.Length.EqualTo(1));
});
tempDirectory.Clear(); tempDirectory.Clear();
Assert.AreEqual(0, tempDirectory.GetFiles().Length);
Assert.Multiple(() => Assert.AreEqual(0, tempDirectory.GetDirectories().Length);
{ Assert.IsTrue(tempDirectory.Exists);
Assert.That(tempDirectory.GetFiles(), Is.Empty);
Assert.That(tempDirectory.GetDirectories(), Is.Empty);
Assert.That(tempDirectory.Exists);
});
tempDirectory.Delete(); tempDirectory.Delete();
} }
[Test] [TestMethod]
public void Clear_ShouldThrowArgumentNullException_GivenNull() public void Clear_ShouldThrowArgumentNullException_GivenNull()
{ {
Assert.Throws<ArgumentNullException>(() => ((DirectoryInfo?)null)!.Clear()); Assert.ThrowsException<ArgumentNullException>(() => ((DirectoryInfo?)null)!.Clear());
} }
[Test] [TestMethod]
public void Clear_ShouldThrowDirectoryNotFoundException_GivenInvalidDirectory() public void Clear_ShouldThrowDirectoryNotFoundException_GivenInvalidDirectory()
{ {
var directory = new DirectoryInfo(@"123:/@12#3"); var directory = new DirectoryInfo(@"123:/@12#3");
Assert.Throws<DirectoryNotFoundException>(() => directory.Clear()); Assert.ThrowsException<DirectoryNotFoundException>(() => directory.Clear());
} }
[Test] [TestMethod]
public void Clear_ShouldThrowDirectoryNotFoundException_GivenNonExistentDirectory() public void Clear_ShouldThrowDirectoryNotFoundException_GivenNonExistentDirectory()
{ {
var directory = new DirectoryInfo(@"/@12#3"); var directory = new DirectoryInfo(@"/@12#3");
Assert.That(directory.Exists, Is.False); Assert.IsFalse(directory.Exists);
Assert.Throws<DirectoryNotFoundException>(() => directory.Clear()); Assert.ThrowsException<DirectoryNotFoundException>(() => directory.Clear());
} }
} }

View File

@ -1,66 +1,66 @@
using NUnit.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting;
using X10D.IO; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
[TestFixture] [TestClass]
internal class DoubleTests public class DoubleTests
{ {
[Test] [TestMethod]
public void GetBigEndianBytes_ReturnsCorrectValue() public void GetBytes_ReturnsCorrectValue()
{ {
const double value = 42.5; const double value = 42.5;
byte[] bytes = BitConverter.IsLittleEndian
var expected = new byte[] { 0x40, 0x45, 0x40, 0, 0, 0, 0, 0 }; ? new byte[] {0, 0, 0, 0, 0, 0x40, 0x45, 0x40}
byte[] actual = value.GetBigEndianBytes(); : new byte[] {0x40, 0x45, 0x40, 0, 0, 0, 0, 0};
CollectionAssert.AreEqual(expected, actual); CollectionAssert.AreEqual(bytes, value.GetBytes());
} }
[Test] [TestMethod]
public void GetLittleEndianBytes_ReturnsCorrectValue() public void GetBytes_ReturnsCorrectValue_WithEndianness()
{ {
const double value = 42.5; 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};
var expected = new byte[] { 0, 0, 0, 0, 0, 0x40, 0x45, 0x40 }; CollectionAssert.AreEqual(littleEndian, value.GetBytes(Endianness.LittleEndian));
byte[] actual = value.GetLittleEndianBytes(); CollectionAssert.AreEqual(bigEndian, value.GetBytes(Endianness.BigEndian));
CollectionAssert.AreEqual(expected, actual);
} }
[Test] [TestMethod]
public void TryWriteBigEndian_ReturnsTrue_FillsSpanCorrectly() public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan()
{ {
const double value = 42.5; 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};
var expected = new byte[] { 0x40, 0x45, 0x40, 0, 0, 0, 0, 0 }; Span<byte> buffer = stackalloc byte[8];
Span<byte> actual = stackalloc byte[8]; Assert.IsTrue(value.TryWriteBytes(buffer));
Assert.That(value.TryWriteBigEndian(actual)); CollectionAssert.AreEqual(bytes, buffer.ToArray());
CollectionAssert.AreEqual(expected, actual.ToArray());
} }
[Test] [TestMethod]
public void TryWriteLittleEndian_ReturnsTrue_FillsSpanCorrectly() public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan_WithEndianness()
{ {
const double value = 42.5; 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};
var expected = new byte[] { 0, 0, 0, 0, 0, 0x40, 0x45, 0x40 }; Span<byte> buffer = stackalloc byte[8];
Span<byte> actual = stackalloc byte[8];
Assert.That(value.TryWriteLittleEndian(actual)); Assert.IsTrue(value.TryWriteBytes(buffer, Endianness.LittleEndian));
CollectionAssert.AreEqual(expected, actual.ToArray()); CollectionAssert.AreEqual(littleEndian, buffer.ToArray());
Assert.IsTrue(value.TryWriteBytes(buffer, Endianness.BigEndian));
CollectionAssert.AreEqual(bigEndian, buffer.ToArray());
} }
[Test] [TestMethod]
public void TryWriteBigEndian_ReturnsFalse_GivenSmallSpan() public void TryWriteBytes_ReturnsFalse_GivenSmallSpan()
{ {
const double value = 42.5; const double value = 42.5;
Span<byte> buffer = stackalloc byte[0]; Span<byte> buffer = stackalloc byte[0];
Assert.That(value.TryWriteBigEndian(buffer), Is.False); Assert.IsFalse(value.TryWriteBytes(buffer));
}
[Test]
public void TryWriteLittleEndian_RReturnsFalse_GivenSmallSpan()
{
const double value = 42.5;
Span<byte> buffer = stackalloc byte[0];
Assert.That(value.TryWriteLittleEndian(buffer), Is.False);
} }
} }

View File

@ -1,23 +1,23 @@
using System.Security.Cryptography; using System.Security.Cryptography;
using NUnit.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting;
using X10D.IO; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
[TestFixture] [TestClass]
internal class FileInfoTests public class FileInfoTests
{ {
[Test] [TestMethod]
public void GetHashSha1ShouldBeCorrect() public void GetHashSha1ShouldBeCorrect()
{ {
var fileName = $"temp.{DateTimeOffset.Now.ToUnixTimeSeconds()}.bin"; string fileName = $"temp.{DateTimeOffset.Now.ToUnixTimeSeconds()}.bin";
if (File.Exists(fileName)) if (File.Exists(fileName))
{ {
Assert.Fail("Temporary file already exists"); Assert.Fail("Temporary file already exists");
} }
File.WriteAllText(fileName, "Hello World"); File.WriteAllText(fileName, "Hello World");
Assert.That(File.Exists(fileName)); Assert.IsTrue(File.Exists(fileName));
// SHA-1 // SHA-1
byte[] expectedHash = byte[] expectedHash =
@ -37,17 +37,17 @@ internal class FileInfoTests
} }
} }
[Test] [TestMethod]
public void TryWriteHashSha1ShouldBeCorrect() public void TryWriteHashSha1ShouldBeCorrect()
{ {
var fileName = $"temp.{DateTimeOffset.Now.ToUnixTimeSeconds()}.bin"; string fileName = $"temp.{DateTimeOffset.Now.ToUnixTimeSeconds()}.bin";
if (File.Exists(fileName)) if (File.Exists(fileName))
{ {
Assert.Fail("Temporary file already exists"); Assert.Fail("Temporary file already exists");
} }
File.WriteAllText(fileName, "Hello World"); File.WriteAllText(fileName, "Hello World");
Assert.That(File.Exists(fileName)); Assert.IsTrue(File.Exists(fileName));
// SHA-1 // SHA-1
byte[] expectedHash = byte[] expectedHash =
@ -60,7 +60,7 @@ internal class FileInfoTests
{ {
Span<byte> hash = stackalloc byte[20]; Span<byte> hash = stackalloc byte[20];
new FileInfo(fileName).TryWriteHash<SHA1>(hash, out int bytesWritten); new FileInfo(fileName).TryWriteHash<SHA1>(hash, out int bytesWritten);
Assert.That(bytesWritten, Is.EqualTo(expectedHash.Length)); Assert.AreEqual(expectedHash.Length, bytesWritten);
CollectionAssert.AreEqual(expectedHash, hash.ToArray()); CollectionAssert.AreEqual(expectedHash, hash.ToArray());
} }
finally finally
@ -69,25 +69,25 @@ internal class FileInfoTests
} }
} }
[Test] [TestMethod]
public void GetHashNullShouldThrow() public void GetHashNullShouldThrow()
{ {
// any HashAlgorithm will do, but SHA1 is used above. so to remain consistent, we use it here // any HashAlgorithm will do, but SHA1 is used above. so to remain consistent, we use it here
Assert.Throws<ArgumentNullException>(() => _ = ((FileInfo?)null)!.GetHash<SHA1>()); Assert.ThrowsException<ArgumentNullException>(() => ((FileInfo?)null)!.GetHash<SHA1>());
Assert.Throws<ArgumentNullException>(() => ((FileInfo?)null)!.TryWriteHash<SHA1>(Span<byte>.Empty, out _)); Assert.ThrowsException<ArgumentNullException>(() => ((FileInfo?)null)!.TryWriteHash<SHA1>(Span<byte>.Empty, out _));
} }
[Test] [TestMethod]
public void GetHashInvalidFileShouldThrow() public void GetHashInvalidFileShouldThrow()
{ {
var fileName = $"temp.{DateTimeOffset.Now.ToUnixTimeSeconds()}.bin"; string fileName = $"temp.{DateTimeOffset.Now.ToUnixTimeSeconds()}.bin";
if (File.Exists(fileName)) if (File.Exists(fileName))
{ {
Assert.Fail("Temporary file already exists"); Assert.Fail("Temporary file already exists");
} }
// any HashAlgorithm will do, but SHA1 is used above. so to remain consistent, we use it here // any HashAlgorithm will do, but SHA1 is used above. so to remain consistent, we use it here
Assert.Throws<FileNotFoundException>(() => _ = new FileInfo(fileName).GetHash<SHA1>()); Assert.ThrowsException<FileNotFoundException>(() => new FileInfo(fileName).GetHash<SHA1>());
Assert.Throws<FileNotFoundException>(() => new FileInfo(fileName).TryWriteHash<SHA1>(Span<byte>.Empty, out _)); Assert.ThrowsException<FileNotFoundException>(() => new FileInfo(fileName).TryWriteHash<SHA1>(Span<byte>.Empty, out _));
} }
} }

View File

@ -1,66 +1,62 @@
using NUnit.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting;
using X10D.IO; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
[TestFixture] [TestClass]
internal class Int16Tests public class Int16Tests
{ {
[Test] [TestMethod]
public void GetLittleEndianBytes_ReturnsCorrectValue() public void GetBytes_ReturnsCorrectValue()
{ {
const short value = 0x0F; const short value = 0x0F;
byte[] bytes = BitConverter.IsLittleEndian ? new byte[] {0x0F, 0} : new byte[] {0, 0x0F};
byte[] expected = { 0x0F, 0 }; CollectionAssert.AreEqual(bytes, value.GetBytes());
byte[] actual = value.GetLittleEndianBytes();
CollectionAssert.AreEqual(expected, actual);
} }
[Test] [TestMethod]
public void GetBigEndianBytes_ReturnsCorrectValue() public void GetBytes_ReturnsCorrectValue_WithEndianness()
{ {
const short value = 0x0F; const short value = 0x0F;
byte[] littleEndian = {0x0F, 0};
byte[] bigEndian = {0, 0x0F};
byte[] expected = { 0, 0x0F }; CollectionAssert.AreEqual(littleEndian, value.GetBytes(Endianness.LittleEndian));
byte[] actual = value.GetBigEndianBytes(); CollectionAssert.AreEqual(bigEndian, value.GetBytes(Endianness.BigEndian));
CollectionAssert.AreEqual(expected, actual);
} }
[Test] [TestMethod]
public void TryWriteLittleEndian_ReturnsTrue_FillsSpanCorrectly() public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan()
{ {
const short value = 0x0F; const short value = 0x0F;
byte[] bytes = BitConverter.IsLittleEndian ? new byte[] {0x0F, 0} : new byte[] {0, 0x0F};
byte[] expected = { 0x0F, 0 }; Span<byte> buffer = stackalloc byte[2];
Span<byte> actual = stackalloc byte[2]; Assert.IsTrue(value.TryWriteBytes(buffer));
Assert.That(value.TryWriteLittleEndian(actual)); CollectionAssert.AreEqual(bytes, buffer.ToArray());
CollectionAssert.AreEqual(expected, actual.ToArray());
} }
[Test] [TestMethod]
public void TryWriteBigEndian_ReturnsTrue_FillsSpanCorrectly() public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan_WithEndianness()
{ {
const short value = 0x0F; const short value = 0x0F;
byte[] littleEndian = {0x0F, 0};
byte[] bigEndian = {0, 0x0F};
byte[] expected = { 0, 0x0F }; Span<byte> buffer = stackalloc byte[2];
Span<byte> actual = stackalloc byte[2];
Assert.That(value.TryWriteBigEndian(actual)); Assert.IsTrue(value.TryWriteBytes(buffer, Endianness.LittleEndian));
CollectionAssert.AreEqual(expected, actual.ToArray()); CollectionAssert.AreEqual(littleEndian, buffer.ToArray());
Assert.IsTrue(value.TryWriteBytes(buffer, Endianness.BigEndian));
CollectionAssert.AreEqual(bigEndian, buffer.ToArray());
} }
[Test] [TestMethod]
public void TryWriteLittleEndian_RReturnsFalse_GivenSmallSpan() public void TryWriteBytes_ReturnsFalse_GivenSmallSpan()
{ {
const short value = 0x0F; const short value = 0x0F;
Span<byte> buffer = stackalloc byte[0]; Span<byte> buffer = stackalloc byte[0];
Assert.That(value.TryWriteLittleEndian(buffer), Is.False); Assert.IsFalse(value.TryWriteBytes(buffer));
}
[Test]
public void TryWriteBigEndian_ReturnsFalse_GivenSmallSpan()
{
const short value = 0x0F;
Span<byte> buffer = stackalloc byte[0];
Assert.That(value.TryWriteBigEndian(buffer), Is.False);
} }
} }

View File

@ -1,66 +1,62 @@
using NUnit.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting;
using X10D.IO; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
[TestFixture] [TestClass]
internal class Int32Tests public class Int32Tests
{ {
[Test] [TestMethod]
public void GetBigEndianBytes_ReturnsCorrectValue() public void GetBytes_ReturnsCorrectValue()
{ {
const int value = 0x0F; const int value = 0x0F;
byte[] bytes = BitConverter.IsLittleEndian ? new byte[] {0x0F, 0, 0, 0} : new byte[] {0, 0, 0, 0x0F};
var expected = new byte[] { 0, 0, 0, 0x0F }; CollectionAssert.AreEqual(bytes, value.GetBytes());
byte[] actual = value.GetBigEndianBytes();
CollectionAssert.AreEqual(expected, actual);
} }
[Test] [TestMethod]
public void GetLittleEndianBytes_ReturnsCorrectValue() public void GetBytes_ReturnsCorrectValue_WithEndianness()
{ {
const int value = 0x0F; const int value = 0x0F;
byte[] littleEndian = {0x0F, 0, 0, 0};
byte[] bigEndian = {0, 0, 0, 0x0F};
var expected = new byte[] { 0x0F, 0, 0, 0 }; CollectionAssert.AreEqual(littleEndian, value.GetBytes(Endianness.LittleEndian));
byte[] actual = value.GetLittleEndianBytes(); CollectionAssert.AreEqual(bigEndian, value.GetBytes(Endianness.BigEndian));
CollectionAssert.AreEqual(expected, actual);
} }
[Test] [TestMethod]
public void TryWriteBigEndian_ReturnsTrue_FillsSpanCorrectly() public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan()
{ {
const int value = 0x0F; const int value = 0x0F;
byte[] bytes = BitConverter.IsLittleEndian ? new byte[] {0x0F, 0, 0, 0} : new byte[] {0, 0, 0, 0x0F};
var expected = new byte[] { 0, 0, 0, 0x0F }; Span<byte> buffer = stackalloc byte[4];
Span<byte> actual = stackalloc byte[4]; Assert.IsTrue(value.TryWriteBytes(buffer));
Assert.That(value.TryWriteBigEndian(actual)); CollectionAssert.AreEqual(bytes, buffer.ToArray());
CollectionAssert.AreEqual(expected, actual.ToArray());
} }
[Test] [TestMethod]
public void TryWriteLittleEndian_ReturnsTrue_FillsSpanCorrectly() public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan_WithEndianness()
{ {
const int value = 0x0F; const int value = 0x0F;
byte[] littleEndian = {0x0F, 0, 0, 0};
byte[] bigEndian = {0, 0, 0, 0x0F};
var expected = new byte[] { 0x0F, 0, 0, 0 }; Span<byte> buffer = stackalloc byte[4];
Span<byte> actual = stackalloc byte[4];
Assert.That(value.TryWriteLittleEndian(actual)); Assert.IsTrue(value.TryWriteBytes(buffer, Endianness.LittleEndian));
CollectionAssert.AreEqual(expected, actual.ToArray()); CollectionAssert.AreEqual(littleEndian, buffer.ToArray());
Assert.IsTrue(value.TryWriteBytes(buffer, Endianness.BigEndian));
CollectionAssert.AreEqual(bigEndian, buffer.ToArray());
} }
[Test] [TestMethod]
public void TryWriteBigEndian_ReturnsFalse_GivenSmallSpan() public void TryWriteBytes_ReturnsFalse_GivenSmallSpan()
{ {
const int value = 0x0F; const int value = 0x0F;
Span<byte> buffer = stackalloc byte[0]; Span<byte> buffer = stackalloc byte[0];
Assert.That(value.TryWriteBigEndian(buffer), Is.False); Assert.IsFalse(value.TryWriteBytes(buffer));
}
[Test]
public void TryWriteLittleEndian_RReturnsFalse_GivenSmallSpan()
{
const int value = 0x0F;
Span<byte> buffer = stackalloc byte[0];
Assert.That(value.TryWriteLittleEndian(buffer), Is.False);
} }
} }

View File

@ -1,66 +1,66 @@
using NUnit.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting;
using X10D.IO; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
[TestFixture] [TestClass]
internal class Int64Tests public class Int64Tests
{ {
[Test] [TestMethod]
public void GetLittleEndianBytes_ReturnsCorrectValue() public void GetBytes_ReturnsCorrectValue()
{ {
const long value = 0x0F; const long value = 0x0F;
byte[] bytes = BitConverter.IsLittleEndian
byte[] expected = { 0x0F, 0, 0, 0, 0, 0, 0, 0 }; ? new byte[] {0x0F, 0, 0, 0, 0, 0, 0, 0}
byte[] actual = value.GetLittleEndianBytes(); : new byte[] {0, 0, 0, 0, 0, 0, 0, 0x0F};
CollectionAssert.AreEqual(expected, actual); CollectionAssert.AreEqual(bytes, value.GetBytes());
} }
[Test] [TestMethod]
public void GetBigEndianBytes_ReturnsCorrectValue() public void GetBytes_ReturnsCorrectValue_WithEndianness()
{ {
const long value = 0x0F; const long 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 }; CollectionAssert.AreEqual(littleEndian, value.GetBytes(Endianness.LittleEndian));
byte[] actual = value.GetBigEndianBytes(); CollectionAssert.AreEqual(bigEndian, value.GetBytes(Endianness.BigEndian));
CollectionAssert.AreEqual(expected, actual);
} }
[Test] [TestMethod]
public void TryWriteLittleEndian_ReturnsTrue_FillsSpanCorrectly() public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan()
{ {
const long value = 0x0F; 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};
byte[] expected = { 0x0F, 0, 0, 0, 0, 0, 0, 0 }; Span<byte> buffer = stackalloc byte[8];
Span<byte> actual = stackalloc byte[8]; Assert.IsTrue(value.TryWriteBytes(buffer));
Assert.That(value.TryWriteLittleEndian(actual)); CollectionAssert.AreEqual(bytes, buffer.ToArray());
CollectionAssert.AreEqual(expected, actual.ToArray());
} }
[Test] [TestMethod]
public void TryWriteBigEndian_ReturnsTrue_FillsSpanCorrectly() public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan_WithEndianness()
{ {
const long value = 0x0F; const long 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<byte> buffer = stackalloc byte[8];
Span<byte> actual = stackalloc byte[8];
Assert.That(value.TryWriteBigEndian(actual)); Assert.IsTrue(value.TryWriteBytes(buffer, Endianness.LittleEndian));
CollectionAssert.AreEqual(expected, actual.ToArray()); CollectionAssert.AreEqual(littleEndian, buffer.ToArray());
Assert.IsTrue(value.TryWriteBytes(buffer, Endianness.BigEndian));
CollectionAssert.AreEqual(bigEndian, buffer.ToArray());
} }
[Test] [TestMethod]
public void TryWriteLittleEndian_RReturnsFalse_GivenSmallSpan() public void TryWriteBytes_ReturnsFalse_GivenSmallSpan()
{ {
const long value = 0x0F; const long value = 0x0F;
Span<byte> buffer = stackalloc byte[0]; Span<byte> buffer = stackalloc byte[0];
Assert.That(value.TryWriteLittleEndian(buffer), Is.False); Assert.IsFalse(value.TryWriteBytes(buffer));
}
[Test]
public void TryWriteBigEndian_ReturnsFalse_GivenSmallSpan()
{
const long value = 0x0F;
Span<byte> buffer = stackalloc byte[0];
Assert.That(value.TryWriteBigEndian(buffer), Is.False);
} }
} }

View File

@ -1,27 +1,27 @@
using System.Text; using System.Text;
using NUnit.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting;
using X10D.IO; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
[TestFixture] [TestClass]
internal class ListOfByteTests public class ListOfByteTests
{ {
[Test] [TestMethod]
public void AsString_ShouldReturnBytes_GivenBytes() public void AsString_ShouldReturnBytes_GivenBytes()
{ {
var bytes = new byte[] {0x01, 0x02, 0x03, 0x04, 0x05}; var bytes = new byte[] {0x01, 0x02, 0x03, 0x04, 0x05};
Assert.That(bytes.AsString(), Is.EqualTo("01-02-03-04-05")); Assert.AreEqual("01-02-03-04-05", bytes.AsString());
} }
[Test] [TestMethod]
public void AsString_ShouldThrow_GivenNullArray() public void AsString_ShouldThrow_GivenNullArray()
{ {
byte[]? bytes = null; byte[]? bytes = null;
Assert.Throws<ArgumentNullException>(() => bytes!.AsString()); Assert.ThrowsException<ArgumentNullException>(() => bytes!.AsString());
} }
[Test] [TestMethod]
public void ToDouble_ShouldReturnDouble_GivenBytes() public void ToDouble_ShouldReturnDouble_GivenBytes()
{ {
var bytes = new byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x7A, 0x40}; var bytes = new byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x7A, 0x40};
@ -31,59 +31,59 @@ internal class ListOfByteTests
Array.Reverse(bytes); Array.Reverse(bytes);
} }
Assert.That(bytes.ToDouble(), Is.EqualTo(420.0).Within(1e-6)); Assert.AreEqual(420.0, bytes.ToDouble(), 1e-6);
} }
[Test] [TestMethod]
public void ToDouble_ShouldThrow_GivenNullArray() public void ToDouble_ShouldThrow_GivenNullArray()
{ {
byte[] bytes = null!; byte[]? bytes = null;
Assert.Throws<ArgumentNullException>(() => bytes.ToDouble()); Assert.ThrowsException<ArgumentNullException>(() => bytes!.ToDouble());
} }
[Test] [TestMethod]
public void ToInt16_ShouldReturnInt16_GivenBytes() public void ToInt16_ShouldReturnInt16_GivenBytes()
{ {
var bytes = new byte[] {0xA4, 0x01}; var bytes = new byte[] {0xA4, 0x01};
Assert.That(bytes.ToInt16(), Is.EqualTo(420)); Assert.AreEqual(420, bytes.ToInt16());
} }
[Test] [TestMethod]
public void ToInt16_ShouldThrow_GivenNullArray() public void ToInt16_ShouldThrow_GivenNullArray()
{ {
byte[] bytes = null!; byte[]? bytes = null;
Assert.Throws<ArgumentNullException>(() => bytes.ToInt16()); Assert.ThrowsException<ArgumentNullException>(() => bytes!.ToInt16());
} }
[Test] [TestMethod]
public void ToInt32_ShouldReturnInt32_GivenBytes() public void ToInt32_ShouldReturnInt32_GivenBytes()
{ {
var bytes = new byte[] {0xA4, 0x01, 0x00, 0x00}; var bytes = new byte[] {0xA4, 0x01, 0x00, 0x00};
Assert.That(bytes.ToInt32(), Is.EqualTo(420)); Assert.AreEqual(420, bytes.ToInt32());
} }
[Test] [TestMethod]
public void ToInt32_ShouldThrow_GivenNullArray() public void ToInt32_ShouldThrow_GivenNullArray()
{ {
byte[] bytes = null!; byte[]? bytes = null;
Assert.Throws<ArgumentNullException>(() => bytes.ToInt32()); Assert.ThrowsException<ArgumentNullException>(() => bytes!.ToInt32());
} }
[Test] [TestMethod]
public void ToInt64_ShouldReturnInt32_GivenBytes() public void ToInt64_ShouldReturnInt32_GivenBytes()
{ {
var bytes = new byte[] {0xA4, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; var bytes = new byte[] {0xA4, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
Assert.That(bytes.ToInt64(), Is.EqualTo(420L)); Assert.AreEqual(420L, bytes.ToInt64());
} }
[Test] [TestMethod]
public void ToInt64_ShouldThrow_GivenNullArray() public void ToInt64_ShouldThrow_GivenNullArray()
{ {
byte[]? bytes = null; byte[]? bytes = null;
Assert.Throws<ArgumentNullException>(() => bytes!.ToInt64()); Assert.ThrowsException<ArgumentNullException>(() => bytes!.ToInt64());
} }
[Test] [TestMethod]
public void ToSingle_ShouldReturnDouble_GivenBytes() public void ToSingle_ShouldReturnDouble_GivenBytes()
{ {
var bytes = new byte[] {0x00, 0x00, 0xD2, 0x43}; var bytes = new byte[] {0x00, 0x00, 0xD2, 0x43};
@ -93,76 +93,76 @@ internal class ListOfByteTests
Array.Reverse(bytes); Array.Reverse(bytes);
} }
Assert.That(bytes.ToSingle(), Is.EqualTo(420.0).Within(1e-6)); Assert.AreEqual(420.0, bytes.ToSingle(), 1e-6);
} }
[Test] [TestMethod]
public void ToSingle_ShouldThrow_GivenNullArray() public void ToSingle_ShouldThrow_GivenNullArray()
{ {
byte[] bytes = null!; byte[]? bytes = null;
Assert.Throws<ArgumentNullException>(() => bytes.ToSingle()); Assert.ThrowsException<ArgumentNullException>(() => bytes!.ToSingle());
} }
[Test] [TestMethod]
public void ToString_ShouldReturnHelloWorld_GivenUTF8() public void ToString_ShouldReturnHelloWorld_GivenUTF8()
{ {
var bytes = new byte[] {0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64}; var bytes = new byte[] {0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64};
Assert.That(bytes.ToString(Encoding.UTF8), Is.EqualTo("Hello World")); Assert.AreEqual("Hello World", bytes.ToString(Encoding.UTF8));
} }
[Test] [TestMethod]
public void ToString_ShouldThrow_GivenNullArray() public void ToString_ShouldThrow_GivenNullArray()
{ {
byte[] bytes = null!; byte[]? bytes = null;
Assert.Throws<ArgumentNullException>(() => bytes.ToString(Encoding.UTF8)); Assert.ThrowsException<ArgumentNullException>(() => bytes!.ToString(Encoding.UTF8));
} }
[Test] [TestMethod]
public void ToString_ShouldThrow_GivenNullEncoding() public void ToString_ShouldThrow_GivenNullEncoding()
{ {
var bytes = new byte[] {0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64}; var bytes = new byte[] {0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64};
Assert.Throws<ArgumentNullException>(() => bytes.ToString(null!)); Assert.ThrowsException<ArgumentNullException>(() => bytes.ToString(null!));
} }
[Test] [TestMethod]
public void ToUInt16_ShouldReturnInt16_GivenBytes() public void ToUInt16_ShouldReturnInt16_GivenBytes()
{ {
var bytes = new byte[] {0xA4, 0x01}; var bytes = new byte[] {0xA4, 0x01};
Assert.That(bytes.ToUInt16(), Is.EqualTo((ushort)420)); Assert.AreEqual((ushort)420, bytes.ToUInt16());
} }
[Test] [TestMethod]
public void ToUInt16_ShouldThrow_GivenNullArray() public void ToUInt16_ShouldThrow_GivenNullArray()
{ {
byte[] bytes = null!; byte[]? bytes = null;
Assert.Throws<ArgumentNullException>(() => bytes.ToUInt16()); Assert.ThrowsException<ArgumentNullException>(() => bytes!.ToUInt16());
} }
[Test] [TestMethod]
public void ToUInt32_ShouldReturnInt32_GivenBytes() public void ToUInt32_ShouldReturnInt32_GivenBytes()
{ {
var bytes = new byte[] {0xA4, 0x01, 0x00, 0x00}; var bytes = new byte[] {0xA4, 0x01, 0x00, 0x00};
Assert.That(bytes.ToUInt32(), Is.EqualTo(420U)); Assert.AreEqual(420U, bytes.ToUInt32());
} }
[Test] [TestMethod]
public void ToUInt32_ShouldThrow_GivenNullArray() public void ToUInt32_ShouldThrow_GivenNullArray()
{ {
byte[]? bytes = null; byte[]? bytes = null;
Assert.Throws<ArgumentNullException>(() => bytes!.ToUInt32()); Assert.ThrowsException<ArgumentNullException>(() => bytes!.ToUInt32());
} }
[Test] [TestMethod]
public void ToUInt64_ShouldReturnInt32_GivenBytes() public void ToUInt64_ShouldReturnInt32_GivenBytes()
{ {
var bytes = new byte[] {0xA4, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; var bytes = new byte[] {0xA4, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
Assert.That(bytes.ToUInt64(), Is.EqualTo(420UL)); Assert.AreEqual(420UL, bytes.ToUInt64());
} }
[Test] [TestMethod]
public void ToUInt64_ShouldThrow_GivenNullArray() public void ToUInt64_ShouldThrow_GivenNullArray()
{ {
byte[] bytes = null!; byte[]? bytes = null;
Assert.Throws<ArgumentNullException>(() => bytes.ToUInt64()); Assert.ThrowsException<ArgumentNullException>(() => bytes!.ToUInt64());
} }
} }

View File

@ -1,32 +1,33 @@
using NUnit.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting;
using X10D.IO; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
[TestFixture] [TestClass]
internal class SByteTests [CLSCompliant(false)]
public class SByteTests
{ {
[Test] [TestMethod]
public void GetBytes_ReturnsArrayContainingItself() public void GetBytes_ReturnsArrayContainingItself()
{ {
const sbyte value = 0x0F; const sbyte value = 0x0F;
CollectionAssert.AreEqual(new[] {(byte)value}, value.GetBytes()); CollectionAssert.AreEqual(new[] {(byte)value}, value.GetBytes());
} }
[Test] [TestMethod]
public void TryWriteBytes_ReturnsTrue_FillsSpanContainingItself_GivenLargeEnoughSpan() public void TryWriteBytes_ReturnsTrue_FillsSpanContainingItself_GivenLargeEnoughSpan()
{ {
const sbyte value = 0x0F; const sbyte value = 0x0F;
Span<byte> buffer = stackalloc byte[1]; Span<byte> buffer = stackalloc byte[1];
Assert.That(value.TryWriteBytes(buffer)); Assert.IsTrue(value.TryWriteBytes(buffer));
CollectionAssert.AreEqual(new[] {(byte)value}, buffer.ToArray()); CollectionAssert.AreEqual(new[] {(byte)value}, buffer.ToArray());
} }
[Test] [TestMethod]
public void TryWriteBytes_ReturnsFalse_GivenSmallSpan() public void TryWriteBytes_ReturnsFalse_GivenSmallSpan()
{ {
const sbyte value = 0x0F; const sbyte value = 0x0F;
Span<byte> buffer = stackalloc byte[0]; Span<byte> buffer = stackalloc byte[0];
Assert.That(value.TryWriteBytes(buffer), Is.False); Assert.IsFalse(value.TryWriteBytes(buffer));
} }
} }

View File

@ -1,66 +1,66 @@
using NUnit.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting;
using X10D.IO; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
[TestFixture] [TestClass]
internal class SingleTests public class SingleTests
{ {
[Test] [TestMethod]
public void GetBigEndianBytes_ReturnsCorrectValue() public void GetBytes_ReturnsCorrectValue()
{ {
const float value = 42.5f; const float value = 42.5f;
byte[] bytes = BitConverter.IsLittleEndian
var expected = new byte[] { 0x42, 0x2A, 0, 0 }; ? new byte[] {0, 0, 0x2A, 0x42}
byte[] actual = value.GetBigEndianBytes(); : new byte[] {0x42, 0x2A, 0, 0};
CollectionAssert.AreEqual(expected, actual); CollectionAssert.AreEqual(bytes, value.GetBytes());
} }
[Test] [TestMethod]
public void GetLittleEndianBytes_ReturnsCorrectValue() public void GetBytes_ReturnsCorrectValue_WithEndianness()
{ {
const float value = 42.5f; const float value = 42.5f;
byte[] littleEndian = {0, 0, 0x2A, 0x42};
byte[] bigEndian = {0x42, 0x2A, 0, 0};
var expected = new byte[] { 0, 0, 0x2A, 0x42 }; CollectionAssert.AreEqual(littleEndian, value.GetBytes(Endianness.LittleEndian));
byte[] actual = value.GetLittleEndianBytes(); CollectionAssert.AreEqual(bigEndian, value.GetBytes(Endianness.BigEndian));
CollectionAssert.AreEqual(expected, actual);
} }
[Test] [TestMethod]
public void TryWriteBigEndian_ReturnsTrue_FillsSpanCorrectly() public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan()
{ {
const float value = 42.5f; const float value = 42.5f;
byte[] bytes = BitConverter.IsLittleEndian
? new byte[] {0, 0, 0x2A, 0x42}
: new byte[] {0x42, 0x2A, 0, 0};
var expected = new byte[] { 0x42, 0x2A, 0, 0 }; Span<byte> buffer = stackalloc byte[4];
Span<byte> actual = stackalloc byte[4]; Assert.IsTrue(value.TryWriteBytes(buffer));
Assert.That(value.TryWriteBigEndian(actual)); CollectionAssert.AreEqual(bytes, buffer.ToArray());
CollectionAssert.AreEqual(expected, actual.ToArray());
} }
[Test] [TestMethod]
public void TryWriteLittleEndian_ReturnsTrue_FillsSpanCorrectly() public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan_WithEndianness()
{ {
const float value = 42.5f; const float value = 42.5f;
byte[] littleEndian = {0, 0, 0x2A, 0x42};
byte[] bigEndian = {0x42, 0x2A, 0, 0};
var expected = new byte[] { 0, 0, 0x2A, 0x42 }; Span<byte> buffer = stackalloc byte[4];
Span<byte> actual = stackalloc byte[4];
Assert.That(value.TryWriteLittleEndian(actual)); Assert.IsTrue(value.TryWriteBytes(buffer, Endianness.LittleEndian));
CollectionAssert.AreEqual(expected, actual.ToArray()); CollectionAssert.AreEqual(littleEndian, buffer.ToArray());
Assert.IsTrue(value.TryWriteBytes(buffer, Endianness.BigEndian));
CollectionAssert.AreEqual(bigEndian, buffer.ToArray());
} }
[Test] [TestMethod]
public void TryWriteBigEndian_ReturnsFalse_GivenSmallSpan() public void TryWriteBytes_ReturnsFalse_GivenSmallSpan()
{ {
const float value = 42.5f; const float value = 42.5f;
Span<byte> buffer = stackalloc byte[0]; Span<byte> buffer = stackalloc byte[0];
Assert.That(value.TryWriteBigEndian(buffer), Is.False); Assert.IsFalse(value.TryWriteBytes(buffer));
}
[Test]
public void TryWriteLittleEndian_RReturnsFalse_GivenSmallSpan()
{
const float value = 42.5f;
Span<byte> buffer = stackalloc byte[0];
Assert.That(value.TryWriteLittleEndian(buffer), Is.False);
} }
} }

View File

@ -1,43 +1,42 @@
using System.Diagnostics.CodeAnalysis; using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;
using X10D.IO; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
internal partial class StreamTests public partial class StreamTests
{ {
[Test] [TestMethod]
public void ReadDecimalBigEndian_ShouldThrowArgumentNullException_GivenNullStream() public void ReadDecimal_ShouldThrowArgumentException_GivenNonReadableStream()
{
Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.ReadDecimalBigEndian());
}
[Test]
public void ReadDecimalLittleEndian_ShouldThrowArgumentNullException_GivenNullStream()
{
Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.ReadDecimalLittleEndian());
}
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void ReadDecimalBigEndian_ShouldThrowArgumentException_GivenNonReadableStream()
{ {
Stream stream = new DummyStream(); Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.ReadDecimalBigEndian()); Assert.ThrowsException<ArgumentException>(() => stream.ReadDecimal());
Assert.ThrowsException<ArgumentException>(() => stream.ReadDecimal(Endianness.LittleEndian));
Assert.ThrowsException<ArgumentException>(() => stream.ReadDecimal(Endianness.BigEndian));
} }
[Test] [TestMethod]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] public void ReadDecimal_ShouldThrowArgumentNullException_GivenNullStream()
public void ReadDecimalLittleEndian_ShouldThrowArgumentException_GivenNonReadableStream()
{ {
Stream stream = new DummyStream(); Stream stream = null!;
Assert.Throws<ArgumentException>(() => stream.ReadDecimalLittleEndian()); Assert.ThrowsException<ArgumentNullException>(() => stream.ReadDecimal());
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadDecimal(Endianness.LittleEndian));
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadDecimal(Endianness.BigEndian));
} }
[Test] [TestMethod]
public void ReadDecimalBigEndian_ShouldReadBigEndian() public void ReadDecimal_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue()
{
// we don't need to enclose this stream in a using declaration, since disposing a
// null stream is meaningless. NullStream.Dispose actually does nothing, anyway.
// 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<ArgumentOutOfRangeException>(() => stream.ReadDecimal((Endianness)(-1)));
}
[TestMethod]
public void ReadDecimal_ShouldReadBigEndian_GivenBigEndian()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
ReadOnlySpan<byte> bytes = stackalloc byte[] ReadOnlySpan<byte> bytes = stackalloc byte[]
@ -48,17 +47,14 @@ internal partial class StreamTests
stream.Position = 0; stream.Position = 0;
const decimal expected = 420.0m; const decimal expected = 420.0m;
decimal actual = stream.ReadDecimalBigEndian(); decimal actual = stream.ReadDecimal(Endianness.BigEndian);
Assert.Multiple(() => Assert.AreEqual(16, stream.Position);
{ Assert.AreEqual(expected, actual);
Assert.That(stream.Position, Is.EqualTo(16));
Assert.That(actual, Is.EqualTo(expected));
});
} }
[Test] [TestMethod]
public void ReadDecimalLittleEndian_ShouldWriteLittleEndian() public void ReadDecimal_ShouldWriteLittleEndian_GivenLittleEndian()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
ReadOnlySpan<byte> bytes = stackalloc byte[] ReadOnlySpan<byte> bytes = stackalloc byte[]
@ -69,12 +65,9 @@ internal partial class StreamTests
stream.Position = 0; stream.Position = 0;
const decimal expected = 420.0m; const decimal expected = 420.0m;
decimal actual = stream.ReadDecimalLittleEndian(); decimal actual = stream.ReadDecimal(Endianness.LittleEndian);
Assert.Multiple(() => Assert.AreEqual(16, stream.Position);
{ Assert.AreEqual(expected, actual);
Assert.That(stream.Position, Is.EqualTo(16));
Assert.That(actual, Is.EqualTo(expected));
});
} }
} }

View File

@ -1,43 +1,42 @@
using System.Diagnostics.CodeAnalysis; using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;
using X10D.IO; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
internal partial class StreamTests public partial class StreamTests
{ {
[Test] [TestMethod]
public void ReadDoubleBigEndian_ShouldThrowArgumentNullException_GivenNullStream() public void ReadDouble_ShouldThrowArgumentException_GivenNonReadableStream()
{
Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.ReadDoubleBigEndian());
}
[Test]
public void ReadDoubleLittleEndian_ShouldThrowArgumentNullException_GivenNullStream()
{
Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.ReadDoubleLittleEndian());
}
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void ReadDoubleBigEndian_ShouldThrowArgumentException_GivenNonReadableStream()
{ {
Stream stream = new DummyStream(); Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.ReadDoubleBigEndian()); Assert.ThrowsException<ArgumentException>(() => stream.ReadDouble());
Assert.ThrowsException<ArgumentException>(() => stream.ReadDouble(Endianness.LittleEndian));
Assert.ThrowsException<ArgumentException>(() => stream.ReadDouble(Endianness.BigEndian));
} }
[Test] [TestMethod]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] public void ReadDouble_ShouldThrowArgumentNullException_GivenNullStream()
public void ReadDoubleLittleEndian_ShouldThrowArgumentException_GivenNonReadableStream()
{ {
Stream stream = new DummyStream(); Stream stream = null!;
Assert.Throws<ArgumentException>(() => stream.ReadDoubleLittleEndian()); Assert.ThrowsException<ArgumentNullException>(() => stream.ReadDouble());
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadDouble(Endianness.LittleEndian));
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadDouble(Endianness.BigEndian));
} }
[Test] [TestMethod]
public void ReadDoubleBigEndian_ShouldReadBigEndian() public void ReadDouble_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue()
{
// we don't need to enclose this stream in a using declaration, since disposing a
// null stream is meaningless. NullStream.Dispose actually does nothing, anyway.
// 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<ArgumentOutOfRangeException>(() => stream.ReadDouble((Endianness)(-1)));
}
[TestMethod]
public void ReadDouble_ShouldReadBigEndian_GivenBigEndian()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
ReadOnlySpan<byte> bytes = stackalloc byte[] {0x40, 0x7A, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00}; ReadOnlySpan<byte> bytes = stackalloc byte[] {0x40, 0x7A, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00};
@ -45,14 +44,14 @@ internal partial class StreamTests
stream.Position = 0; stream.Position = 0;
const double expected = 420.0; const double expected = 420.0;
double actual = stream.ReadDoubleBigEndian(); double actual = stream.ReadDouble(Endianness.BigEndian);
Assert.That(stream.Position, Is.EqualTo(8)); Assert.AreEqual(8, stream.Position);
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
[Test] [TestMethod]
public void ReadDoubleLittleEndian_ShouldWriteLittleEndian() public void ReadDouble_ShouldWriteLittleEndian_GivenLittleEndian()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
ReadOnlySpan<byte> bytes = stackalloc byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x7A, 0x40}; ReadOnlySpan<byte> bytes = stackalloc byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x7A, 0x40};
@ -60,9 +59,9 @@ internal partial class StreamTests
stream.Position = 0; stream.Position = 0;
const double expected = 420.0; const double expected = 420.0;
double actual = stream.ReadDoubleLittleEndian(); double actual = stream.ReadDouble(Endianness.LittleEndian);
Assert.That(stream.Position, Is.EqualTo(8)); Assert.AreEqual(8, stream.Position);
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
} }

View File

@ -1,43 +1,42 @@
using System.Diagnostics.CodeAnalysis; using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;
using X10D.IO; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
internal partial class StreamTests public partial class StreamTests
{ {
[Test] [TestMethod]
public void ReadInt16BigEndian_ShouldThrowArgumentNullException_GivenNullStream() public void ReadInt16_ShouldThrowArgumentException_GivenNonReadableStream()
{
Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.ReadInt16BigEndian());
}
[Test]
public void ReadInt16LittleEndian_ShouldThrowArgumentNullException_GivenNullStream()
{
Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.ReadInt16LittleEndian());
}
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void ReadInt16BigEndian_ShouldThrowArgumentException_GivenNonReadableStream()
{ {
Stream stream = new DummyStream(); Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.ReadInt16BigEndian()); Assert.ThrowsException<ArgumentException>(() => stream.ReadInt16());
Assert.ThrowsException<ArgumentException>(() => stream.ReadInt16(Endianness.LittleEndian));
Assert.ThrowsException<ArgumentException>(() => stream.ReadInt16(Endianness.BigEndian));
} }
[Test] [TestMethod]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] public void ReadInt16_ShouldThrowArgumentNullException_GivenNullStream()
public void ReadInt16LittleEndian_ShouldThrowArgumentException_GivenNonReadableStream()
{ {
Stream stream = new DummyStream(); Stream stream = null!;
Assert.Throws<ArgumentException>(() => stream.ReadInt16LittleEndian()); Assert.ThrowsException<ArgumentNullException>(() => stream.ReadInt16());
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadInt16(Endianness.LittleEndian));
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadInt16(Endianness.BigEndian));
} }
[Test] [TestMethod]
public void ReadInt16BigEndian_ShouldReadBigEndian() public void ReadInt16_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue()
{
// we don't need to enclose this stream in a using declaration, since disposing a
// null stream is meaningless. NullStream.Dispose actually does nothing, anyway.
// 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<ArgumentOutOfRangeException>(() => stream.ReadInt16((Endianness)(-1)));
}
[TestMethod]
public void ReadInt16_ShouldReadBigEndian_GivenBigEndian()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
ReadOnlySpan<byte> bytes = stackalloc byte[] {0x01, 0xA4}; ReadOnlySpan<byte> bytes = stackalloc byte[] {0x01, 0xA4};
@ -45,14 +44,14 @@ internal partial class StreamTests
stream.Position = 0; stream.Position = 0;
const short expected = 420; const short expected = 420;
short actual = stream.ReadInt16BigEndian(); short actual = stream.ReadInt16(Endianness.BigEndian);
Assert.That(stream.Position, Is.EqualTo(2)); Assert.AreEqual(2, stream.Position);
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
[Test] [TestMethod]
public void ReadInt16LittleEndian_ShouldReadLittleEndian() public void ReadInt16_ShouldReadLittleEndian_GivenLittleEndian()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
ReadOnlySpan<byte> bytes = stackalloc byte[] {0xA4, 0x01}; ReadOnlySpan<byte> bytes = stackalloc byte[] {0xA4, 0x01};
@ -60,9 +59,9 @@ internal partial class StreamTests
stream.Position = 0; stream.Position = 0;
const short expected = 420; const short expected = 420;
short actual = stream.ReadInt16LittleEndian(); short actual = stream.ReadInt16(Endianness.LittleEndian);
Assert.That(stream.Position, Is.EqualTo(2)); Assert.AreEqual(2, stream.Position);
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
} }

View File

@ -1,43 +1,42 @@
using System.Diagnostics.CodeAnalysis; using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;
using X10D.IO; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
internal partial class StreamTests public partial class StreamTests
{ {
[Test] [TestMethod]
public void ReadInt32BigEndian_ShouldThrowArgumentNullException_GivenNullStream() public void ReadInt32_ShouldThrowArgumentException_GivenNonReadableStream()
{
Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.ReadInt32BigEndian());
}
[Test]
public void ReadInt32LittleEndian_ShouldThrowArgumentNullException_GivenNullStream()
{
Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.ReadInt32LittleEndian());
}
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void ReadInt32BigEndian_ShouldThrowArgumentException_GivenNonReadableStream()
{ {
Stream stream = new DummyStream(); Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.ReadInt32BigEndian()); Assert.ThrowsException<ArgumentException>(() => stream.ReadInt32());
Assert.ThrowsException<ArgumentException>(() => stream.ReadInt32(Endianness.LittleEndian));
Assert.ThrowsException<ArgumentException>(() => stream.ReadInt32(Endianness.BigEndian));
} }
[Test] [TestMethod]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] public void ReadInt32_ShouldThrowArgumentNullException_GivenNullStream()
public void ReadInt32LittleEndian_ShouldThrowArgumentException_GivenNonReadableStream()
{ {
Stream stream = new DummyStream(); Stream stream = null!;
Assert.Throws<ArgumentException>(() => stream.ReadInt32LittleEndian()); Assert.ThrowsException<ArgumentNullException>(() => stream.ReadInt32());
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadInt32(Endianness.LittleEndian));
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadInt32(Endianness.BigEndian));
} }
[Test] [TestMethod]
public void ReadInt32BigEndian_ShouldReadBigEndian() public void ReadInt32_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue()
{
// we don't need to enclose this stream in a using declaration, since disposing a
// null stream is meaningless. NullStream.Dispose actually does nothing, anyway.
// 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<ArgumentOutOfRangeException>(() => stream.ReadInt32((Endianness)(-1)));
}
[TestMethod]
public void ReadInt32_ShouldReadBigEndian_GivenBigEndian()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
ReadOnlySpan<byte> bytes = stackalloc byte[] {0x00, 0x00, 0x01, 0xA4}; ReadOnlySpan<byte> bytes = stackalloc byte[] {0x00, 0x00, 0x01, 0xA4};
@ -45,14 +44,14 @@ internal partial class StreamTests
stream.Position = 0; stream.Position = 0;
const int expected = 420; const int expected = 420;
int actual = stream.ReadInt32BigEndian(); int actual = stream.ReadInt32(Endianness.BigEndian);
Assert.That(stream.Position, Is.EqualTo(4)); Assert.AreEqual(4, stream.Position);
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
[Test] [TestMethod]
public void ReadInt32LittleEndian_ShouldReadLittleEndian() public void ReadInt32_ShouldReadLittleEndian_GivenLittleEndian()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
ReadOnlySpan<byte> bytes = stackalloc byte[] {0xA4, 0x01, 0x00, 0x00}; ReadOnlySpan<byte> bytes = stackalloc byte[] {0xA4, 0x01, 0x00, 0x00};
@ -60,9 +59,9 @@ internal partial class StreamTests
stream.Position = 0; stream.Position = 0;
const int expected = 420; const int expected = 420;
int actual = stream.ReadInt32LittleEndian(); int actual = stream.ReadInt32(Endianness.LittleEndian);
Assert.That(stream.Position, Is.EqualTo(4)); Assert.AreEqual(4, stream.Position);
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
} }

View File

@ -1,40 +1,42 @@
using NUnit.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting;
using X10D.IO; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
internal partial class StreamTests public partial class StreamTests
{ {
[Test] [TestMethod]
public void ReadInt64BigEndian_ShouldThrowArgumentNullException_GivenNullStream() public void ReadInt64_ShouldThrowArgumentException_GivenNonReadableStream()
{
Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.ReadInt64BigEndian());
}
[Test]
public void ReadInt64LittleEndian_ShouldThrowArgumentNullException_GivenNullStream()
{
Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.ReadInt64LittleEndian());
}
[Test]
public void ReadInt64BigEndian_ShouldThrowArgumentException_GivenNonReadableStream()
{ {
Stream stream = new DummyStream(); Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.ReadInt64BigEndian()); Assert.ThrowsException<ArgumentException>(() => stream.ReadInt64());
Assert.ThrowsException<ArgumentException>(() => stream.ReadInt64(Endianness.LittleEndian));
Assert.ThrowsException<ArgumentException>(() => stream.ReadInt64(Endianness.BigEndian));
} }
[Test] [TestMethod]
public void ReadInt64LittleEndian_ShouldThrowArgumentException_GivenNonReadableStream() public void ReadInt64_ShouldThrowArgumentNullException_GivenNullStream()
{ {
Stream stream = new DummyStream(); Stream stream = null!;
Assert.Throws<ArgumentException>(() => stream.ReadInt64LittleEndian()); Assert.ThrowsException<ArgumentNullException>(() => stream.ReadInt64());
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadInt64(Endianness.LittleEndian));
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadInt64(Endianness.BigEndian));
} }
[Test] [TestMethod]
public void ReadInt64BigEndian_ShouldReadBigEndian() public void ReadInt64_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue()
{
// we don't need to enclose this stream in a using declaration, since disposing a
// null stream is meaningless. NullStream.Dispose actually does nothing, anyway.
// 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<ArgumentOutOfRangeException>(() => stream.ReadInt64((Endianness)(-1)));
}
[TestMethod]
public void ReadInt64_ShouldReadBigEndian_GivenBigEndian()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
ReadOnlySpan<byte> bytes = stackalloc byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xA4}; ReadOnlySpan<byte> bytes = stackalloc byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xA4};
@ -42,14 +44,14 @@ internal partial class StreamTests
stream.Position = 0; stream.Position = 0;
const long expected = 420; const long expected = 420;
long actual = stream.ReadInt64BigEndian(); long actual = stream.ReadInt64(Endianness.BigEndian);
Assert.That(stream.Position, Is.EqualTo(8)); Assert.AreEqual(8, stream.Position);
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
[Test] [TestMethod]
public void ReadInt64LittleEndian_ShouldWriteLittleEndian() public void ReadInt64_ShouldWriteLittleEndian_GivenLittleEndian()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
ReadOnlySpan<byte> bytes = stackalloc byte[] {0xA4, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; ReadOnlySpan<byte> bytes = stackalloc byte[] {0xA4, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
@ -57,9 +59,9 @@ internal partial class StreamTests
stream.Position = 0; stream.Position = 0;
const long expected = 420; const long expected = 420;
long actual = stream.ReadInt64LittleEndian(); long actual = stream.ReadInt64(Endianness.LittleEndian);
Assert.That(stream.Position, Is.EqualTo(8)); Assert.AreEqual(8, stream.Position);
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
} }

View File

@ -1,43 +1,42 @@
using System.Diagnostics.CodeAnalysis; using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;
using X10D.IO; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
internal partial class StreamTests public partial class StreamTests
{ {
[Test] [TestMethod]
public void ReadSingleBigEndian_ShouldThrowArgumentNullException_GivenNullStream() public void ReadSingle_ShouldThrowArgumentException_GivenNonReadableStream()
{
Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.ReadSingleBigEndian());
}
[Test]
public void ReadSingleLittleEndian_ShouldThrowArgumentNullException_GivenNullStream()
{
Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.ReadSingleLittleEndian());
}
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void ReadSingleBigEndian_ShouldThrowArgumentException_GivenNonReadableStream()
{ {
Stream stream = new DummyStream(); Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.ReadSingleBigEndian()); Assert.ThrowsException<ArgumentException>(() => stream.ReadSingle());
Assert.ThrowsException<ArgumentException>(() => stream.ReadSingle(Endianness.LittleEndian));
Assert.ThrowsException<ArgumentException>(() => stream.ReadSingle(Endianness.BigEndian));
} }
[Test] [TestMethod]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] public void ReadSingle_ShouldThrowArgumentNullException_GivenNullStream()
public void ReadSingleLittleEndian_ShouldThrowArgumentException_GivenNonReadableStream()
{ {
Stream stream = new DummyStream(); Stream stream = null!;
Assert.Throws<ArgumentException>(() => stream.ReadSingleLittleEndian()); Assert.ThrowsException<ArgumentNullException>(() => stream.ReadSingle());
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadSingle(Endianness.LittleEndian));
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadSingle(Endianness.BigEndian));
} }
[Test] [TestMethod]
public void ReadSingleBigEndian_ShouldReadBigEndian() public void ReadSingle_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue()
{
// we don't need to enclose this stream in a using declaration, since disposing a
// null stream is meaningless. NullStream.Dispose actually does nothing, anyway.
// 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<ArgumentOutOfRangeException>(() => stream.ReadSingle((Endianness)(-1)));
}
[TestMethod]
public void ReadSingle_ShouldReadBigEndian_GivenBigEndian()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
ReadOnlySpan<byte> bytes = stackalloc byte[] {0x43, 0xD2, 0x00, 0x00}; ReadOnlySpan<byte> bytes = stackalloc byte[] {0x43, 0xD2, 0x00, 0x00};
@ -45,14 +44,14 @@ internal partial class StreamTests
stream.Position = 0; stream.Position = 0;
const float expected = 420.0f; const float expected = 420.0f;
float actual = stream.ReadSingleBigEndian(); float actual = stream.ReadSingle(Endianness.BigEndian);
Assert.That(stream.Position, Is.EqualTo(4)); Assert.AreEqual(4, stream.Position);
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
[Test] [TestMethod]
public void ReadSingleLittleEndian_ShouldReadLittleEndian() public void ReadSingle_ShouldReadLittleEndian_GivenLittleEndian()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
ReadOnlySpan<byte> bytes = stackalloc byte[] {0x00, 0x00, 0xD2, 0x43}; ReadOnlySpan<byte> bytes = stackalloc byte[] {0x00, 0x00, 0xD2, 0x43};
@ -60,9 +59,9 @@ internal partial class StreamTests
stream.Position = 0; stream.Position = 0;
const float expected = 420.0f; const float expected = 420.0f;
float actual = stream.ReadSingleLittleEndian(); float actual = stream.ReadSingle(Endianness.LittleEndian);
Assert.That(stream.Position, Is.EqualTo(4)); Assert.AreEqual(4, stream.Position);
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
} }

View File

@ -1,43 +1,46 @@
using System.Diagnostics.CodeAnalysis; using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;
using X10D.IO; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
internal partial class StreamTests public partial class StreamTests
{ {
[Test] [TestMethod]
public void ReadUInt16BigEndian_ShouldThrowArgumentNullException_GivenNullStream() [CLSCompliant(false)]
{ public void ReadUInt16_ShouldThrowArgumentException_GivenNonReadableStream()
Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.ReadUInt16BigEndian());
}
[Test]
public void ReadUInt16LittleEndian_ShouldThrowArgumentNullException_GivenNullStream()
{
Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.ReadUInt16LittleEndian());
}
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void ReadUInt16BigEndian_ShouldThrowArgumentException_GivenNonReadableStream()
{ {
Stream stream = new DummyStream(); Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.ReadUInt16BigEndian()); Assert.ThrowsException<ArgumentException>(() => stream.ReadUInt16());
Assert.ThrowsException<ArgumentException>(() => stream.ReadUInt16(Endianness.LittleEndian));
Assert.ThrowsException<ArgumentException>(() => stream.ReadUInt16(Endianness.BigEndian));
} }
[Test] [TestMethod]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] [CLSCompliant(false)]
public void ReadUInt16LittleEndian_ShouldThrowArgumentException_GivenNonReadableStream() public void ReadUInt16_ShouldThrowArgumentNullException_GivenNullStream()
{ {
Stream stream = new DummyStream(); Stream stream = null!;
Assert.Throws<ArgumentException>(() => stream.ReadUInt16LittleEndian()); Assert.ThrowsException<ArgumentNullException>(() => stream.ReadUInt16());
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadUInt16(Endianness.LittleEndian));
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadUInt16(Endianness.BigEndian));
} }
[Test] [TestMethod]
public void ReadUInt16BigEndian_ShouldReadBigEndian() [CLSCompliant(false)]
public void ReadUInt16_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue()
{
// we don't need to enclose this stream in a using declaration, since disposing a
// null stream is meaningless. NullStream.Dispose actually does nothing, anyway.
// 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<ArgumentOutOfRangeException>(() => stream.ReadUInt16((Endianness)(-1)));
}
[TestMethod]
[CLSCompliant(false)]
public void ReadUInt16_ShouldReadBigEndian_GivenBigEndian()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
ReadOnlySpan<byte> bytes = stackalloc byte[] {0x01, 0xA4}; ReadOnlySpan<byte> bytes = stackalloc byte[] {0x01, 0xA4};
@ -45,14 +48,15 @@ internal partial class StreamTests
stream.Position = 0; stream.Position = 0;
const ushort expected = 420; const ushort expected = 420;
ushort actual = stream.ReadUInt16BigEndian(); ushort actual = stream.ReadUInt16(Endianness.BigEndian);
Assert.That(stream.Position, Is.EqualTo(2)); Assert.AreEqual(2, stream.Position);
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
[Test] [TestMethod]
public void ReadUInt16LittleEndian_ShouldReadLittleEndian() [CLSCompliant(false)]
public void ReadUInt16_ShouldReadLittleEndian_GivenLittleEndian()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
ReadOnlySpan<byte> bytes = stackalloc byte[] {0xA4, 0x01}; ReadOnlySpan<byte> bytes = stackalloc byte[] {0xA4, 0x01};
@ -60,9 +64,9 @@ internal partial class StreamTests
stream.Position = 0; stream.Position = 0;
const ushort expected = 420; const ushort expected = 420;
ushort actual = stream.ReadUInt16LittleEndian(); ushort actual = stream.ReadUInt16(Endianness.LittleEndian);
Assert.That(stream.Position, Is.EqualTo(2)); Assert.AreEqual(2, stream.Position);
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
} }

View File

@ -1,43 +1,46 @@
using System.Diagnostics.CodeAnalysis; using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;
using X10D.IO; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
internal partial class StreamTests public partial class StreamTests
{ {
[Test] [TestMethod]
public void ReadUInt32BigEndian_ShouldThrowArgumentNullException_GivenNullStream() [CLSCompliant(false)]
{ public void ReadUInt32_ShouldThrowArgumentException_GivenNonReadableStream()
Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.ReadUInt32BigEndian());
}
[Test]
public void ReadUInt32LittleEndian_ShouldThrowArgumentNullException_GivenNullStream()
{
Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.ReadUInt32LittleEndian());
}
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void ReadUInt32BigEndian_ShouldThrowArgumentException_GivenNonReadableStream()
{ {
Stream stream = new DummyStream(); Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.ReadUInt32BigEndian()); Assert.ThrowsException<ArgumentException>(() => stream.ReadUInt32());
Assert.ThrowsException<ArgumentException>(() => stream.ReadUInt32(Endianness.LittleEndian));
Assert.ThrowsException<ArgumentException>(() => stream.ReadUInt32(Endianness.BigEndian));
} }
[Test] [TestMethod]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] [CLSCompliant(false)]
public void ReadUInt32LittleEndian_ShouldThrowArgumentException_GivenNonReadableStream() public void ReadUInt32_ShouldThrowArgumentNullException_GivenNullStream()
{ {
Stream stream = new DummyStream(); Stream stream = null!;
Assert.Throws<ArgumentException>(() => stream.ReadUInt32LittleEndian()); Assert.ThrowsException<ArgumentNullException>(() => stream.ReadUInt32());
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadUInt32(Endianness.LittleEndian));
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadUInt32(Endianness.BigEndian));
} }
[Test] [TestMethod]
public void ReadUInt32BigEndian_ShouldReadBigEndian() [CLSCompliant(false)]
public void ReadUInt32_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue()
{
// we don't need to enclose this stream in a using declaration, since disposing a
// null stream is meaningless. NullStream.Dispose actually does nothing, anyway.
// 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<ArgumentOutOfRangeException>(() => stream.ReadUInt32((Endianness)(-1)));
}
[TestMethod]
[CLSCompliant(false)]
public void ReadUInt32_ShouldReadBigEndian_GivenBigEndian()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
ReadOnlySpan<byte> bytes = stackalloc byte[] {0x00, 0x00, 0x01, 0xA4}; ReadOnlySpan<byte> bytes = stackalloc byte[] {0x00, 0x00, 0x01, 0xA4};
@ -45,14 +48,15 @@ internal partial class StreamTests
stream.Position = 0; stream.Position = 0;
const uint expected = 420; const uint expected = 420;
uint actual = stream.ReadUInt32BigEndian(); uint actual = stream.ReadUInt32(Endianness.BigEndian);
Assert.That(stream.Position, Is.EqualTo(4)); Assert.AreEqual(4, stream.Position);
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
[Test] [TestMethod]
public void ReadUInt32LittleEndian_ShouldReadLittleEndian() [CLSCompliant(false)]
public void ReadUInt32_ShouldReadLittleEndian_GivenLittleEndian()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
ReadOnlySpan<byte> bytes = stackalloc byte[] {0xA4, 0x01, 0x00, 0x00}; ReadOnlySpan<byte> bytes = stackalloc byte[] {0xA4, 0x01, 0x00, 0x00};
@ -60,9 +64,9 @@ internal partial class StreamTests
stream.Position = 0; stream.Position = 0;
const uint expected = 420; const uint expected = 420;
uint actual = stream.ReadUInt32LittleEndian(); uint actual = stream.ReadUInt32(Endianness.LittleEndian);
Assert.That(stream.Position, Is.EqualTo(4)); Assert.AreEqual(4, stream.Position);
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
} }

View File

@ -1,43 +1,46 @@
using System.Diagnostics.CodeAnalysis; using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;
using X10D.IO; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
internal partial class StreamTests public partial class StreamTests
{ {
[Test] [TestMethod]
public void ReadUInt64BigEndian_ShouldThrowArgumentNullException_GivenNullStream() [CLSCompliant(false)]
{ public void ReadUInt64_ShouldThrowArgumentException_GivenNonReadableStream()
Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.ReadUInt64BigEndian());
}
[Test]
public void ReadUInt64LittleEndian_ShouldThrowArgumentNullException_GivenNullStream()
{
Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.ReadUInt64LittleEndian());
}
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void ReadUInt64BigEndian_ShouldThrowArgumentException_GivenNonReadableStream()
{ {
Stream stream = new DummyStream(); Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.ReadUInt64BigEndian()); Assert.ThrowsException<ArgumentException>(() => stream.ReadUInt64());
Assert.ThrowsException<ArgumentException>(() => stream.ReadUInt64(Endianness.LittleEndian));
Assert.ThrowsException<ArgumentException>(() => stream.ReadUInt64(Endianness.BigEndian));
} }
[Test] [TestMethod]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] [CLSCompliant(false)]
public void ReadUInt64LittleEndian_ShouldThrowArgumentException_GivenNonReadableStream() public void ReadUInt64_ShouldThrowArgumentNullException_GivenNullStream()
{ {
Stream stream = new DummyStream(); Stream stream = null!;
Assert.Throws<ArgumentException>(() => stream.ReadUInt64LittleEndian()); Assert.ThrowsException<ArgumentNullException>(() => stream.ReadUInt64());
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadUInt64(Endianness.LittleEndian));
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadUInt64(Endianness.BigEndian));
} }
[Test] [TestMethod]
public void ReadUInt64BigEndian_ShouldReadBigEndian() [CLSCompliant(false)]
public void ReadUInt64_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue()
{
// we don't need to enclose this stream in a using declaration, since disposing a
// null stream is meaningless. NullStream.Dispose actually does nothing, anyway.
// 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<ArgumentOutOfRangeException>(() => stream.ReadUInt64((Endianness)(-1)));
}
[TestMethod]
[CLSCompliant(false)]
public void ReadUInt64_ShouldReadBigEndian_GivenBigEndian()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
ReadOnlySpan<byte> bytes = stackalloc byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xA4}; ReadOnlySpan<byte> bytes = stackalloc byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xA4};
@ -45,14 +48,15 @@ internal partial class StreamTests
stream.Position = 0; stream.Position = 0;
const ulong expected = 420; const ulong expected = 420;
ulong actual = stream.ReadUInt64BigEndian(); ulong actual = stream.ReadUInt64(Endianness.BigEndian);
Assert.That(stream.Position, Is.EqualTo(8)); Assert.AreEqual(8, stream.Position);
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
[Test] [TestMethod]
public void ReadUInt64LittleEndian_ShouldWriteLittleEndian() [CLSCompliant(false)]
public void ReadUInt64_ShouldWriteLittleEndian_GivenLittleEndian()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
ReadOnlySpan<byte> bytes = stackalloc byte[] {0xA4, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; ReadOnlySpan<byte> bytes = stackalloc byte[] {0xA4, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
@ -60,9 +64,9 @@ internal partial class StreamTests
stream.Position = 0; stream.Position = 0;
const ulong expected = 420; const ulong expected = 420;
ulong actual = stream.ReadUInt64LittleEndian(); ulong actual = stream.ReadUInt64(Endianness.LittleEndian);
Assert.That(stream.Position, Is.EqualTo(8)); Assert.AreEqual(8, stream.Position);
Assert.That(actual, Is.EqualTo(expected)); Assert.AreEqual(expected, actual);
} }
} }

View File

@ -1,67 +1,65 @@
using System.Diagnostics; using System.Diagnostics;
using System.Diagnostics.CodeAnalysis; using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;
using X10D.IO; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
internal partial class StreamTests public partial class StreamTests
{ {
[Test] [TestMethod]
public void WriteBigEndian_ShouldThrowArgumentNullException_GivenNullStream_AndDecimalArgument() public void WriteDecimal_ShouldThrowArgumentException_GivenNonWriteableStream()
{
Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.WriteBigEndian(420.0m));
}
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void WriteBigEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndDecimalArgument()
{ {
Stream stream = new DummyStream(); Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.WriteBigEndian(420.0m)); Assert.ThrowsException<ArgumentException>(() => stream.Write(420.0m, Endianness.LittleEndian));
Assert.ThrowsException<ArgumentException>(() => stream.Write(420.0m, Endianness.BigEndian));
} }
[Test] [TestMethod]
public void WriteLittleEndian_ShouldThrowArgumentNullException_GivenNullStream_AndDecimalArgument() public void WriteDecimal_ShouldThrowArgumentNullException_GivenNullStream()
{ {
Stream stream = null!; Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.WriteLittleEndian(420.0m)); Assert.ThrowsException<ArgumentNullException>(() => stream.Write(420.0m, Endianness.LittleEndian));
Assert.ThrowsException<ArgumentNullException>(() => stream.Write(420.0m, Endianness.BigEndian));
} }
[Test] [TestMethod]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] public void WriteDecimal_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue()
public void WriteLittleEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndDecimalArgument()
{ {
Stream stream = new DummyStream(); // we don't need to enclose this stream in a using declaration, since disposing a
Assert.Throws<ArgumentException>(() => stream.WriteLittleEndian(420.0m)); // 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<ArgumentOutOfRangeException>(() => stream.Write(420.0m, (Endianness)(-1)));
Assert.ThrowsException<ArgumentOutOfRangeException>(() => stream.Write(420.0m, (Endianness)(-1)));
} }
[Test] [TestMethod]
public void WriteBigEndian_ShouldWriteBigEndian_GivenDecimalArgument() public void WriteDecimal_ShouldWriteBigEndian_GivenBigEndian()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
stream.WriteBigEndian(420.0m); stream.Write(420.0m, Endianness.BigEndian);
Assert.That(stream.Position, Is.EqualTo(16)); Assert.AreEqual(16, stream.Position);
stream.Position = 0; stream.Position = 0;
Span<byte> actual = stackalloc byte[16]; Span<byte> actual = stackalloc byte[16];
ReadOnlySpan<byte> expected = stackalloc byte[] ReadOnlySpan<byte> expected = stackalloc byte[]
{ {
0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x68, 0x10, 0x00, 0x00 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x68
}; };
int read = stream.Read(actual); int read = stream.Read(actual);
Assert.That(read, Is.EqualTo(16)); Assert.AreEqual(16, read);
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
} }
[Test] [TestMethod]
public void WriteLittleEndian_ShouldWriteLittleEndian_GivenDecimalArgument() public void WriteDecimal_ShouldWriteLittleEndian_GivenLittleEndian()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
stream.WriteLittleEndian(420.0m); stream.Write(420.0m, Endianness.LittleEndian);
Assert.That(stream.Position, Is.EqualTo(16)); Assert.AreEqual(16, stream.Position);
stream.Position = 0; stream.Position = 0;
Span<byte> actual = stackalloc byte[16]; Span<byte> actual = stackalloc byte[16];
@ -73,7 +71,7 @@ internal partial class StreamTests
Trace.WriteLine(string.Join(", ", actual.ToArray().Select(b => $"0x{b:X2}"))); Trace.WriteLine(string.Join(", ", actual.ToArray().Select(b => $"0x{b:X2}")));
Assert.That(read, Is.EqualTo(16)); Assert.AreEqual(16, read);
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
} }
} }

View File

@ -1,70 +1,68 @@
using System.Diagnostics.CodeAnalysis; using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;
using X10D.IO; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
internal partial class StreamTests public partial class StreamTests
{ {
[Test] [TestMethod]
public void WriteBigEndian_ShouldThrowArgumentNullException_GivenNullStream_AndDoubleArgument() public void WriteDouble_ShouldThrowArgumentException_GivenNonWriteableStream()
{
Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.WriteBigEndian(420.0));
}
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void WriteBigEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndDoubleArgument()
{ {
Stream stream = new DummyStream(); Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.WriteBigEndian(420.0)); Assert.ThrowsException<ArgumentException>(() => stream.Write(420.0, Endianness.LittleEndian));
Assert.ThrowsException<ArgumentException>(() => stream.Write(420.0, Endianness.BigEndian));
} }
[Test] [TestMethod]
public void WriteLittleEndian_ShouldThrowArgumentNullException_GivenNullStream_AndDoubleArgument() public void WriteDouble_ShouldThrowArgumentNullException_GivenNullStream()
{ {
Stream stream = null!; Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.WriteLittleEndian(420.0)); Assert.ThrowsException<ArgumentNullException>(() => stream.Write(420.0, Endianness.LittleEndian));
Assert.ThrowsException<ArgumentNullException>(() => stream.Write(420.0, Endianness.BigEndian));
} }
[Test] [TestMethod]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] public void WriteDouble_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue()
public void WriteLittleEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndDoubleArgument()
{ {
Stream stream = new DummyStream(); // we don't need to enclose this stream in a using declaration, since disposing a
Assert.Throws<ArgumentException>(() => stream.WriteLittleEndian(420.0)); // 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<ArgumentOutOfRangeException>(() => stream.Write(420.0, (Endianness)(-1)));
Assert.ThrowsException<ArgumentOutOfRangeException>(() => stream.Write(420.0, (Endianness)(-1)));
} }
[Test] [TestMethod]
public void WriteBigEndian_ShouldWriteBigEndian_GivenDoubleArgument() public void WriteDouble_ShouldWriteBigEndian_GivenBigEndian()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
stream.WriteBigEndian(420.0); stream.Write(420.0, Endianness.BigEndian);
Assert.That(stream.Position, Is.EqualTo(8)); Assert.AreEqual(8, stream.Position);
stream.Position = 0; stream.Position = 0;
Span<byte> actual = stackalloc byte[8]; Span<byte> actual = stackalloc byte[8];
ReadOnlySpan<byte> expected = stackalloc byte[] {0x40, 0x7A, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00}; ReadOnlySpan<byte> expected = stackalloc byte[] {0x40, 0x7A, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00};
int read = stream.Read(actual); int read = stream.Read(actual);
Assert.That(read, Is.EqualTo(8)); Assert.AreEqual(8, read);
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
} }
[Test] [TestMethod]
public void WriteLittleEndian_ShouldWriteLittleEndian_GivenDoubleArgument() public void WriteDouble_ShouldWriteLittleEndian_GivenLittleEndian()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
stream.WriteLittleEndian(420.0); stream.Write(420.0, Endianness.LittleEndian);
Assert.That(stream.Position, Is.EqualTo(8)); Assert.AreEqual(8, stream.Position);
stream.Position = 0; stream.Position = 0;
Span<byte> actual = stackalloc byte[8]; Span<byte> actual = stackalloc byte[8];
ReadOnlySpan<byte> expected = stackalloc byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x7A, 0x40}; ReadOnlySpan<byte> expected = stackalloc byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x7A, 0x40};
int read = stream.Read(actual); int read = stream.Read(actual);
Assert.That(read, Is.EqualTo(8)); Assert.AreEqual(8, read);
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
} }
} }

View File

@ -1,70 +1,68 @@
using System.Diagnostics.CodeAnalysis; using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;
using X10D.IO; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
internal partial class StreamTests public partial class StreamTests
{ {
[Test] [TestMethod]
public void WriteBigEndian_ShouldThrowArgumentNullException_GivenNullStream_AndInt16Argument() public void WriteInt16_ShouldThrowArgumentException_GivenNonWriteableStream()
{
Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.WriteBigEndian((short)420));
}
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void WriteBigEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndInt16Argument()
{ {
Stream stream = new DummyStream(); Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.WriteBigEndian((short)420)); Assert.ThrowsException<ArgumentException>(() => stream.Write((short)420, Endianness.LittleEndian));
Assert.ThrowsException<ArgumentException>(() => stream.Write((short)420, Endianness.BigEndian));
} }
[Test] [TestMethod]
public void WriteLittleEndian_ShouldThrowArgumentNullException_GivenNullStream_AndInt16Argument() public void WriteInt16_ShouldThrowArgumentNullException_GivenNullStream()
{ {
Stream stream = null!; Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.WriteLittleEndian((short)420)); Assert.ThrowsException<ArgumentNullException>(() => stream.Write((short)420, Endianness.LittleEndian));
Assert.ThrowsException<ArgumentNullException>(() => stream.Write((short)420, Endianness.BigEndian));
} }
[Test] [TestMethod]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] public void WriteInt16_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue()
public void WriteLittleEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndInt16Argument()
{ {
Stream stream = new DummyStream(); // we don't need to enclose this stream in a using declaration, since disposing a
Assert.Throws<ArgumentException>(() => stream.WriteLittleEndian((short)420)); // 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<ArgumentOutOfRangeException>(() => stream.Write((short)420, (Endianness)(-1)));
Assert.ThrowsException<ArgumentOutOfRangeException>(() => stream.Write((short)420, (Endianness)(-1)));
} }
[Test] [TestMethod]
public void WriteBigEndian_ShouldWriteBigEndian_GivenInt16Argument() public void WriteInt16_ShouldWriteBigEndian_GivenBigEndian()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
stream.WriteBigEndian((short)420); stream.Write((short)420, Endianness.BigEndian);
Assert.That(stream.Position, Is.EqualTo(2)); Assert.AreEqual(2, stream.Position);
stream.Position = 0; stream.Position = 0;
Span<byte> actual = stackalloc byte[2]; Span<byte> actual = stackalloc byte[2];
ReadOnlySpan<byte> expected = stackalloc byte[] {0x01, 0xA4}; ReadOnlySpan<byte> expected = stackalloc byte[] {0x01, 0xA4};
int read = stream.Read(actual); int read = stream.Read(actual);
Assert.That(read, Is.EqualTo(2)); Assert.AreEqual(2, read);
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
} }
[Test] [TestMethod]
public void WriteLittleEndian_ShouldWriteLittleEndian_GivenInt16Argument() public void WriteInt16_ShouldWriteLittleEndian_GivenLittleEndian()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
stream.WriteLittleEndian((short)420); stream.Write((short)420, Endianness.LittleEndian);
Assert.That(stream.Position, Is.EqualTo(2)); Assert.AreEqual(2, stream.Position);
stream.Position = 0; stream.Position = 0;
Span<byte> actual = stackalloc byte[2]; Span<byte> actual = stackalloc byte[2];
ReadOnlySpan<byte> expected = stackalloc byte[] {0xA4, 0x01}; ReadOnlySpan<byte> expected = stackalloc byte[] {0xA4, 0x01};
int read = stream.Read(actual); int read = stream.Read(actual);
Assert.That(read, Is.EqualTo(2)); Assert.AreEqual(2, read);
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
} }
} }

View File

@ -1,70 +1,68 @@
using System.Diagnostics.CodeAnalysis; using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;
using X10D.IO; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
internal partial class StreamTests public partial class StreamTests
{ {
[Test] [TestMethod]
public void WriteBigEndian_ShouldThrowArgumentNullException_GivenNullStream_AndInt32Argument() public void WriteInt32_ShouldThrowArgumentException_GivenNonWriteableStream()
{
Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.WriteBigEndian(420));
}
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void WriteBigEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndInt32Argument()
{ {
Stream stream = new DummyStream(); Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.WriteBigEndian(420)); Assert.ThrowsException<ArgumentException>(() => stream.Write(420, Endianness.LittleEndian));
Assert.ThrowsException<ArgumentException>(() => stream.Write(420, Endianness.BigEndian));
} }
[Test] [TestMethod]
public void WriteLittleEndian_ShouldThrowArgumentNullException_GivenNullStream_AndInt32Argument() public void WriteInt32_ShouldThrowArgumentNullException_GivenNullStream()
{ {
Stream stream = null!; Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.WriteLittleEndian(420)); Assert.ThrowsException<ArgumentNullException>(() => stream.Write(420, Endianness.LittleEndian));
Assert.ThrowsException<ArgumentNullException>(() => stream.Write(420, Endianness.BigEndian));
} }
[Test] [TestMethod]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] public void WriteInt32_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue()
public void WriteLittleEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndInt32Argument()
{ {
Stream stream = new DummyStream(); // we don't need to enclose this stream in a using declaration, since disposing a
Assert.Throws<ArgumentException>(() => stream.WriteLittleEndian(420)); // 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<ArgumentOutOfRangeException>(() => stream.Write(420, (Endianness)(-1)));
Assert.ThrowsException<ArgumentOutOfRangeException>(() => stream.Write(420, (Endianness)(-1)));
} }
[Test] [TestMethod]
public void WriteBigEndian_ShouldWriteBigEndian_GivenInt32Argument() public void WriteInt32_ShouldWriteBigEndian_GivenBigEndian()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
stream.WriteBigEndian(420); stream.Write(420, Endianness.BigEndian);
Assert.That(stream.Position, Is.EqualTo(4)); Assert.AreEqual(4, stream.Position);
stream.Position = 0; stream.Position = 0;
Span<byte> actual = stackalloc byte[4]; Span<byte> actual = stackalloc byte[4];
ReadOnlySpan<byte> expected = stackalloc byte[] {0x00, 0x00, 0x01, 0xA4}; ReadOnlySpan<byte> expected = stackalloc byte[] {0x00, 0x00, 0x01, 0xA4};
int read = stream.Read(actual); int read = stream.Read(actual);
Assert.That(read, Is.EqualTo(4)); Assert.AreEqual(4, read);
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
} }
[Test] [TestMethod]
public void WriteLittleEndian_ShouldWriteLittleEndian_GivenInt32Argument() public void WriteInt32_ShouldWriteLittleEndian_GivenLittleEndian()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
stream.WriteLittleEndian(420); stream.Write(420, Endianness.LittleEndian);
Assert.That(stream.Position, Is.EqualTo(4)); Assert.AreEqual(4, stream.Position);
stream.Position = 0; stream.Position = 0;
Span<byte> actual = stackalloc byte[4]; Span<byte> actual = stackalloc byte[4];
ReadOnlySpan<byte> expected = stackalloc byte[] {0xA4, 0x01, 0x00, 0x00}; ReadOnlySpan<byte> expected = stackalloc byte[] {0xA4, 0x01, 0x00, 0x00};
int read = stream.Read(actual); int read = stream.Read(actual);
Assert.That(read, Is.EqualTo(4)); Assert.AreEqual(4, read);
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
} }
} }

View File

@ -1,70 +1,68 @@
using System.Diagnostics.CodeAnalysis; using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;
using X10D.IO; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
internal partial class StreamTests public partial class StreamTests
{ {
[Test] [TestMethod]
public void WriteBigEndian_ShouldThrowArgumentNullException_GivenNullStream_AndInt64Argument() public void WriteInt64_ShouldThrowArgumentException_GivenNonWriteableStream()
{
Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.WriteBigEndian(420L));
}
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void WriteBigEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndInt64Argument()
{ {
Stream stream = new DummyStream(); Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.WriteBigEndian(420L)); Assert.ThrowsException<ArgumentException>(() => stream.Write(420L, Endianness.LittleEndian));
Assert.ThrowsException<ArgumentException>(() => stream.Write(420L, Endianness.BigEndian));
} }
[Test] [TestMethod]
public void WriteLittleEndian_ShouldThrowArgumentNullException_GivenNullStream_AndInt64Argument() public void WriteInt64_ShouldThrowArgumentNullException_GivenNullStream()
{ {
Stream stream = null!; Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.WriteLittleEndian(420L)); Assert.ThrowsException<ArgumentNullException>(() => stream.Write(420L, Endianness.LittleEndian));
Assert.ThrowsException<ArgumentNullException>(() => stream.Write(420L, Endianness.BigEndian));
} }
[Test] [TestMethod]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] public void WriteInt64_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue()
public void WriteLittleEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndInt64Argument()
{ {
Stream stream = new DummyStream(); // we don't need to enclose this stream in a using declaration, since disposing a
Assert.Throws<ArgumentException>(() => stream.WriteLittleEndian(420L)); // 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<ArgumentOutOfRangeException>(() => stream.Write(420L, (Endianness)(-1)));
Assert.ThrowsException<ArgumentOutOfRangeException>(() => stream.Write(420L, (Endianness)(-1)));
} }
[Test] [TestMethod]
public void WriteBigEndian_ShouldWriteBigEndian_GivenInt64Argument() public void WriteInt64_ShouldWriteBigEndian_GivenBigEndian()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
stream.WriteBigEndian(420L); stream.Write(420L, Endianness.BigEndian);
Assert.That(stream.Position, Is.EqualTo(8)); Assert.AreEqual(8, stream.Position);
stream.Position = 0; stream.Position = 0;
Span<byte> actual = stackalloc byte[8]; Span<byte> actual = stackalloc byte[8];
ReadOnlySpan<byte> expected = stackalloc byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xA4}; ReadOnlySpan<byte> expected = stackalloc byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xA4};
int read = stream.Read(actual); int read = stream.Read(actual);
Assert.That(read, Is.EqualTo(8)); Assert.AreEqual(8, read);
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
} }
[Test] [TestMethod]
public void WriteLittleEndian_ShouldWriteLittleEndian_GivenLittleEndian() public void WriteInt64_ShouldWriteLittleEndian_GivenLittleEndian()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
stream.WriteLittleEndian(420L); stream.Write(420L, Endianness.LittleEndian);
Assert.That(stream.Position, Is.EqualTo(8)); Assert.AreEqual(8, stream.Position);
stream.Position = 0; stream.Position = 0;
Span<byte> actual = stackalloc byte[8]; Span<byte> actual = stackalloc byte[8];
ReadOnlySpan<byte> expected = stackalloc byte[] {0xA4, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; ReadOnlySpan<byte> expected = stackalloc byte[] {0xA4, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
int read = stream.Read(actual); int read = stream.Read(actual);
Assert.That(read, Is.EqualTo(8)); Assert.AreEqual(8, read);
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
} }
} }

View File

@ -1,70 +1,68 @@
using System.Diagnostics.CodeAnalysis; using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;
using X10D.IO; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
internal partial class StreamTests public partial class StreamTests
{ {
[Test] [TestMethod]
public void WriteBigEndian_ShouldThrowArgumentNullException_GivenNullStream_AndSingleArgument() public void WriteSingle_ShouldThrowArgumentException_GivenNonWriteableStream()
{
Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.WriteBigEndian(420.0f));
}
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void WriteBigEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndSingleArgument()
{ {
Stream stream = new DummyStream(); Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.WriteBigEndian(420.0f)); Assert.ThrowsException<ArgumentException>(() => stream.Write(420.0f, Endianness.LittleEndian));
Assert.ThrowsException<ArgumentException>(() => stream.Write(420.0f, Endianness.BigEndian));
} }
[Test] [TestMethod]
public void WriteLittleEndian_ShouldThrowArgumentNullException_GivenNullStream_AndSingleArgument() public void WriteSingle_ShouldThrowArgumentNullException_GivenNullStream()
{ {
Stream stream = null!; Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.WriteLittleEndian(420.0f)); Assert.ThrowsException<ArgumentNullException>(() => stream.Write(420.0f, Endianness.LittleEndian));
Assert.ThrowsException<ArgumentNullException>(() => stream.Write(420.0f, Endianness.BigEndian));
} }
[Test] [TestMethod]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] public void WriteSingle_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue()
public void WriteLittleEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndSingleArgument()
{ {
Stream stream = new DummyStream(); // we don't need to enclose this stream in a using declaration, since disposing a
Assert.Throws<ArgumentException>(() => stream.WriteLittleEndian(420.0f)); // 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<ArgumentOutOfRangeException>(() => stream.Write(420.0f, (Endianness)(-1)));
Assert.ThrowsException<ArgumentOutOfRangeException>(() => stream.Write(420.0f, (Endianness)(-1)));
} }
[Test] [TestMethod]
public void WriteBigEndian_ShouldWriteBigEndian_GivenSingleArgument() public void WriteSingle_ShouldWriteBigEndian_GivenBigEndian()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
stream.WriteBigEndian(420.0f); stream.Write(420.0f, Endianness.BigEndian);
Assert.That(stream.Position, Is.EqualTo(4)); Assert.AreEqual(4, stream.Position);
stream.Position = 0; stream.Position = 0;
Span<byte> actual = stackalloc byte[4]; Span<byte> actual = stackalloc byte[4];
ReadOnlySpan<byte> expected = stackalloc byte[] {0x43, 0xD2, 0x00, 0x00}; ReadOnlySpan<byte> expected = stackalloc byte[] {0x43, 0xD2, 0x00, 0x00};
int read = stream.Read(actual); int read = stream.Read(actual);
Assert.That(read, Is.EqualTo(4)); Assert.AreEqual(4, read);
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
} }
[Test] [TestMethod]
public void WriteLittleEndian_ShouldWriteLittleEndian_GivenSingleArgument() public void WriteSingle_ShouldWriteLittleEndian_GivenLittleEndian()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
stream.WriteLittleEndian(420.0f); stream.Write(420.0f, Endianness.LittleEndian);
Assert.That(stream.Position, Is.EqualTo(4)); Assert.AreEqual(4, stream.Position);
stream.Position = 0; stream.Position = 0;
Span<byte> actual = stackalloc byte[4]; Span<byte> actual = stackalloc byte[4];
ReadOnlySpan<byte> expected = stackalloc byte[] {0x00, 0x00, 0xD2, 0x43}; ReadOnlySpan<byte> expected = stackalloc byte[] {0x00, 0x00, 0xD2, 0x43};
int read = stream.Read(actual); int read = stream.Read(actual);
Assert.That(read, Is.EqualTo(4)); Assert.AreEqual(4, read);
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
} }
} }

View File

@ -1,70 +1,73 @@
using System.Diagnostics.CodeAnalysis; using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;
using X10D.IO; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
internal partial class StreamTests public partial class StreamTests
{ {
[Test] [TestMethod]
public void WriteBigEndian_ShouldThrowArgumentNullException_GivenNullStream_AndUInt16Argument() [CLSCompliant(false)]
{ public void WriteUInt16_ShouldThrowArgumentException_GivenNonWriteableStream()
Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.WriteBigEndian((ushort)420));
}
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void WriteBigEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndUInt16Argument()
{ {
Stream stream = new DummyStream(); Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.WriteBigEndian((ushort)420)); Assert.ThrowsException<ArgumentException>(() => stream.Write((ushort)420, Endianness.LittleEndian));
Assert.ThrowsException<ArgumentException>(() => stream.Write((ushort)420, Endianness.BigEndian));
} }
[Test] [TestMethod]
public void WriteLittleEndian_ShouldThrowArgumentNullException_GivenNullStream_AndUInt16Argument() [CLSCompliant(false)]
public void WriteUInt16_ShouldThrowArgumentNullException_GivenNullStream()
{ {
Stream stream = null!; Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.WriteLittleEndian((ushort)420)); Assert.ThrowsException<ArgumentNullException>(() => stream.Write((ushort)420, Endianness.LittleEndian));
Assert.ThrowsException<ArgumentNullException>(() => stream.Write((ushort)420, Endianness.BigEndian));
} }
[Test] [TestMethod]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] [CLSCompliant(false)]
public void WriteLittleEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndUInt16Argument() public void WriteUInt16_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue()
{ {
Stream stream = new DummyStream(); // we don't need to enclose this stream in a using declaration, since disposing a
Assert.Throws<ArgumentException>(() => stream.WriteLittleEndian((ushort)420)); // 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<ArgumentOutOfRangeException>(() => stream.Write((ushort)420, (Endianness)(-1)));
Assert.ThrowsException<ArgumentOutOfRangeException>(() => stream.Write((ushort)420, (Endianness)(-1)));
} }
[Test] [TestMethod]
public void WriteBigEndian_ShouldWriteBigEndian_GivenUInt16Endian() [CLSCompliant(false)]
public void WriteUInt16_ShouldWriteBigEndian_GivenBigEndian()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
stream.WriteBigEndian((ushort)420); stream.Write((ushort)420, Endianness.BigEndian);
Assert.That(stream.Position, Is.EqualTo(2)); Assert.AreEqual(2, stream.Position);
stream.Position = 0; stream.Position = 0;
Span<byte> actual = stackalloc byte[2]; Span<byte> actual = stackalloc byte[2];
ReadOnlySpan<byte> expected = stackalloc byte[] {0x01, 0xA4}; ReadOnlySpan<byte> expected = stackalloc byte[] {0x01, 0xA4};
int read = stream.Read(actual); int read = stream.Read(actual);
Assert.That(read, Is.EqualTo(2)); Assert.AreEqual(2, read);
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
} }
[Test] [TestMethod]
public void WriteLittleEndian_ShouldWriteLittleEndian_GivenUInt16tleEndian() [CLSCompliant(false)]
public void WriteUInt16_ShouldWriteLittleEndian_GivenLittleEndian()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
stream.WriteLittleEndian((ushort)420); stream.Write((ushort)420, Endianness.LittleEndian);
Assert.That(stream.Position, Is.EqualTo(2)); Assert.AreEqual(2, stream.Position);
stream.Position = 0; stream.Position = 0;
Span<byte> actual = stackalloc byte[2]; Span<byte> actual = stackalloc byte[2];
ReadOnlySpan<byte> expected = stackalloc byte[] {0xA4, 0x01}; ReadOnlySpan<byte> expected = stackalloc byte[] {0xA4, 0x01};
int read = stream.Read(actual); int read = stream.Read(actual);
Assert.That(read, Is.EqualTo(2)); Assert.AreEqual(2, read);
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
} }
} }

View File

@ -1,70 +1,73 @@
using System.Diagnostics.CodeAnalysis; using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;
using X10D.IO; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
internal partial class StreamTests public partial class StreamTests
{ {
[Test] [TestMethod]
public void WriteBigEndian_ShouldThrowArgumentNullException_GivenNullStream_AndUInt32Argument() [CLSCompliant(false)]
{ public void WriteUInt32_ShouldThrowArgumentException_GivenNonWriteableStream()
Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.WriteBigEndian(420U));
}
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void WriteBigEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndUInt32Argument()
{ {
Stream stream = new DummyStream(); Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.WriteBigEndian(420U)); Assert.ThrowsException<ArgumentException>(() => stream.Write(420U, Endianness.LittleEndian));
Assert.ThrowsException<ArgumentException>(() => stream.Write(420U, Endianness.BigEndian));
} }
[Test] [TestMethod]
public void WriteLittleEndian_ShouldThrowArgumentNullException_GivenNullStream_AndUInt32Argument() [CLSCompliant(false)]
public void WriteUInt32_ShouldThrowArgumentNullException_GivenNullStream()
{ {
Stream stream = null!; Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.WriteLittleEndian(420U)); Assert.ThrowsException<ArgumentNullException>(() => stream.Write(420U, Endianness.LittleEndian));
Assert.ThrowsException<ArgumentNullException>(() => stream.Write(420U, Endianness.BigEndian));
} }
[Test] [TestMethod]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] [CLSCompliant(false)]
public void WriteLittleEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndUInt32Argument() public void WriteUInt32_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue()
{ {
Stream stream = new DummyStream(); // we don't need to enclose this stream in a using declaration, since disposing a
Assert.Throws<ArgumentException>(() => stream.WriteLittleEndian(420U)); // 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<ArgumentOutOfRangeException>(() => stream.Write(420U, (Endianness)(-1)));
Assert.ThrowsException<ArgumentOutOfRangeException>(() => stream.Write(420U, (Endianness)(-1)));
} }
[Test] [TestMethod]
public void WriteBigEndian_ShouldWriteBigEndian_GivenUInt32Argument() [CLSCompliant(false)]
public void WriteUInt32_ShouldWriteBigEndian_GivenBigEndian()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
stream.WriteBigEndian(420U); stream.Write(420U, Endianness.BigEndian);
Assert.That(stream.Position, Is.EqualTo(4)); Assert.AreEqual(4, stream.Position);
stream.Position = 0; stream.Position = 0;
Span<byte> actual = stackalloc byte[4]; Span<byte> actual = stackalloc byte[4];
ReadOnlySpan<byte> expected = stackalloc byte[] {0x00, 0x00, 0x01, 0xA4}; ReadOnlySpan<byte> expected = stackalloc byte[] {0x00, 0x00, 0x01, 0xA4};
int read = stream.Read(actual); int read = stream.Read(actual);
Assert.That(read, Is.EqualTo(4)); Assert.AreEqual(4, read);
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
} }
[Test] [TestMethod]
public void WriteLittleEndian_ShouldWriteLittleEndian_GivenUInt32Argument() [CLSCompliant(false)]
public void WriteUInt32_ShouldWriteLittleEndian_GivenLittleEndian()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
stream.WriteLittleEndian(420U); stream.Write(420U, Endianness.LittleEndian);
Assert.That(stream.Position, Is.EqualTo(4)); Assert.AreEqual(4, stream.Position);
stream.Position = 0; stream.Position = 0;
Span<byte> actual = stackalloc byte[4]; Span<byte> actual = stackalloc byte[4];
ReadOnlySpan<byte> expected = stackalloc byte[] {0xA4, 0x01, 0x00, 0x00}; ReadOnlySpan<byte> expected = stackalloc byte[] {0xA4, 0x01, 0x00, 0x00};
int read = stream.Read(actual); int read = stream.Read(actual);
Assert.That(read, Is.EqualTo(4)); Assert.AreEqual(4, read);
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
} }
} }

View File

@ -1,70 +1,73 @@
using System.Diagnostics.CodeAnalysis; using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;
using X10D.IO; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
internal partial class StreamTests public partial class StreamTests
{ {
[Test] [TestMethod]
public void WriteBigEndian_ShouldThrowArgumentNullException_GivenNullStream_AndUInt64Argument() [CLSCompliant(false)]
{ public void WriteUInt64_ShouldThrowArgumentException_GivenNonWriteableStream()
Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.WriteBigEndian(420UL));
}
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void WriteBigEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndUInt64Argument()
{ {
Stream stream = new DummyStream(); Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.WriteBigEndian(420UL)); Assert.ThrowsException<ArgumentException>(() => stream.Write(420UL, Endianness.LittleEndian));
Assert.ThrowsException<ArgumentException>(() => stream.Write(420UL, Endianness.BigEndian));
} }
[Test] [TestMethod]
public void WriteLittleEndian_ShouldThrowArgumentNullException_GivenNullStream_AndUInt64Argument() [CLSCompliant(false)]
public void WriteUInt64_ShouldThrowArgumentNullException_GivenNullStream()
{ {
Stream stream = null!; Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.WriteLittleEndian(420UL)); Assert.ThrowsException<ArgumentNullException>(() => stream.Write(420UL, Endianness.LittleEndian));
Assert.ThrowsException<ArgumentNullException>(() => stream.Write(420UL, Endianness.BigEndian));
} }
[Test] [TestMethod]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")] [CLSCompliant(false)]
public void WriteLittleEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndUInt64Argument() public void WriteUInt64_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue()
{ {
Stream stream = new DummyStream(); // we don't need to enclose this stream in a using declaration, since disposing a
Assert.Throws<ArgumentException>(() => stream.WriteLittleEndian(420UL)); // 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<ArgumentOutOfRangeException>(() => stream.Write(420UL, (Endianness)(-1)));
Assert.ThrowsException<ArgumentOutOfRangeException>(() => stream.Write(420UL, (Endianness)(-1)));
} }
[Test] [TestMethod]
public void WriteBigEndian_ShouldWriteBigEndian_GivenUInt64Argument() [CLSCompliant(false)]
public void WriteUInt64_ShouldWriteBigEndian_GivenBigEndian()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
stream.WriteBigEndian(420UL); stream.Write(420UL, Endianness.BigEndian);
Assert.That(stream.Position, Is.EqualTo(8)); Assert.AreEqual(8, stream.Position);
stream.Position = 0; stream.Position = 0;
Span<byte> actual = stackalloc byte[8]; Span<byte> actual = stackalloc byte[8];
ReadOnlySpan<byte> expected = stackalloc byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xA4}; ReadOnlySpan<byte> expected = stackalloc byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xA4};
int read = stream.Read(actual); int read = stream.Read(actual);
Assert.That(read, Is.EqualTo(8)); Assert.AreEqual(8, read);
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
} }
[Test] [TestMethod]
public void WriteLittleEndian_ShouldWriteLittleEndian_GivenUInt64Argument() [CLSCompliant(false)]
public void WriteUInt64_ShouldWriteLittleEndian_GivenLittleEndian()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
stream.WriteLittleEndian(420UL); stream.Write(420UL, Endianness.LittleEndian);
Assert.That(stream.Position, Is.EqualTo(8)); Assert.AreEqual(8, stream.Position);
stream.Position = 0; stream.Position = 0;
Span<byte> actual = stackalloc byte[8]; Span<byte> actual = stackalloc byte[8];
ReadOnlySpan<byte> expected = stackalloc byte[] {0xA4, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; ReadOnlySpan<byte> expected = stackalloc byte[] {0xA4, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
int read = stream.Read(actual); int read = stream.Read(actual);
Assert.That(read, Is.EqualTo(8)); Assert.AreEqual(8, read);
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
} }
} }

View File

@ -1,15 +1,15 @@
using System.Diagnostics; using System.Diagnostics;
using System.Security.Cryptography; using System.Security.Cryptography;
using System.Text; using System.Text;
using NUnit.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting;
using X10D.IO; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
[TestFixture] [TestClass]
internal partial class StreamTests public partial class StreamTests
{ {
[Test] [TestMethod]
public void GetHashSha1ShouldBeCorrect() public void GetHashSha1ShouldBeCorrect()
{ {
// SHA-1 // SHA-1
@ -29,15 +29,15 @@ internal partial class StreamTests
CollectionAssert.AreEqual(expectedHash, hash); CollectionAssert.AreEqual(expectedHash, hash);
} }
[Test] [TestMethod]
public void GetHashNullShouldThrow() public void GetHashNullShouldThrow()
{ {
// any HashAlgorithm will do, but SHA1 is used above. so to remain consistent, we use it here // any HashAlgorithm will do, but SHA1 is used above. so to remain consistent, we use it here
Assert.Throws<ArgumentNullException>(() => ((Stream?)null)!.GetHash<SHA1>()); Assert.ThrowsException<ArgumentNullException>(() => ((Stream?)null)!.GetHash<SHA1>());
Assert.Throws<ArgumentNullException>(() => ((Stream?)null)!.TryWriteHash<SHA1>(Span<byte>.Empty, out _)); Assert.ThrowsException<ArgumentNullException>(() => ((Stream?)null)!.TryWriteHash<SHA1>(Span<byte>.Empty, out _));
} }
[Test] [TestMethod]
public void TryWriteHashSha1_ShouldBeCorrect() public void TryWriteHashSha1_ShouldBeCorrect()
{ {
// SHA-1 // SHA-1
@ -53,48 +53,49 @@ internal partial class StreamTests
Span<byte> hash = stackalloc byte[20]; Span<byte> hash = stackalloc byte[20];
stream.TryWriteHash<SHA1>(hash, out int bytesWritten); stream.TryWriteHash<SHA1>(hash, out int bytesWritten);
Assert.That(bytesWritten, Is.EqualTo(expectedHash.Length)); Assert.AreEqual(expectedHash.Length, bytesWritten);
CollectionAssert.AreEqual(expectedHash, hash.ToArray()); CollectionAssert.AreEqual(expectedHash, hash.ToArray());
} }
[Test] [TestMethod]
public void GetHash_TryWriteHash_ShouldThrow_GivenNonReadableStream() public void GetHash_TryWriteHash_ShouldThrow_GivenNonReadableStream()
{ {
Assert.Throws<IOException>(() => Assert.ThrowsException<IOException>(() =>
{ {
using var stream = new DummyStream(); using var stream = new DummyStream();
stream.GetHash<SHA1>(); stream.GetHash<SHA1>();
}); });
Assert.Throws<IOException>(() => Assert.ThrowsException<IOException>(() =>
{ {
using var stream = new DummyStream(); using var stream = new DummyStream();
stream.TryWriteHash<SHA1>(Span<byte>.Empty, out _); stream.TryWriteHash<SHA1>(Span<byte>.Empty, out _);
}); });
} }
[Test] [TestMethod]
public void LargeStreamShouldThrow() public void LargeStreamShouldThrow()
{ {
Assert.Throws<ArgumentException>(() => Assert.ThrowsException<ArgumentException>(() =>
{ {
using var stream = new DummyStream(true); using var stream = new DummyStream(true);
stream.TryWriteHash<SHA1>(Span<byte>.Empty, out _); stream.TryWriteHash<SHA1>(Span<byte>.Empty, out _);
}); });
} }
[Test] [TestMethod]
public void NullCreateMethodShouldThrow() public void NullCreateMethodShouldThrow()
{ {
Assert.Throws<ArgumentException>(() => Stream.Null.GetHash<HashAlgorithmTestClass>()); Assert.ThrowsException<TypeInitializationException>(() => Stream.Null.GetHash<HashAlgorithmTestClass>());
Assert.Throws<ArgumentException>(() => Stream.Null.TryWriteHash<HashAlgorithmTestClass>(Span<byte>.Empty, out _)); Assert.ThrowsException<TypeInitializationException>(() =>
Stream.Null.TryWriteHash<HashAlgorithmTestClass>(Span<byte>.Empty, out _));
} }
[Test] [TestMethod]
public void NoCreateMethodShouldThrow() public void NoCreateMethodShouldThrow()
{ {
Assert.Throws<ArgumentException>(() => Stream.Null.GetHash<HashAlgorithmTestClassNoCreateMethod>()); Assert.ThrowsException<TypeInitializationException>(() => Stream.Null.GetHash<HashAlgorithmTestClassNoCreateMethod>());
Assert.Throws<ArgumentException>(() => Assert.ThrowsException<TypeInitializationException>(() =>
Stream.Null.TryWriteHash<HashAlgorithmTestClassNoCreateMethod>(Span<byte>.Empty, out _)); Stream.Null.TryWriteHash<HashAlgorithmTestClassNoCreateMethod>(Span<byte>.Empty, out _));
} }

View File

@ -1,13 +1,13 @@
using System.Text; using System.Text;
using NUnit.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting;
using X10D.IO; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
[TestFixture] [TestClass]
internal class TextReaderTests public class TextReaderTests
{ {
[Test] [TestMethod]
public void EnumerateLines_ShouldYield10Lines_Given10LineString() public void EnumerateLines_ShouldYield10Lines_Given10LineString()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
@ -28,10 +28,10 @@ internal class TextReaderTests
lineCount++; lineCount++;
} }
Assert.That(lineCount, Is.EqualTo(10)); Assert.AreEqual(10, lineCount);
} }
[Test] [TestMethod]
public async Task EnumerateLinesAsync_ShouldYield10Lines_Given10LineString() public async Task EnumerateLinesAsync_ShouldYield10Lines_Given10LineString()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
@ -52,14 +52,14 @@ internal class TextReaderTests
lineCount++; lineCount++;
} }
Assert.That(lineCount, Is.EqualTo(10)); Assert.AreEqual(10, lineCount);
} }
[Test] [TestMethod]
public void EnumerateLines_ShouldThrowArgumentNullException_GivenNullSource() public void EnumerateLines_ShouldThrowArgumentNullException_GivenNullSource()
{ {
TextReader reader = null!; TextReader reader = null!;
Assert.Throws<ArgumentNullException>(() => Assert.ThrowsException<ArgumentNullException>(() =>
{ {
foreach (string _ in reader.EnumerateLines()) foreach (string _ in reader.EnumerateLines())
{ {
@ -68,16 +68,16 @@ internal class TextReaderTests
}); });
} }
[Test] [TestMethod]
public void EnumerateLinesAsync_ShouldThrowArgumentNullException_GivenNullSource() public async Task EnumerateLinesAsync_ShouldThrowArgumentNullException_GivenNullSource()
{ {
TextReader reader = null!; TextReader reader = null!;
Assert.ThrowsAsync<ArgumentNullException>(async () => await Assert.ThrowsExceptionAsync<ArgumentNullException>(async () =>
{ {
await foreach (string _ in reader.EnumerateLinesAsync().ConfigureAwait(false)) await foreach (string _ in reader.EnumerateLinesAsync().ConfigureAwait(false))
{ {
// loop body is intentionally empty // loop body is intentionally empty
} }
}); }).ConfigureAwait(false);
} }
} }

Some files were not shown because too many files have changed in this diff Show More