1
0
mirror of https://github.com/oliverbooth/X10D synced 2024-11-22 01:28:46 +00:00

Merge branch 'release/4.0.0' into feature/generic_math

This commit is contained in:
Oliver Booth 2023-08-25 02:27:08 +01:00
commit 8bc7372ba4
Signed by: oliverbooth
GPG Key ID: B89D139977693FED
328 changed files with 13228 additions and 10916 deletions

View File

@ -37,6 +37,8 @@ body:
label: Version
description: What version of the package are you running?
options:
- Nightly / other
- 3.2.0
- 3.1.0
- 3.0.0
- 2.6.0
@ -47,6 +49,12 @@ body:
- 2.1.0
validations:
required: true
- type: input
id: other-version
attributes:
label: Other version
description: If you selected "nightly / other", please enter the full version number here.
placeholder: "Example: 4.0.0-nightly-230"
- type: textarea
id: logs
attributes:

View File

@ -3,20 +3,29 @@ name: DocFX
on:
push:
branches: [ main ]
workflow_dispatch:
jobs:
docfx:
runs-on: ubuntu-latest
name: Publish Documentation
steps:
- uses: actions/checkout@v3
- uses: nikeee/docfx-action@v1.0.0
name: Build Documentation
with:
args: docfx_project/docfx.json
- uses: maxheld83/ghpages@master
name: Publish Documentation on GitHub Pages
env:
BUILD_DIR: docfx_project/_site
GH_PAT: ${{ secrets.GH_PAT }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Checkout
uses: actions/checkout@v3
- name: Copy favicon
run: |
mkdir docfx_project/images
cp branding_Icon.png docfx_project/images/favicon.png
- name: Build documentation
uses: nikeee/docfx-action@v1.0.0
with:
args: docfx_project/docfx.json
- name: Publish documentation on GitHub Pages
uses: maxheld83/ghpages@master
env:
BUILD_DIR: docfx_project/_site
GH_PAT: ${{ secrets.GH_PAT }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

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

View File

@ -4,6 +4,7 @@ on:
push:
branches:
- main
workflow_dispatch:
jobs:
nightly:
@ -32,7 +33,6 @@ jobs:
run: |
mkdir build
dotnet pack X10D --configuration Debug --no-build -p:SymbolPackageFormat=snupkg --include-symbols --include-source -o build -p:VersionSuffix='nightly' -p:BuildNumber=${{ github.run_number }}
dotnet pack X10D.DSharpPlus --configuration Debug --no-build -p:SymbolPackageFormat=snupkg --include-symbols --include-source -o build -p:VersionSuffix='nightly' -p:BuildNumber=${{ github.run_number }}
dotnet pack X10D.Hosting --configuration Debug --no-build -p:SymbolPackageFormat=snupkg --include-symbols --include-source -o build -p:VersionSuffix='nightly' -p:BuildNumber=${{ github.run_number }}
dotnet pack X10D.Unity --configuration Debug --no-build -p:SymbolPackageFormat=snupkg --include-symbols --include-source -o build -p:VersionSuffix='nightly' -p:BuildNumber=${{ github.run_number }}

View File

@ -32,7 +32,6 @@ jobs:
run: |
mkdir build
dotnet pack X10D --configuration Release --no-build -p:SymbolPackageFormat=snupkg --include-symbols --include-source -o build -p:VersionSuffix='prerelease' -p:BuildNumber=${{ github.run_number }}
dotnet pack X10D.DSharpPlus --configuration Release --no-build -p:SymbolPackageFormat=snupkg --include-symbols --include-source -o build -p:VersionSuffix='prerelease' -p:BuildNumber=${{ github.run_number }}
dotnet pack X10D.Hosting --configuration Release --no-build -p:SymbolPackageFormat=snupkg --include-symbols --include-source -o build -p:VersionSuffix='prerelease' -p:BuildNumber=${{ github.run_number }}
dotnet pack X10D.Unity --configuration Release --no-build -p:SymbolPackageFormat=snupkg --include-symbols --include-source -o build -p:VersionSuffix='prerelease' -p:BuildNumber=${{ github.run_number }}

View File

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

View File

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

View File

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

View File

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

View File

@ -8,11 +8,64 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## 4.0.0 - [Unreleased]
### Added
- X10D: Added extension methods for `DateOnly`, for parity with `DateTime` and `DateTimeOffset`.
- X10D: Added math-related extension methods for `BigInteger`.
- X10D: Added `Span<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
- 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
@ -576,7 +629,10 @@ please [open an issue](https://github.com/oliverbooth/X10D/issues)!
Earlier versions of this package are undocumented and unlisted from package results.
[unreleased]: https://github.com/oliverbooth/X10D/compare/v3.2.0...main
[unreleased]: https://github.com/oliverbooth/X10D/compare/v3.3.1...main
[3.3.1]: https://github.com/oliverbooth/X10D/releases/tag/v3.3.1
[3.3.0]: https://github.com/oliverbooth/X10D/releases/tag/v3.3.0
[3.2.2]: https://github.com/oliverbooth/X10D/releases/tag/v3.2.2
[3.2.0]: https://github.com/oliverbooth/X10D/releases/tag/v3.2.0
[3.1.0]: https://github.com/oliverbooth/X10D/releases/tag/v3.1.0
[3.0.0]: https://github.com/oliverbooth/X10D/releases/tag/v3.0.0

View File

@ -9,6 +9,10 @@ This project uses C# 11.0 language features where feasible, and adheres to Style
There is an `.editorconfig` included in this repository. For quick and painless pull requests, ensure that the analyzer does not
throw warnings.
Please ensure that you follow the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/)
specification, as the GitHub release for this project is automatically generated from the commit history, and formatted using the
convetional commits specification.
### Code style
Below are a few pointers to which you may refer, but keep in mind this is not an exhaustive list:

View File

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

View File

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

View File

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

View File

@ -1,80 +0,0 @@
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

@ -1,79 +0,0 @@
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

@ -1,239 +0,0 @@
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

@ -1,97 +0,0 @@
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

@ -1,73 +0,0 @@
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

@ -1,89 +0,0 @@
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

@ -1,158 +0,0 @@
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

@ -1,329 +0,0 @@
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,69 +1,7 @@
<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>
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="7.0.0"/>
</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>

View File

@ -21,6 +21,22 @@ public static class ServiceCollectionExtensions
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>
/// Adds an <see cref="IHostedService" /> registration for the given type, while simultaneously adding it as a singleton.
/// </summary>
@ -32,4 +48,19 @@ public static class ServiceCollectionExtensions
services.AddSingleton(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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,42 +1,43 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Diagnostics.CodeAnalysis;
using NUnit.Framework;
using X10D.IO;
namespace X10D.Tests.IO;
public partial class StreamTests
internal partial class StreamTests
{
[TestMethod]
public void ReadDecimal_ShouldThrowArgumentException_GivenNonReadableStream()
{
Stream stream = new DummyStream();
Assert.ThrowsException<ArgumentException>(() => stream.ReadDecimal());
Assert.ThrowsException<ArgumentException>(() => stream.ReadDecimal(Endianness.LittleEndian));
Assert.ThrowsException<ArgumentException>(() => stream.ReadDecimal(Endianness.BigEndian));
}
[TestMethod]
public void ReadDecimal_ShouldThrowArgumentNullException_GivenNullStream()
[Test]
public void ReadDecimalBigEndian_ShouldThrowArgumentNullException_GivenNullStream()
{
Stream stream = null!;
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadDecimal());
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadDecimal(Endianness.LittleEndian));
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadDecimal(Endianness.BigEndian));
Assert.Throws<ArgumentNullException>(() => stream.ReadDecimalBigEndian());
}
[TestMethod]
public void ReadDecimal_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue()
[Test]
public void ReadDecimalLittleEndian_ShouldThrowArgumentNullException_GivenNullStream()
{
// we don't need to enclose this stream in a using declaration, since disposing a
// null stream is meaningless. NullStream.Dispose actually does nothing, anyway.
// that - coupled with the fact that encapsulating the stream in a using declaration causes the
// analyser to trip up and think the stream is disposed by the time the local is captured in
// assertion lambda - means this line is fine as it is. please do not change.
Stream stream = Stream.Null;
Assert.ThrowsException<ArgumentOutOfRangeException>(() => stream.ReadDecimal((Endianness)(-1)));
Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.ReadDecimalLittleEndian());
}
[TestMethod]
public void ReadDecimal_ShouldReadBigEndian_GivenBigEndian()
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void ReadDecimalBigEndian_ShouldThrowArgumentException_GivenNonReadableStream()
{
Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.ReadDecimalBigEndian());
}
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void ReadDecimalLittleEndian_ShouldThrowArgumentException_GivenNonReadableStream()
{
Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.ReadDecimalLittleEndian());
}
[Test]
public void ReadDecimalBigEndian_ShouldReadBigEndian()
{
using var stream = new MemoryStream();
ReadOnlySpan<byte> bytes = stackalloc byte[]
@ -47,14 +48,17 @@ public partial class StreamTests
stream.Position = 0;
const decimal expected = 420.0m;
decimal actual = stream.ReadDecimal(Endianness.BigEndian);
decimal actual = stream.ReadDecimalBigEndian();
Assert.AreEqual(16, stream.Position);
Assert.AreEqual(expected, actual);
Assert.Multiple(() =>
{
Assert.That(stream.Position, Is.EqualTo(16));
Assert.That(actual, Is.EqualTo(expected));
});
}
[TestMethod]
public void ReadDecimal_ShouldWriteLittleEndian_GivenLittleEndian()
[Test]
public void ReadDecimalLittleEndian_ShouldWriteLittleEndian()
{
using var stream = new MemoryStream();
ReadOnlySpan<byte> bytes = stackalloc byte[]
@ -65,9 +69,12 @@ public partial class StreamTests
stream.Position = 0;
const decimal expected = 420.0m;
decimal actual = stream.ReadDecimal(Endianness.LittleEndian);
decimal actual = stream.ReadDecimalLittleEndian();
Assert.AreEqual(16, stream.Position);
Assert.AreEqual(expected, actual);
Assert.Multiple(() =>
{
Assert.That(stream.Position, Is.EqualTo(16));
Assert.That(actual, Is.EqualTo(expected));
});
}
}

View File

@ -1,67 +1,68 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Diagnostics.CodeAnalysis;
using NUnit.Framework;
using X10D.IO;
namespace X10D.Tests.IO;
public partial class StreamTests
internal partial class StreamTests
{
[TestMethod]
public void ReadDouble_ShouldThrowArgumentException_GivenNonReadableStream()
{
Stream stream = new DummyStream();
Assert.ThrowsException<ArgumentException>(() => stream.ReadDouble());
Assert.ThrowsException<ArgumentException>(() => stream.ReadDouble(Endianness.LittleEndian));
Assert.ThrowsException<ArgumentException>(() => stream.ReadDouble(Endianness.BigEndian));
}
[TestMethod]
public void ReadDouble_ShouldThrowArgumentNullException_GivenNullStream()
[Test]
public void ReadDoubleBigEndian_ShouldThrowArgumentNullException_GivenNullStream()
{
Stream stream = null!;
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadDouble());
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadDouble(Endianness.LittleEndian));
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadDouble(Endianness.BigEndian));
Assert.Throws<ArgumentNullException>(() => stream.ReadDoubleBigEndian());
}
[TestMethod]
public void ReadDouble_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue()
[Test]
public void ReadDoubleLittleEndian_ShouldThrowArgumentNullException_GivenNullStream()
{
// we don't need to enclose this stream in a using declaration, since disposing a
// null stream is meaningless. NullStream.Dispose actually does nothing, anyway.
// that - coupled with the fact that encapsulating the stream in a using declaration causes the
// analyser to trip up and think the stream is disposed by the time the local is captured in
// assertion lambda - means this line is fine as it is. please do not change.
Stream stream = Stream.Null;
Assert.ThrowsException<ArgumentOutOfRangeException>(() => stream.ReadDouble((Endianness)(-1)));
Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.ReadDoubleLittleEndian());
}
[TestMethod]
public void ReadDouble_ShouldReadBigEndian_GivenBigEndian()
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void ReadDoubleBigEndian_ShouldThrowArgumentException_GivenNonReadableStream()
{
Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.ReadDoubleBigEndian());
}
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void ReadDoubleLittleEndian_ShouldThrowArgumentException_GivenNonReadableStream()
{
Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.ReadDoubleLittleEndian());
}
[Test]
public void ReadDoubleBigEndian_ShouldReadBigEndian()
{
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 };
stream.Write(bytes);
stream.Position = 0;
const double expected = 420.0;
double actual = stream.ReadDouble(Endianness.BigEndian);
double actual = stream.ReadDoubleBigEndian();
Assert.AreEqual(8, stream.Position);
Assert.AreEqual(expected, actual);
Assert.That(stream.Position, Is.EqualTo(8));
Assert.That(actual, Is.EqualTo(expected));
}
[TestMethod]
public void ReadDouble_ShouldWriteLittleEndian_GivenLittleEndian()
[Test]
public void ReadDoubleLittleEndian_ShouldWriteLittleEndian()
{
using var stream = new MemoryStream();
ReadOnlySpan<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 };
stream.Write(bytes);
stream.Position = 0;
const double expected = 420.0;
double actual = stream.ReadDouble(Endianness.LittleEndian);
double actual = stream.ReadDoubleLittleEndian();
Assert.AreEqual(8, stream.Position);
Assert.AreEqual(expected, actual);
Assert.That(stream.Position, Is.EqualTo(8));
Assert.That(actual, Is.EqualTo(expected));
}
}

View File

@ -1,67 +1,68 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Diagnostics.CodeAnalysis;
using NUnit.Framework;
using X10D.IO;
namespace X10D.Tests.IO;
public partial class StreamTests
internal partial class StreamTests
{
[TestMethod]
public void ReadInt16_ShouldThrowArgumentException_GivenNonReadableStream()
{
Stream stream = new DummyStream();
Assert.ThrowsException<ArgumentException>(() => stream.ReadInt16());
Assert.ThrowsException<ArgumentException>(() => stream.ReadInt16(Endianness.LittleEndian));
Assert.ThrowsException<ArgumentException>(() => stream.ReadInt16(Endianness.BigEndian));
}
[TestMethod]
public void ReadInt16_ShouldThrowArgumentNullException_GivenNullStream()
[Test]
public void ReadInt16BigEndian_ShouldThrowArgumentNullException_GivenNullStream()
{
Stream stream = null!;
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadInt16());
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadInt16(Endianness.LittleEndian));
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadInt16(Endianness.BigEndian));
Assert.Throws<ArgumentNullException>(() => stream.ReadInt16BigEndian());
}
[TestMethod]
public void ReadInt16_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue()
[Test]
public void ReadInt16LittleEndian_ShouldThrowArgumentNullException_GivenNullStream()
{
// we don't need to enclose this stream in a using declaration, since disposing a
// null stream is meaningless. NullStream.Dispose actually does nothing, anyway.
// that - coupled with the fact that encapsulating the stream in a using declaration causes the
// analyser to trip up and think the stream is disposed by the time the local is captured in
// assertion lambda - means this line is fine as it is. please do not change.
Stream stream = Stream.Null;
Assert.ThrowsException<ArgumentOutOfRangeException>(() => stream.ReadInt16((Endianness)(-1)));
Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.ReadInt16LittleEndian());
}
[TestMethod]
public void ReadInt16_ShouldReadBigEndian_GivenBigEndian()
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void ReadInt16BigEndian_ShouldThrowArgumentException_GivenNonReadableStream()
{
Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.ReadInt16BigEndian());
}
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void ReadInt16LittleEndian_ShouldThrowArgumentException_GivenNonReadableStream()
{
Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.ReadInt16LittleEndian());
}
[Test]
public void ReadInt16BigEndian_ShouldReadBigEndian()
{
using var stream = new MemoryStream();
ReadOnlySpan<byte> bytes = stackalloc byte[] {0x01, 0xA4};
ReadOnlySpan<byte> bytes = stackalloc byte[] { 0x01, 0xA4 };
stream.Write(bytes);
stream.Position = 0;
const short expected = 420;
short actual = stream.ReadInt16(Endianness.BigEndian);
short actual = stream.ReadInt16BigEndian();
Assert.AreEqual(2, stream.Position);
Assert.AreEqual(expected, actual);
Assert.That(stream.Position, Is.EqualTo(2));
Assert.That(actual, Is.EqualTo(expected));
}
[TestMethod]
public void ReadInt16_ShouldReadLittleEndian_GivenLittleEndian()
[Test]
public void ReadInt16LittleEndian_ShouldReadLittleEndian()
{
using var stream = new MemoryStream();
ReadOnlySpan<byte> bytes = stackalloc byte[] {0xA4, 0x01};
ReadOnlySpan<byte> bytes = stackalloc byte[] { 0xA4, 0x01 };
stream.Write(bytes);
stream.Position = 0;
const short expected = 420;
short actual = stream.ReadInt16(Endianness.LittleEndian);
short actual = stream.ReadInt16LittleEndian();
Assert.AreEqual(2, stream.Position);
Assert.AreEqual(expected, actual);
Assert.That(stream.Position, Is.EqualTo(2));
Assert.That(actual, Is.EqualTo(expected));
}
}

View File

@ -1,67 +1,68 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Diagnostics.CodeAnalysis;
using NUnit.Framework;
using X10D.IO;
namespace X10D.Tests.IO;
public partial class StreamTests
internal partial class StreamTests
{
[TestMethod]
public void ReadInt32_ShouldThrowArgumentException_GivenNonReadableStream()
{
Stream stream = new DummyStream();
Assert.ThrowsException<ArgumentException>(() => stream.ReadInt32());
Assert.ThrowsException<ArgumentException>(() => stream.ReadInt32(Endianness.LittleEndian));
Assert.ThrowsException<ArgumentException>(() => stream.ReadInt32(Endianness.BigEndian));
}
[TestMethod]
public void ReadInt32_ShouldThrowArgumentNullException_GivenNullStream()
[Test]
public void ReadInt32BigEndian_ShouldThrowArgumentNullException_GivenNullStream()
{
Stream stream = null!;
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadInt32());
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadInt32(Endianness.LittleEndian));
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadInt32(Endianness.BigEndian));
Assert.Throws<ArgumentNullException>(() => stream.ReadInt32BigEndian());
}
[TestMethod]
public void ReadInt32_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue()
[Test]
public void ReadInt32LittleEndian_ShouldThrowArgumentNullException_GivenNullStream()
{
// we don't need to enclose this stream in a using declaration, since disposing a
// null stream is meaningless. NullStream.Dispose actually does nothing, anyway.
// that - coupled with the fact that encapsulating the stream in a using declaration causes the
// analyser to trip up and think the stream is disposed by the time the local is captured in
// assertion lambda - means this line is fine as it is. please do not change.
Stream stream = Stream.Null;
Assert.ThrowsException<ArgumentOutOfRangeException>(() => stream.ReadInt32((Endianness)(-1)));
Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.ReadInt32LittleEndian());
}
[TestMethod]
public void ReadInt32_ShouldReadBigEndian_GivenBigEndian()
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void ReadInt32BigEndian_ShouldThrowArgumentException_GivenNonReadableStream()
{
Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.ReadInt32BigEndian());
}
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void ReadInt32LittleEndian_ShouldThrowArgumentException_GivenNonReadableStream()
{
Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.ReadInt32LittleEndian());
}
[Test]
public void ReadInt32BigEndian_ShouldReadBigEndian()
{
using var stream = new MemoryStream();
ReadOnlySpan<byte> bytes = stackalloc byte[] {0x00, 0x00, 0x01, 0xA4};
ReadOnlySpan<byte> bytes = stackalloc byte[] { 0x00, 0x00, 0x01, 0xA4 };
stream.Write(bytes);
stream.Position = 0;
const int expected = 420;
int actual = stream.ReadInt32(Endianness.BigEndian);
int actual = stream.ReadInt32BigEndian();
Assert.AreEqual(4, stream.Position);
Assert.AreEqual(expected, actual);
Assert.That(stream.Position, Is.EqualTo(4));
Assert.That(actual, Is.EqualTo(expected));
}
[TestMethod]
public void ReadInt32_ShouldReadLittleEndian_GivenLittleEndian()
[Test]
public void ReadInt32LittleEndian_ShouldReadLittleEndian()
{
using var stream = new MemoryStream();
ReadOnlySpan<byte> bytes = stackalloc byte[] {0xA4, 0x01, 0x00, 0x00};
ReadOnlySpan<byte> bytes = stackalloc byte[] { 0xA4, 0x01, 0x00, 0x00 };
stream.Write(bytes);
stream.Position = 0;
const int expected = 420;
int actual = stream.ReadInt32(Endianness.LittleEndian);
int actual = stream.ReadInt32LittleEndian();
Assert.AreEqual(4, stream.Position);
Assert.AreEqual(expected, actual);
Assert.That(stream.Position, Is.EqualTo(4));
Assert.That(actual, Is.EqualTo(expected));
}
}

View File

@ -1,67 +1,65 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;
using X10D.IO;
namespace X10D.Tests.IO;
public partial class StreamTests
internal partial class StreamTests
{
[TestMethod]
public void ReadInt64_ShouldThrowArgumentException_GivenNonReadableStream()
{
Stream stream = new DummyStream();
Assert.ThrowsException<ArgumentException>(() => stream.ReadInt64());
Assert.ThrowsException<ArgumentException>(() => stream.ReadInt64(Endianness.LittleEndian));
Assert.ThrowsException<ArgumentException>(() => stream.ReadInt64(Endianness.BigEndian));
}
[TestMethod]
public void ReadInt64_ShouldThrowArgumentNullException_GivenNullStream()
[Test]
public void ReadInt64BigEndian_ShouldThrowArgumentNullException_GivenNullStream()
{
Stream stream = null!;
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadInt64());
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadInt64(Endianness.LittleEndian));
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadInt64(Endianness.BigEndian));
Assert.Throws<ArgumentNullException>(() => stream.ReadInt64BigEndian());
}
[TestMethod]
public void ReadInt64_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue()
[Test]
public void ReadInt64LittleEndian_ShouldThrowArgumentNullException_GivenNullStream()
{
// we don't need to enclose this stream in a using declaration, since disposing a
// null stream is meaningless. NullStream.Dispose actually does nothing, anyway.
// that - coupled with the fact that encapsulating the stream in a using declaration causes the
// analyser to trip up and think the stream is disposed by the time the local is captured in
// assertion lambda - means this line is fine as it is. please do not change.
Stream stream = Stream.Null;
Assert.ThrowsException<ArgumentOutOfRangeException>(() => stream.ReadInt64((Endianness)(-1)));
Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.ReadInt64LittleEndian());
}
[TestMethod]
public void ReadInt64_ShouldReadBigEndian_GivenBigEndian()
[Test]
public void ReadInt64BigEndian_ShouldThrowArgumentException_GivenNonReadableStream()
{
Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.ReadInt64BigEndian());
}
[Test]
public void ReadInt64LittleEndian_ShouldThrowArgumentException_GivenNonReadableStream()
{
Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.ReadInt64LittleEndian());
}
[Test]
public void ReadInt64BigEndian_ShouldReadBigEndian()
{
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 };
stream.Write(bytes);
stream.Position = 0;
const long expected = 420;
long actual = stream.ReadInt64(Endianness.BigEndian);
long actual = stream.ReadInt64BigEndian();
Assert.AreEqual(8, stream.Position);
Assert.AreEqual(expected, actual);
Assert.That(stream.Position, Is.EqualTo(8));
Assert.That(actual, Is.EqualTo(expected));
}
[TestMethod]
public void ReadInt64_ShouldWriteLittleEndian_GivenLittleEndian()
[Test]
public void ReadInt64LittleEndian_ShouldWriteLittleEndian()
{
using var stream = new MemoryStream();
ReadOnlySpan<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 };
stream.Write(bytes);
stream.Position = 0;
const long expected = 420;
long actual = stream.ReadInt64(Endianness.LittleEndian);
long actual = stream.ReadInt64LittleEndian();
Assert.AreEqual(8, stream.Position);
Assert.AreEqual(expected, actual);
Assert.That(stream.Position, Is.EqualTo(8));
Assert.That(actual, Is.EqualTo(expected));
}
}

View File

@ -1,67 +1,68 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Diagnostics.CodeAnalysis;
using NUnit.Framework;
using X10D.IO;
namespace X10D.Tests.IO;
public partial class StreamTests
internal partial class StreamTests
{
[TestMethod]
public void ReadSingle_ShouldThrowArgumentException_GivenNonReadableStream()
{
Stream stream = new DummyStream();
Assert.ThrowsException<ArgumentException>(() => stream.ReadSingle());
Assert.ThrowsException<ArgumentException>(() => stream.ReadSingle(Endianness.LittleEndian));
Assert.ThrowsException<ArgumentException>(() => stream.ReadSingle(Endianness.BigEndian));
}
[TestMethod]
public void ReadSingle_ShouldThrowArgumentNullException_GivenNullStream()
[Test]
public void ReadSingleBigEndian_ShouldThrowArgumentNullException_GivenNullStream()
{
Stream stream = null!;
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadSingle());
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadSingle(Endianness.LittleEndian));
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadSingle(Endianness.BigEndian));
Assert.Throws<ArgumentNullException>(() => stream.ReadSingleBigEndian());
}
[TestMethod]
public void ReadSingle_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue()
[Test]
public void ReadSingleLittleEndian_ShouldThrowArgumentNullException_GivenNullStream()
{
// we don't need to enclose this stream in a using declaration, since disposing a
// null stream is meaningless. NullStream.Dispose actually does nothing, anyway.
// that - coupled with the fact that encapsulating the stream in a using declaration causes the
// analyser to trip up and think the stream is disposed by the time the local is captured in
// assertion lambda - means this line is fine as it is. please do not change.
Stream stream = Stream.Null;
Assert.ThrowsException<ArgumentOutOfRangeException>(() => stream.ReadSingle((Endianness)(-1)));
Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.ReadSingleLittleEndian());
}
[TestMethod]
public void ReadSingle_ShouldReadBigEndian_GivenBigEndian()
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void ReadSingleBigEndian_ShouldThrowArgumentException_GivenNonReadableStream()
{
Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.ReadSingleBigEndian());
}
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void ReadSingleLittleEndian_ShouldThrowArgumentException_GivenNonReadableStream()
{
Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.ReadSingleLittleEndian());
}
[Test]
public void ReadSingleBigEndian_ShouldReadBigEndian()
{
using var stream = new MemoryStream();
ReadOnlySpan<byte> bytes = stackalloc byte[] {0x43, 0xD2, 0x00, 0x00};
ReadOnlySpan<byte> bytes = stackalloc byte[] { 0x43, 0xD2, 0x00, 0x00 };
stream.Write(bytes);
stream.Position = 0;
const float expected = 420.0f;
float actual = stream.ReadSingle(Endianness.BigEndian);
float actual = stream.ReadSingleBigEndian();
Assert.AreEqual(4, stream.Position);
Assert.AreEqual(expected, actual);
Assert.That(stream.Position, Is.EqualTo(4));
Assert.That(actual, Is.EqualTo(expected));
}
[TestMethod]
public void ReadSingle_ShouldReadLittleEndian_GivenLittleEndian()
[Test]
public void ReadSingleLittleEndian_ShouldReadLittleEndian()
{
using var stream = new MemoryStream();
ReadOnlySpan<byte> bytes = stackalloc byte[] {0x00, 0x00, 0xD2, 0x43};
ReadOnlySpan<byte> bytes = stackalloc byte[] { 0x00, 0x00, 0xD2, 0x43 };
stream.Write(bytes);
stream.Position = 0;
const float expected = 420.0f;
float actual = stream.ReadSingle(Endianness.LittleEndian);
float actual = stream.ReadSingleLittleEndian();
Assert.AreEqual(4, stream.Position);
Assert.AreEqual(expected, actual);
Assert.That(stream.Position, Is.EqualTo(4));
Assert.That(actual, Is.EqualTo(expected));
}
}

View File

@ -1,72 +1,68 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Diagnostics.CodeAnalysis;
using NUnit.Framework;
using X10D.IO;
namespace X10D.Tests.IO;
public partial class StreamTests
internal partial class StreamTests
{
[TestMethod]
[CLSCompliant(false)]
public void ReadUInt16_ShouldThrowArgumentException_GivenNonReadableStream()
{
Stream stream = new DummyStream();
Assert.ThrowsException<ArgumentException>(() => stream.ReadUInt16());
Assert.ThrowsException<ArgumentException>(() => stream.ReadUInt16(Endianness.LittleEndian));
Assert.ThrowsException<ArgumentException>(() => stream.ReadUInt16(Endianness.BigEndian));
}
[TestMethod]
[CLSCompliant(false)]
public void ReadUInt16_ShouldThrowArgumentNullException_GivenNullStream()
[Test]
public void ReadUInt16BigEndian_ShouldThrowArgumentNullException_GivenNullStream()
{
Stream stream = null!;
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadUInt16());
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadUInt16(Endianness.LittleEndian));
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadUInt16(Endianness.BigEndian));
Assert.Throws<ArgumentNullException>(() => stream.ReadUInt16BigEndian());
}
[TestMethod]
[CLSCompliant(false)]
public void ReadUInt16_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue()
[Test]
public void ReadUInt16LittleEndian_ShouldThrowArgumentNullException_GivenNullStream()
{
// we don't need to enclose this stream in a using declaration, since disposing a
// null stream is meaningless. NullStream.Dispose actually does nothing, anyway.
// that - coupled with the fact that encapsulating the stream in a using declaration causes the
// analyser to trip up and think the stream is disposed by the time the local is captured in
// assertion lambda - means this line is fine as it is. please do not change.
Stream stream = Stream.Null;
Assert.ThrowsException<ArgumentOutOfRangeException>(() => stream.ReadUInt16((Endianness)(-1)));
Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.ReadUInt16LittleEndian());
}
[TestMethod]
[CLSCompliant(false)]
public void ReadUInt16_ShouldReadBigEndian_GivenBigEndian()
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void ReadUInt16BigEndian_ShouldThrowArgumentException_GivenNonReadableStream()
{
Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.ReadUInt16BigEndian());
}
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void ReadUInt16LittleEndian_ShouldThrowArgumentException_GivenNonReadableStream()
{
Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.ReadUInt16LittleEndian());
}
[Test]
public void ReadUInt16BigEndian_ShouldReadBigEndian()
{
using var stream = new MemoryStream();
ReadOnlySpan<byte> bytes = stackalloc byte[] {0x01, 0xA4};
ReadOnlySpan<byte> bytes = stackalloc byte[] { 0x01, 0xA4 };
stream.Write(bytes);
stream.Position = 0;
const ushort expected = 420;
ushort actual = stream.ReadUInt16(Endianness.BigEndian);
ushort actual = stream.ReadUInt16BigEndian();
Assert.AreEqual(2, stream.Position);
Assert.AreEqual(expected, actual);
Assert.That(stream.Position, Is.EqualTo(2));
Assert.That(actual, Is.EqualTo(expected));
}
[TestMethod]
[CLSCompliant(false)]
public void ReadUInt16_ShouldReadLittleEndian_GivenLittleEndian()
[Test]
public void ReadUInt16LittleEndian_ShouldReadLittleEndian()
{
using var stream = new MemoryStream();
ReadOnlySpan<byte> bytes = stackalloc byte[] {0xA4, 0x01};
ReadOnlySpan<byte> bytes = stackalloc byte[] { 0xA4, 0x01 };
stream.Write(bytes);
stream.Position = 0;
const ushort expected = 420;
ushort actual = stream.ReadUInt16(Endianness.LittleEndian);
ushort actual = stream.ReadUInt16LittleEndian();
Assert.AreEqual(2, stream.Position);
Assert.AreEqual(expected, actual);
Assert.That(stream.Position, Is.EqualTo(2));
Assert.That(actual, Is.EqualTo(expected));
}
}

View File

@ -1,72 +1,68 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Diagnostics.CodeAnalysis;
using NUnit.Framework;
using X10D.IO;
namespace X10D.Tests.IO;
public partial class StreamTests
internal partial class StreamTests
{
[TestMethod]
[CLSCompliant(false)]
public void ReadUInt32_ShouldThrowArgumentException_GivenNonReadableStream()
{
Stream stream = new DummyStream();
Assert.ThrowsException<ArgumentException>(() => stream.ReadUInt32());
Assert.ThrowsException<ArgumentException>(() => stream.ReadUInt32(Endianness.LittleEndian));
Assert.ThrowsException<ArgumentException>(() => stream.ReadUInt32(Endianness.BigEndian));
}
[TestMethod]
[CLSCompliant(false)]
public void ReadUInt32_ShouldThrowArgumentNullException_GivenNullStream()
[Test]
public void ReadUInt32BigEndian_ShouldThrowArgumentNullException_GivenNullStream()
{
Stream stream = null!;
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadUInt32());
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadUInt32(Endianness.LittleEndian));
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadUInt32(Endianness.BigEndian));
Assert.Throws<ArgumentNullException>(() => stream.ReadUInt32BigEndian());
}
[TestMethod]
[CLSCompliant(false)]
public void ReadUInt32_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue()
[Test]
public void ReadUInt32LittleEndian_ShouldThrowArgumentNullException_GivenNullStream()
{
// we don't need to enclose this stream in a using declaration, since disposing a
// null stream is meaningless. NullStream.Dispose actually does nothing, anyway.
// that - coupled with the fact that encapsulating the stream in a using declaration causes the
// analyser to trip up and think the stream is disposed by the time the local is captured in
// assertion lambda - means this line is fine as it is. please do not change.
Stream stream = Stream.Null;
Assert.ThrowsException<ArgumentOutOfRangeException>(() => stream.ReadUInt32((Endianness)(-1)));
Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.ReadUInt32LittleEndian());
}
[TestMethod]
[CLSCompliant(false)]
public void ReadUInt32_ShouldReadBigEndian_GivenBigEndian()
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void ReadUInt32BigEndian_ShouldThrowArgumentException_GivenNonReadableStream()
{
Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.ReadUInt32BigEndian());
}
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void ReadUInt32LittleEndian_ShouldThrowArgumentException_GivenNonReadableStream()
{
Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.ReadUInt32LittleEndian());
}
[Test]
public void ReadUInt32BigEndian_ShouldReadBigEndian()
{
using var stream = new MemoryStream();
ReadOnlySpan<byte> bytes = stackalloc byte[] {0x00, 0x00, 0x01, 0xA4};
ReadOnlySpan<byte> bytes = stackalloc byte[] { 0x00, 0x00, 0x01, 0xA4 };
stream.Write(bytes);
stream.Position = 0;
const uint expected = 420;
uint actual = stream.ReadUInt32(Endianness.BigEndian);
uint actual = stream.ReadUInt32BigEndian();
Assert.AreEqual(4, stream.Position);
Assert.AreEqual(expected, actual);
Assert.That(stream.Position, Is.EqualTo(4));
Assert.That(actual, Is.EqualTo(expected));
}
[TestMethod]
[CLSCompliant(false)]
public void ReadUInt32_ShouldReadLittleEndian_GivenLittleEndian()
[Test]
public void ReadUInt32LittleEndian_ShouldReadLittleEndian()
{
using var stream = new MemoryStream();
ReadOnlySpan<byte> bytes = stackalloc byte[] {0xA4, 0x01, 0x00, 0x00};
ReadOnlySpan<byte> bytes = stackalloc byte[] { 0xA4, 0x01, 0x00, 0x00 };
stream.Write(bytes);
stream.Position = 0;
const uint expected = 420;
uint actual = stream.ReadUInt32(Endianness.LittleEndian);
uint actual = stream.ReadUInt32LittleEndian();
Assert.AreEqual(4, stream.Position);
Assert.AreEqual(expected, actual);
Assert.That(stream.Position, Is.EqualTo(4));
Assert.That(actual, Is.EqualTo(expected));
}
}

View File

@ -1,72 +1,68 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Diagnostics.CodeAnalysis;
using NUnit.Framework;
using X10D.IO;
namespace X10D.Tests.IO;
public partial class StreamTests
internal partial class StreamTests
{
[TestMethod]
[CLSCompliant(false)]
public void ReadUInt64_ShouldThrowArgumentException_GivenNonReadableStream()
{
Stream stream = new DummyStream();
Assert.ThrowsException<ArgumentException>(() => stream.ReadUInt64());
Assert.ThrowsException<ArgumentException>(() => stream.ReadUInt64(Endianness.LittleEndian));
Assert.ThrowsException<ArgumentException>(() => stream.ReadUInt64(Endianness.BigEndian));
}
[TestMethod]
[CLSCompliant(false)]
public void ReadUInt64_ShouldThrowArgumentNullException_GivenNullStream()
[Test]
public void ReadUInt64BigEndian_ShouldThrowArgumentNullException_GivenNullStream()
{
Stream stream = null!;
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadUInt64());
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadUInt64(Endianness.LittleEndian));
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadUInt64(Endianness.BigEndian));
Assert.Throws<ArgumentNullException>(() => stream.ReadUInt64BigEndian());
}
[TestMethod]
[CLSCompliant(false)]
public void ReadUInt64_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue()
[Test]
public void ReadUInt64LittleEndian_ShouldThrowArgumentNullException_GivenNullStream()
{
// we don't need to enclose this stream in a using declaration, since disposing a
// null stream is meaningless. NullStream.Dispose actually does nothing, anyway.
// that - coupled with the fact that encapsulating the stream in a using declaration causes the
// analyser to trip up and think the stream is disposed by the time the local is captured in
// assertion lambda - means this line is fine as it is. please do not change.
Stream stream = Stream.Null;
Assert.ThrowsException<ArgumentOutOfRangeException>(() => stream.ReadUInt64((Endianness)(-1)));
Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.ReadUInt64LittleEndian());
}
[TestMethod]
[CLSCompliant(false)]
public void ReadUInt64_ShouldReadBigEndian_GivenBigEndian()
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void ReadUInt64BigEndian_ShouldThrowArgumentException_GivenNonReadableStream()
{
Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.ReadUInt64BigEndian());
}
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void ReadUInt64LittleEndian_ShouldThrowArgumentException_GivenNonReadableStream()
{
Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.ReadUInt64LittleEndian());
}
[Test]
public void ReadUInt64BigEndian_ShouldReadBigEndian()
{
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 };
stream.Write(bytes);
stream.Position = 0;
const ulong expected = 420;
ulong actual = stream.ReadUInt64(Endianness.BigEndian);
ulong actual = stream.ReadUInt64BigEndian();
Assert.AreEqual(8, stream.Position);
Assert.AreEqual(expected, actual);
Assert.That(stream.Position, Is.EqualTo(8));
Assert.That(actual, Is.EqualTo(expected));
}
[TestMethod]
[CLSCompliant(false)]
public void ReadUInt64_ShouldWriteLittleEndian_GivenLittleEndian()
[Test]
public void ReadUInt64LittleEndian_ShouldWriteLittleEndian()
{
using var stream = new MemoryStream();
ReadOnlySpan<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 };
stream.Write(bytes);
stream.Position = 0;
const ulong expected = 420;
ulong actual = stream.ReadUInt64(Endianness.LittleEndian);
ulong actual = stream.ReadUInt64LittleEndian();
Assert.AreEqual(8, stream.Position);
Assert.AreEqual(expected, actual);
Assert.That(stream.Position, Is.EqualTo(8));
Assert.That(actual, Is.EqualTo(expected));
}
}

View File

@ -1,65 +1,67 @@
using System.Diagnostics;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Diagnostics.CodeAnalysis;
using NUnit.Framework;
using X10D.IO;
namespace X10D.Tests.IO;
public partial class StreamTests
internal partial class StreamTests
{
[TestMethod]
public void WriteDecimal_ShouldThrowArgumentException_GivenNonWriteableStream()
{
Stream stream = new DummyStream();
Assert.ThrowsException<ArgumentException>(() => stream.Write(420.0m, Endianness.LittleEndian));
Assert.ThrowsException<ArgumentException>(() => stream.Write(420.0m, Endianness.BigEndian));
}
[TestMethod]
public void WriteDecimal_ShouldThrowArgumentNullException_GivenNullStream()
[Test]
public void WriteBigEndian_ShouldThrowArgumentNullException_GivenNullStream_AndDecimalArgument()
{
Stream stream = null!;
Assert.ThrowsException<ArgumentNullException>(() => stream.Write(420.0m, Endianness.LittleEndian));
Assert.ThrowsException<ArgumentNullException>(() => stream.Write(420.0m, Endianness.BigEndian));
Assert.Throws<ArgumentNullException>(() => stream.WriteBigEndian(420.0m));
}
[TestMethod]
public void WriteDecimal_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue()
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void WriteBigEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndDecimalArgument()
{
// we don't need to enclose this stream in a using declaration, since disposing a
// null stream is meaningless. NullStream.Dispose actually does nothing, anyway.
// that - coupled with the fact that encapsulating the stream in a using declaration causes the
// analyser to trip up and think the stream is disposed by the time the local is captured in
// assertion lambda - means this line is fine as it is. please do not change.
Stream stream = Stream.Null;
Assert.ThrowsException<ArgumentOutOfRangeException>(() => stream.Write(420.0m, (Endianness)(-1)));
Assert.ThrowsException<ArgumentOutOfRangeException>(() => stream.Write(420.0m, (Endianness)(-1)));
Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.WriteBigEndian(420.0m));
}
[TestMethod]
public void WriteDecimal_ShouldWriteBigEndian_GivenBigEndian()
[Test]
public void WriteLittleEndian_ShouldThrowArgumentNullException_GivenNullStream_AndDecimalArgument()
{
Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.WriteLittleEndian(420.0m));
}
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void WriteLittleEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndDecimalArgument()
{
Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.WriteLittleEndian(420.0m));
}
[Test]
public void WriteBigEndian_ShouldWriteBigEndian_GivenDecimalArgument()
{
using var stream = new MemoryStream();
stream.Write(420.0m, Endianness.BigEndian);
Assert.AreEqual(16, stream.Position);
stream.WriteBigEndian(420.0m);
Assert.That(stream.Position, Is.EqualTo(16));
stream.Position = 0;
Span<byte> actual = stackalloc byte[16];
ReadOnlySpan<byte> expected = stackalloc byte[]
{
0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x68
0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x68, 0x10, 0x00, 0x00
};
int read = stream.Read(actual);
Assert.AreEqual(16, read);
Assert.That(read, Is.EqualTo(16));
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
}
[TestMethod]
public void WriteDecimal_ShouldWriteLittleEndian_GivenLittleEndian()
[Test]
public void WriteLittleEndian_ShouldWriteLittleEndian_GivenDecimalArgument()
{
using var stream = new MemoryStream();
stream.Write(420.0m, Endianness.LittleEndian);
Assert.AreEqual(16, stream.Position);
stream.WriteLittleEndian(420.0m);
Assert.That(stream.Position, Is.EqualTo(16));
stream.Position = 0;
Span<byte> actual = stackalloc byte[16];
@ -71,7 +73,7 @@ public partial class StreamTests
Trace.WriteLine(string.Join(", ", actual.ToArray().Select(b => $"0x{b:X2}")));
Assert.AreEqual(16, read);
Assert.That(read, Is.EqualTo(16));
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
}
}

View File

@ -1,68 +1,70 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Diagnostics.CodeAnalysis;
using NUnit.Framework;
using X10D.IO;
namespace X10D.Tests.IO;
public partial class StreamTests
internal partial class StreamTests
{
[TestMethod]
public void WriteDouble_ShouldThrowArgumentException_GivenNonWriteableStream()
{
Stream stream = new DummyStream();
Assert.ThrowsException<ArgumentException>(() => stream.Write(420.0, Endianness.LittleEndian));
Assert.ThrowsException<ArgumentException>(() => stream.Write(420.0, Endianness.BigEndian));
}
[TestMethod]
public void WriteDouble_ShouldThrowArgumentNullException_GivenNullStream()
[Test]
public void WriteBigEndian_ShouldThrowArgumentNullException_GivenNullStream_AndDoubleArgument()
{
Stream stream = null!;
Assert.ThrowsException<ArgumentNullException>(() => stream.Write(420.0, Endianness.LittleEndian));
Assert.ThrowsException<ArgumentNullException>(() => stream.Write(420.0, Endianness.BigEndian));
Assert.Throws<ArgumentNullException>(() => stream.WriteBigEndian(420.0));
}
[TestMethod]
public void WriteDouble_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue()
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void WriteBigEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndDoubleArgument()
{
// we don't need to enclose this stream in a using declaration, since disposing a
// null stream is meaningless. NullStream.Dispose actually does nothing, anyway.
// that - coupled with the fact that encapsulating the stream in a using declaration causes the
// analyser to trip up and think the stream is disposed by the time the local is captured in
// assertion lambda - means this line is fine as it is. please do not change.
Stream stream = Stream.Null;
Assert.ThrowsException<ArgumentOutOfRangeException>(() => stream.Write(420.0, (Endianness)(-1)));
Assert.ThrowsException<ArgumentOutOfRangeException>(() => stream.Write(420.0, (Endianness)(-1)));
Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.WriteBigEndian(420.0));
}
[TestMethod]
public void WriteDouble_ShouldWriteBigEndian_GivenBigEndian()
[Test]
public void WriteLittleEndian_ShouldThrowArgumentNullException_GivenNullStream_AndDoubleArgument()
{
Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.WriteLittleEndian(420.0));
}
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void WriteLittleEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndDoubleArgument()
{
Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.WriteLittleEndian(420.0));
}
[Test]
public void WriteBigEndian_ShouldWriteBigEndian_GivenDoubleArgument()
{
using var stream = new MemoryStream();
stream.Write(420.0, Endianness.BigEndian);
Assert.AreEqual(8, stream.Position);
stream.WriteBigEndian(420.0);
Assert.That(stream.Position, Is.EqualTo(8));
stream.Position = 0;
Span<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);
Assert.AreEqual(8, read);
Assert.That(read, Is.EqualTo(8));
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
}
[TestMethod]
public void WriteDouble_ShouldWriteLittleEndian_GivenLittleEndian()
[Test]
public void WriteLittleEndian_ShouldWriteLittleEndian_GivenDoubleArgument()
{
using var stream = new MemoryStream();
stream.Write(420.0, Endianness.LittleEndian);
Assert.AreEqual(8, stream.Position);
stream.WriteLittleEndian(420.0);
Assert.That(stream.Position, Is.EqualTo(8));
stream.Position = 0;
Span<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);
Assert.AreEqual(8, read);
Assert.That(read, Is.EqualTo(8));
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
}
}

View File

@ -1,68 +1,70 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Diagnostics.CodeAnalysis;
using NUnit.Framework;
using X10D.IO;
namespace X10D.Tests.IO;
public partial class StreamTests
internal partial class StreamTests
{
[TestMethod]
public void WriteInt16_ShouldThrowArgumentException_GivenNonWriteableStream()
{
Stream stream = new DummyStream();
Assert.ThrowsException<ArgumentException>(() => stream.Write((short)420, Endianness.LittleEndian));
Assert.ThrowsException<ArgumentException>(() => stream.Write((short)420, Endianness.BigEndian));
}
[TestMethod]
public void WriteInt16_ShouldThrowArgumentNullException_GivenNullStream()
[Test]
public void WriteBigEndian_ShouldThrowArgumentNullException_GivenNullStream_AndInt16Argument()
{
Stream stream = null!;
Assert.ThrowsException<ArgumentNullException>(() => stream.Write((short)420, Endianness.LittleEndian));
Assert.ThrowsException<ArgumentNullException>(() => stream.Write((short)420, Endianness.BigEndian));
Assert.Throws<ArgumentNullException>(() => stream.WriteBigEndian((short)420));
}
[TestMethod]
public void WriteInt16_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue()
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void WriteBigEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndInt16Argument()
{
// we don't need to enclose this stream in a using declaration, since disposing a
// null stream is meaningless. NullStream.Dispose actually does nothing, anyway.
// that - coupled with the fact that encapsulating the stream in a using declaration causes the
// analyser to trip up and think the stream is disposed by the time the local is captured in
// assertion lambda - means this line is fine as it is. please do not change.
Stream stream = Stream.Null;
Assert.ThrowsException<ArgumentOutOfRangeException>(() => stream.Write((short)420, (Endianness)(-1)));
Assert.ThrowsException<ArgumentOutOfRangeException>(() => stream.Write((short)420, (Endianness)(-1)));
Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.WriteBigEndian((short)420));
}
[TestMethod]
public void WriteInt16_ShouldWriteBigEndian_GivenBigEndian()
[Test]
public void WriteLittleEndian_ShouldThrowArgumentNullException_GivenNullStream_AndInt16Argument()
{
Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.WriteLittleEndian((short)420));
}
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void WriteLittleEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndInt16Argument()
{
Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.WriteLittleEndian((short)420));
}
[Test]
public void WriteBigEndian_ShouldWriteBigEndian_GivenInt16Argument()
{
using var stream = new MemoryStream();
stream.Write((short)420, Endianness.BigEndian);
Assert.AreEqual(2, stream.Position);
stream.WriteBigEndian((short)420);
Assert.That(stream.Position, Is.EqualTo(2));
stream.Position = 0;
Span<byte> actual = stackalloc byte[2];
ReadOnlySpan<byte> expected = stackalloc byte[] {0x01, 0xA4};
ReadOnlySpan<byte> expected = stackalloc byte[] { 0x01, 0xA4 };
int read = stream.Read(actual);
Assert.AreEqual(2, read);
Assert.That(read, Is.EqualTo(2));
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
}
[TestMethod]
public void WriteInt16_ShouldWriteLittleEndian_GivenLittleEndian()
[Test]
public void WriteLittleEndian_ShouldWriteLittleEndian_GivenInt16Argument()
{
using var stream = new MemoryStream();
stream.Write((short)420, Endianness.LittleEndian);
Assert.AreEqual(2, stream.Position);
stream.WriteLittleEndian((short)420);
Assert.That(stream.Position, Is.EqualTo(2));
stream.Position = 0;
Span<byte> actual = stackalloc byte[2];
ReadOnlySpan<byte> expected = stackalloc byte[] {0xA4, 0x01};
ReadOnlySpan<byte> expected = stackalloc byte[] { 0xA4, 0x01 };
int read = stream.Read(actual);
Assert.AreEqual(2, read);
Assert.That(read, Is.EqualTo(2));
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
}
}

View File

@ -1,68 +1,70 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Diagnostics.CodeAnalysis;
using NUnit.Framework;
using X10D.IO;
namespace X10D.Tests.IO;
public partial class StreamTests
internal partial class StreamTests
{
[TestMethod]
public void WriteInt32_ShouldThrowArgumentException_GivenNonWriteableStream()
{
Stream stream = new DummyStream();
Assert.ThrowsException<ArgumentException>(() => stream.Write(420, Endianness.LittleEndian));
Assert.ThrowsException<ArgumentException>(() => stream.Write(420, Endianness.BigEndian));
}
[TestMethod]
public void WriteInt32_ShouldThrowArgumentNullException_GivenNullStream()
[Test]
public void WriteBigEndian_ShouldThrowArgumentNullException_GivenNullStream_AndInt32Argument()
{
Stream stream = null!;
Assert.ThrowsException<ArgumentNullException>(() => stream.Write(420, Endianness.LittleEndian));
Assert.ThrowsException<ArgumentNullException>(() => stream.Write(420, Endianness.BigEndian));
Assert.Throws<ArgumentNullException>(() => stream.WriteBigEndian(420));
}
[TestMethod]
public void WriteInt32_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue()
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void WriteBigEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndInt32Argument()
{
// we don't need to enclose this stream in a using declaration, since disposing a
// null stream is meaningless. NullStream.Dispose actually does nothing, anyway.
// that - coupled with the fact that encapsulating the stream in a using declaration causes the
// analyser to trip up and think the stream is disposed by the time the local is captured in
// assertion lambda - means this line is fine as it is. please do not change.
Stream stream = Stream.Null;
Assert.ThrowsException<ArgumentOutOfRangeException>(() => stream.Write(420, (Endianness)(-1)));
Assert.ThrowsException<ArgumentOutOfRangeException>(() => stream.Write(420, (Endianness)(-1)));
Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.WriteBigEndian(420));
}
[TestMethod]
public void WriteInt32_ShouldWriteBigEndian_GivenBigEndian()
[Test]
public void WriteLittleEndian_ShouldThrowArgumentNullException_GivenNullStream_AndInt32Argument()
{
Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.WriteLittleEndian(420));
}
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void WriteLittleEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndInt32Argument()
{
Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.WriteLittleEndian(420));
}
[Test]
public void WriteBigEndian_ShouldWriteBigEndian_GivenInt32Argument()
{
using var stream = new MemoryStream();
stream.Write(420, Endianness.BigEndian);
Assert.AreEqual(4, stream.Position);
stream.WriteBigEndian(420);
Assert.That(stream.Position, Is.EqualTo(4));
stream.Position = 0;
Span<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);
Assert.AreEqual(4, read);
Assert.That(read, Is.EqualTo(4));
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
}
[TestMethod]
public void WriteInt32_ShouldWriteLittleEndian_GivenLittleEndian()
[Test]
public void WriteLittleEndian_ShouldWriteLittleEndian_GivenInt32Argument()
{
using var stream = new MemoryStream();
stream.Write(420, Endianness.LittleEndian);
Assert.AreEqual(4, stream.Position);
stream.WriteLittleEndian(420);
Assert.That(stream.Position, Is.EqualTo(4));
stream.Position = 0;
Span<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);
Assert.AreEqual(4, read);
Assert.That(read, Is.EqualTo(4));
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
}
}

View File

@ -1,68 +1,70 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Diagnostics.CodeAnalysis;
using NUnit.Framework;
using X10D.IO;
namespace X10D.Tests.IO;
public partial class StreamTests
internal partial class StreamTests
{
[TestMethod]
public void WriteInt64_ShouldThrowArgumentException_GivenNonWriteableStream()
{
Stream stream = new DummyStream();
Assert.ThrowsException<ArgumentException>(() => stream.Write(420L, Endianness.LittleEndian));
Assert.ThrowsException<ArgumentException>(() => stream.Write(420L, Endianness.BigEndian));
}
[TestMethod]
public void WriteInt64_ShouldThrowArgumentNullException_GivenNullStream()
[Test]
public void WriteBigEndian_ShouldThrowArgumentNullException_GivenNullStream_AndInt64Argument()
{
Stream stream = null!;
Assert.ThrowsException<ArgumentNullException>(() => stream.Write(420L, Endianness.LittleEndian));
Assert.ThrowsException<ArgumentNullException>(() => stream.Write(420L, Endianness.BigEndian));
Assert.Throws<ArgumentNullException>(() => stream.WriteBigEndian(420L));
}
[TestMethod]
public void WriteInt64_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue()
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void WriteBigEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndInt64Argument()
{
// we don't need to enclose this stream in a using declaration, since disposing a
// null stream is meaningless. NullStream.Dispose actually does nothing, anyway.
// that - coupled with the fact that encapsulating the stream in a using declaration causes the
// analyser to trip up and think the stream is disposed by the time the local is captured in
// assertion lambda - means this line is fine as it is. please do not change.
Stream stream = Stream.Null;
Assert.ThrowsException<ArgumentOutOfRangeException>(() => stream.Write(420L, (Endianness)(-1)));
Assert.ThrowsException<ArgumentOutOfRangeException>(() => stream.Write(420L, (Endianness)(-1)));
Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.WriteBigEndian(420L));
}
[TestMethod]
public void WriteInt64_ShouldWriteBigEndian_GivenBigEndian()
[Test]
public void WriteLittleEndian_ShouldThrowArgumentNullException_GivenNullStream_AndInt64Argument()
{
Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.WriteLittleEndian(420L));
}
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void WriteLittleEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndInt64Argument()
{
Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.WriteLittleEndian(420L));
}
[Test]
public void WriteBigEndian_ShouldWriteBigEndian_GivenInt64Argument()
{
using var stream = new MemoryStream();
stream.Write(420L, Endianness.BigEndian);
Assert.AreEqual(8, stream.Position);
stream.WriteBigEndian(420L);
Assert.That(stream.Position, Is.EqualTo(8));
stream.Position = 0;
Span<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);
Assert.AreEqual(8, read);
Assert.That(read, Is.EqualTo(8));
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
}
[TestMethod]
public void WriteInt64_ShouldWriteLittleEndian_GivenLittleEndian()
[Test]
public void WriteLittleEndian_ShouldWriteLittleEndian_GivenLittleEndian()
{
using var stream = new MemoryStream();
stream.Write(420L, Endianness.LittleEndian);
Assert.AreEqual(8, stream.Position);
stream.WriteLittleEndian(420L);
Assert.That(stream.Position, Is.EqualTo(8));
stream.Position = 0;
Span<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);
Assert.AreEqual(8, read);
Assert.That(read, Is.EqualTo(8));
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
}
}

View File

@ -1,68 +1,70 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Diagnostics.CodeAnalysis;
using NUnit.Framework;
using X10D.IO;
namespace X10D.Tests.IO;
public partial class StreamTests
internal partial class StreamTests
{
[TestMethod]
public void WriteSingle_ShouldThrowArgumentException_GivenNonWriteableStream()
{
Stream stream = new DummyStream();
Assert.ThrowsException<ArgumentException>(() => stream.Write(420.0f, Endianness.LittleEndian));
Assert.ThrowsException<ArgumentException>(() => stream.Write(420.0f, Endianness.BigEndian));
}
[TestMethod]
public void WriteSingle_ShouldThrowArgumentNullException_GivenNullStream()
[Test]
public void WriteBigEndian_ShouldThrowArgumentNullException_GivenNullStream_AndSingleArgument()
{
Stream stream = null!;
Assert.ThrowsException<ArgumentNullException>(() => stream.Write(420.0f, Endianness.LittleEndian));
Assert.ThrowsException<ArgumentNullException>(() => stream.Write(420.0f, Endianness.BigEndian));
Assert.Throws<ArgumentNullException>(() => stream.WriteBigEndian(420.0f));
}
[TestMethod]
public void WriteSingle_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue()
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void WriteBigEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndSingleArgument()
{
// we don't need to enclose this stream in a using declaration, since disposing a
// null stream is meaningless. NullStream.Dispose actually does nothing, anyway.
// that - coupled with the fact that encapsulating the stream in a using declaration causes the
// analyser to trip up and think the stream is disposed by the time the local is captured in
// assertion lambda - means this line is fine as it is. please do not change.
Stream stream = Stream.Null;
Assert.ThrowsException<ArgumentOutOfRangeException>(() => stream.Write(420.0f, (Endianness)(-1)));
Assert.ThrowsException<ArgumentOutOfRangeException>(() => stream.Write(420.0f, (Endianness)(-1)));
Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.WriteBigEndian(420.0f));
}
[TestMethod]
public void WriteSingle_ShouldWriteBigEndian_GivenBigEndian()
[Test]
public void WriteLittleEndian_ShouldThrowArgumentNullException_GivenNullStream_AndSingleArgument()
{
Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.WriteLittleEndian(420.0f));
}
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void WriteLittleEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndSingleArgument()
{
Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.WriteLittleEndian(420.0f));
}
[Test]
public void WriteBigEndian_ShouldWriteBigEndian_GivenSingleArgument()
{
using var stream = new MemoryStream();
stream.Write(420.0f, Endianness.BigEndian);
Assert.AreEqual(4, stream.Position);
stream.WriteBigEndian(420.0f);
Assert.That(stream.Position, Is.EqualTo(4));
stream.Position = 0;
Span<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);
Assert.AreEqual(4, read);
Assert.That(read, Is.EqualTo(4));
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
}
[TestMethod]
public void WriteSingle_ShouldWriteLittleEndian_GivenLittleEndian()
[Test]
public void WriteLittleEndian_ShouldWriteLittleEndian_GivenSingleArgument()
{
using var stream = new MemoryStream();
stream.Write(420.0f, Endianness.LittleEndian);
Assert.AreEqual(4, stream.Position);
stream.WriteLittleEndian(420.0f);
Assert.That(stream.Position, Is.EqualTo(4));
stream.Position = 0;
Span<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);
Assert.AreEqual(4, read);
Assert.That(read, Is.EqualTo(4));
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
}
}

View File

@ -1,73 +1,70 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Diagnostics.CodeAnalysis;
using NUnit.Framework;
using X10D.IO;
namespace X10D.Tests.IO;
public partial class StreamTests
internal partial class StreamTests
{
[TestMethod]
[CLSCompliant(false)]
public void WriteUInt16_ShouldThrowArgumentException_GivenNonWriteableStream()
{
Stream stream = new DummyStream();
Assert.ThrowsException<ArgumentException>(() => stream.Write((ushort)420, Endianness.LittleEndian));
Assert.ThrowsException<ArgumentException>(() => stream.Write((ushort)420, Endianness.BigEndian));
}
[TestMethod]
[CLSCompliant(false)]
public void WriteUInt16_ShouldThrowArgumentNullException_GivenNullStream()
[Test]
public void WriteBigEndian_ShouldThrowArgumentNullException_GivenNullStream_AndUInt16Argument()
{
Stream stream = null!;
Assert.ThrowsException<ArgumentNullException>(() => stream.Write((ushort)420, Endianness.LittleEndian));
Assert.ThrowsException<ArgumentNullException>(() => stream.Write((ushort)420, Endianness.BigEndian));
Assert.Throws<ArgumentNullException>(() => stream.WriteBigEndian((ushort)420));
}
[TestMethod]
[CLSCompliant(false)]
public void WriteUInt16_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue()
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void WriteBigEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndUInt16Argument()
{
// we don't need to enclose this stream in a using declaration, since disposing a
// null stream is meaningless. NullStream.Dispose actually does nothing, anyway.
// that - coupled with the fact that encapsulating the stream in a using declaration causes the
// analyser to trip up and think the stream is disposed by the time the local is captured in
// assertion lambda - means this line is fine as it is. please do not change.
Stream stream = Stream.Null;
Assert.ThrowsException<ArgumentOutOfRangeException>(() => stream.Write((ushort)420, (Endianness)(-1)));
Assert.ThrowsException<ArgumentOutOfRangeException>(() => stream.Write((ushort)420, (Endianness)(-1)));
Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.WriteBigEndian((ushort)420));
}
[TestMethod]
[CLSCompliant(false)]
public void WriteUInt16_ShouldWriteBigEndian_GivenBigEndian()
[Test]
public void WriteLittleEndian_ShouldThrowArgumentNullException_GivenNullStream_AndUInt16Argument()
{
Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.WriteLittleEndian((ushort)420));
}
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void WriteLittleEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndUInt16Argument()
{
Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.WriteLittleEndian((ushort)420));
}
[Test]
public void WriteBigEndian_ShouldWriteBigEndian_GivenUInt16Endian()
{
using var stream = new MemoryStream();
stream.Write((ushort)420, Endianness.BigEndian);
Assert.AreEqual(2, stream.Position);
stream.WriteBigEndian((ushort)420);
Assert.That(stream.Position, Is.EqualTo(2));
stream.Position = 0;
Span<byte> actual = stackalloc byte[2];
ReadOnlySpan<byte> expected = stackalloc byte[] {0x01, 0xA4};
ReadOnlySpan<byte> expected = stackalloc byte[] { 0x01, 0xA4 };
int read = stream.Read(actual);
Assert.AreEqual(2, read);
Assert.That(read, Is.EqualTo(2));
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
}
[TestMethod]
[CLSCompliant(false)]
public void WriteUInt16_ShouldWriteLittleEndian_GivenLittleEndian()
[Test]
public void WriteLittleEndian_ShouldWriteLittleEndian_GivenUInt16tleEndian()
{
using var stream = new MemoryStream();
stream.Write((ushort)420, Endianness.LittleEndian);
Assert.AreEqual(2, stream.Position);
stream.WriteLittleEndian((ushort)420);
Assert.That(stream.Position, Is.EqualTo(2));
stream.Position = 0;
Span<byte> actual = stackalloc byte[2];
ReadOnlySpan<byte> expected = stackalloc byte[] {0xA4, 0x01};
ReadOnlySpan<byte> expected = stackalloc byte[] { 0xA4, 0x01 };
int read = stream.Read(actual);
Assert.AreEqual(2, read);
Assert.That(read, Is.EqualTo(2));
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
}
}

View File

@ -1,73 +1,70 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Diagnostics.CodeAnalysis;
using NUnit.Framework;
using X10D.IO;
namespace X10D.Tests.IO;
public partial class StreamTests
internal partial class StreamTests
{
[TestMethod]
[CLSCompliant(false)]
public void WriteUInt32_ShouldThrowArgumentException_GivenNonWriteableStream()
{
Stream stream = new DummyStream();
Assert.ThrowsException<ArgumentException>(() => stream.Write(420U, Endianness.LittleEndian));
Assert.ThrowsException<ArgumentException>(() => stream.Write(420U, Endianness.BigEndian));
}
[TestMethod]
[CLSCompliant(false)]
public void WriteUInt32_ShouldThrowArgumentNullException_GivenNullStream()
[Test]
public void WriteBigEndian_ShouldThrowArgumentNullException_GivenNullStream_AndUInt32Argument()
{
Stream stream = null!;
Assert.ThrowsException<ArgumentNullException>(() => stream.Write(420U, Endianness.LittleEndian));
Assert.ThrowsException<ArgumentNullException>(() => stream.Write(420U, Endianness.BigEndian));
Assert.Throws<ArgumentNullException>(() => stream.WriteBigEndian(420U));
}
[TestMethod]
[CLSCompliant(false)]
public void WriteUInt32_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue()
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void WriteBigEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndUInt32Argument()
{
// we don't need to enclose this stream in a using declaration, since disposing a
// null stream is meaningless. NullStream.Dispose actually does nothing, anyway.
// that - coupled with the fact that encapsulating the stream in a using declaration causes the
// analyser to trip up and think the stream is disposed by the time the local is captured in
// assertion lambda - means this line is fine as it is. please do not change.
Stream stream = Stream.Null;
Assert.ThrowsException<ArgumentOutOfRangeException>(() => stream.Write(420U, (Endianness)(-1)));
Assert.ThrowsException<ArgumentOutOfRangeException>(() => stream.Write(420U, (Endianness)(-1)));
Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.WriteBigEndian(420U));
}
[TestMethod]
[CLSCompliant(false)]
public void WriteUInt32_ShouldWriteBigEndian_GivenBigEndian()
[Test]
public void WriteLittleEndian_ShouldThrowArgumentNullException_GivenNullStream_AndUInt32Argument()
{
Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.WriteLittleEndian(420U));
}
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void WriteLittleEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndUInt32Argument()
{
Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.WriteLittleEndian(420U));
}
[Test]
public void WriteBigEndian_ShouldWriteBigEndian_GivenUInt32Argument()
{
using var stream = new MemoryStream();
stream.Write(420U, Endianness.BigEndian);
Assert.AreEqual(4, stream.Position);
stream.WriteBigEndian(420U);
Assert.That(stream.Position, Is.EqualTo(4));
stream.Position = 0;
Span<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);
Assert.AreEqual(4, read);
Assert.That(read, Is.EqualTo(4));
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
}
[TestMethod]
[CLSCompliant(false)]
public void WriteUInt32_ShouldWriteLittleEndian_GivenLittleEndian()
[Test]
public void WriteLittleEndian_ShouldWriteLittleEndian_GivenUInt32Argument()
{
using var stream = new MemoryStream();
stream.Write(420U, Endianness.LittleEndian);
Assert.AreEqual(4, stream.Position);
stream.WriteLittleEndian(420U);
Assert.That(stream.Position, Is.EqualTo(4));
stream.Position = 0;
Span<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);
Assert.AreEqual(4, read);
Assert.That(read, Is.EqualTo(4));
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
}
}

View File

@ -1,73 +1,70 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Diagnostics.CodeAnalysis;
using NUnit.Framework;
using X10D.IO;
namespace X10D.Tests.IO;
public partial class StreamTests
internal partial class StreamTests
{
[TestMethod]
[CLSCompliant(false)]
public void WriteUInt64_ShouldThrowArgumentException_GivenNonWriteableStream()
{
Stream stream = new DummyStream();
Assert.ThrowsException<ArgumentException>(() => stream.Write(420UL, Endianness.LittleEndian));
Assert.ThrowsException<ArgumentException>(() => stream.Write(420UL, Endianness.BigEndian));
}
[TestMethod]
[CLSCompliant(false)]
public void WriteUInt64_ShouldThrowArgumentNullException_GivenNullStream()
[Test]
public void WriteBigEndian_ShouldThrowArgumentNullException_GivenNullStream_AndUInt64Argument()
{
Stream stream = null!;
Assert.ThrowsException<ArgumentNullException>(() => stream.Write(420UL, Endianness.LittleEndian));
Assert.ThrowsException<ArgumentNullException>(() => stream.Write(420UL, Endianness.BigEndian));
Assert.Throws<ArgumentNullException>(() => stream.WriteBigEndian(420UL));
}
[TestMethod]
[CLSCompliant(false)]
public void WriteUInt64_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue()
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void WriteBigEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndUInt64Argument()
{
// we don't need to enclose this stream in a using declaration, since disposing a
// null stream is meaningless. NullStream.Dispose actually does nothing, anyway.
// that - coupled with the fact that encapsulating the stream in a using declaration causes the
// analyser to trip up and think the stream is disposed by the time the local is captured in
// assertion lambda - means this line is fine as it is. please do not change.
Stream stream = Stream.Null;
Assert.ThrowsException<ArgumentOutOfRangeException>(() => stream.Write(420UL, (Endianness)(-1)));
Assert.ThrowsException<ArgumentOutOfRangeException>(() => stream.Write(420UL, (Endianness)(-1)));
Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.WriteBigEndian(420UL));
}
[TestMethod]
[CLSCompliant(false)]
public void WriteUInt64_ShouldWriteBigEndian_GivenBigEndian()
[Test]
public void WriteLittleEndian_ShouldThrowArgumentNullException_GivenNullStream_AndUInt64Argument()
{
Stream stream = null!;
Assert.Throws<ArgumentNullException>(() => stream.WriteLittleEndian(420UL));
}
[Test]
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void WriteLittleEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndUInt64Argument()
{
Stream stream = new DummyStream();
Assert.Throws<ArgumentException>(() => stream.WriteLittleEndian(420UL));
}
[Test]
public void WriteBigEndian_ShouldWriteBigEndian_GivenUInt64Argument()
{
using var stream = new MemoryStream();
stream.Write(420UL, Endianness.BigEndian);
Assert.AreEqual(8, stream.Position);
stream.WriteBigEndian(420UL);
Assert.That(stream.Position, Is.EqualTo(8));
stream.Position = 0;
Span<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);
Assert.AreEqual(8, read);
Assert.That(read, Is.EqualTo(8));
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
}
[TestMethod]
[CLSCompliant(false)]
public void WriteUInt64_ShouldWriteLittleEndian_GivenLittleEndian()
[Test]
public void WriteLittleEndian_ShouldWriteLittleEndian_GivenUInt64Argument()
{
using var stream = new MemoryStream();
stream.Write(420UL, Endianness.LittleEndian);
Assert.AreEqual(8, stream.Position);
stream.WriteLittleEndian(420UL);
Assert.That(stream.Position, Is.EqualTo(8));
stream.Position = 0;
Span<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);
Assert.AreEqual(8, read);
Assert.That(read, Is.EqualTo(8));
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
}
}

View File

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

View File

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

View File

@ -0,0 +1,131 @@
using System.Globalization;
using System.Text;
using NUnit.Framework;
using X10D.IO;
namespace X10D.Tests.IO;
internal partial class TextWriterTests
{
[Test]
public void WriteNoAlloc_ShouldThrowArgumentNullException_GivenDouble_AndNullWriter()
{
TextWriter writer = null!;
Assert.Throws<ArgumentNullException>(() => writer.WriteNoAlloc(420.0));
Assert.Throws<ArgumentNullException>(() => writer.WriteNoAlloc(420.0, "N0"));
Assert.Throws<ArgumentNullException>(() => writer.WriteNoAlloc(420.0, "N0", null));
}
[Test]
public void WriteNoAlloc_ShouldThrowObjectDisposedException_GivenDouble_AndDisposedStream()
{
var stream = new MemoryStream();
var writer = new StreamWriter(stream, Encoding.UTF8);
writer.Dispose();
stream.Dispose();
Assert.Throws<ObjectDisposedException>(() => writer.WriteNoAlloc(420.0));
Assert.Throws<ObjectDisposedException>(() => writer.WriteNoAlloc(420.0, "N0"));
Assert.Throws<ObjectDisposedException>(() => writer.WriteNoAlloc(420.0, "N0", null));
}
[Test]
public void WriteLineNoAlloc_ShouldThrowArgumentNullException_GivenDouble_AndNullWriter()
{
TextWriter writer = null!;
Assert.Throws<ArgumentNullException>(() => writer.WriteLineNoAlloc(420.0));
Assert.Throws<ArgumentNullException>(() => writer.WriteLineNoAlloc(420.0, "N0"));
Assert.Throws<ArgumentNullException>(() => writer.WriteLineNoAlloc(420.0, "N0", null));
}
[Test]
public void WriteLineNoAlloc_ShouldThrowObjectDisposedException_GivenDouble_AndDisposedStream()
{
var stream = new MemoryStream();
var writer = new StreamWriter(stream, Encoding.UTF8);
writer.Dispose();
stream.Dispose();
Assert.Throws<ObjectDisposedException>(() => writer.WriteLineNoAlloc(420.0));
Assert.Throws<ObjectDisposedException>(() => writer.WriteLineNoAlloc(420.0, "N0"));
Assert.Throws<ObjectDisposedException>(() => writer.WriteLineNoAlloc(420.0, "N0", null));
}
[Test]
public void WriteNoAlloc_ShouldWriteTextValue_GivenDouble()
{
Assert.That(_stream.Length, Is.Zero);
_writer.WriteNoAlloc(420.0);
_writer.Flush();
string actual = Encoding.UTF8.GetString(_stream.ToArray());
const string expected = "420";
Assert.That(actual, Is.EqualTo(expected));
}
[Test]
public void WriteNoAlloc_ShouldWriteTextValue_GivenDouble_AndFormatString()
{
Assert.That(_stream.Length, Is.Zero);
_writer.WriteNoAlloc(420.0, "N0");
_writer.Flush();
string actual = Encoding.UTF8.GetString(_stream.ToArray());
const string expected = "420";
Assert.That(actual, Is.EqualTo(expected));
}
[Test]
public void WriteNoAlloc_ShouldWriteTextValue_GivenDouble_AndFormatString_AndCultureInfo()
{
Assert.That(_stream.Length, Is.Zero);
_writer.WriteNoAlloc(420.0, "N0", CultureInfo.CurrentCulture);
_writer.Flush();
string actual = Encoding.UTF8.GetString(_stream.ToArray());
const string expected = "420";
Assert.That(actual, Is.EqualTo(expected));
}
[Test]
public void WriteLineNoAlloc_ShouldWriteTextValue_GivenDouble()
{
Assert.That(_stream.Length, Is.Zero);
_writer.WriteLineNoAlloc(420.0);
_writer.Flush();
string actual = Encoding.UTF8.GetString(_stream.ToArray());
var expected = $"420{Environment.NewLine}";
Assert.That(actual, Is.EqualTo(expected));
}
[Test]
public void WriteLineNoAlloc_ShouldWriteTextValue_GivenDouble_AndFormatString()
{
Assert.That(_stream.Length, Is.Zero);
_writer.WriteLineNoAlloc(420.0, "N0");
_writer.Flush();
string actual = Encoding.UTF8.GetString(_stream.ToArray());
var expected = $"420{Environment.NewLine}";
Assert.That(actual, Is.EqualTo(expected));
}
[Test]
public void WriteLineNoAlloc_ShouldWriteTextValue_GivenDouble_AndFormatString_AndCultureInfo()
{
Assert.That(_stream.Length, Is.Zero);
_writer.WriteLineNoAlloc(420.0, "N0", CultureInfo.CurrentCulture);
_writer.Flush();
string actual = Encoding.UTF8.GetString(_stream.ToArray());
var expected = $"420{Environment.NewLine}";
Assert.That(actual, Is.EqualTo(expected));
}
}

View File

@ -0,0 +1,131 @@
using System.Globalization;
using System.Text;
using NUnit.Framework;
using X10D.IO;
namespace X10D.Tests.IO;
internal partial class TextWriterTests
{
[Test]
public void WriteNoAlloc_ShouldThrowArgumentNullException_GivenInt32_AndNullWriter()
{
TextWriter writer = null!;
Assert.Throws<ArgumentNullException>(() => writer.WriteNoAlloc(420));
Assert.Throws<ArgumentNullException>(() => writer.WriteNoAlloc(420, "N0"));
Assert.Throws<ArgumentNullException>(() => writer.WriteNoAlloc(420, "N0", null));
}
[Test]
public void WriteNoAlloc_ShouldThrowObjectDisposedException_GivenInt32_AndDisposedStream()
{
var stream = new MemoryStream();
var writer = new StreamWriter(stream, Encoding.UTF8);
writer.Dispose();
stream.Dispose();
Assert.Throws<ObjectDisposedException>(() => writer.WriteNoAlloc(420));
Assert.Throws<ObjectDisposedException>(() => writer.WriteNoAlloc(420, "N0"));
Assert.Throws<ObjectDisposedException>(() => writer.WriteNoAlloc(420, "N0", null));
}
[Test]
public void WriteLineNoAlloc_ShouldThrowArgumentNullException_GivenInt32_AndNullWriter()
{
TextWriter writer = null!;
Assert.Throws<ArgumentNullException>(() => writer.WriteLineNoAlloc(420));
Assert.Throws<ArgumentNullException>(() => writer.WriteLineNoAlloc(420, "N0"));
Assert.Throws<ArgumentNullException>(() => writer.WriteLineNoAlloc(420, "N0", null));
}
[Test]
public void WriteLineNoAlloc_ShouldThrowObjectDisposedException_GivenInt32_AndDisposedStream()
{
var stream = new MemoryStream();
var writer = new StreamWriter(stream, Encoding.UTF8);
writer.Dispose();
stream.Dispose();
Assert.Throws<ObjectDisposedException>(() => writer.WriteLineNoAlloc(420));
Assert.Throws<ObjectDisposedException>(() => writer.WriteLineNoAlloc(420, "N0"));
Assert.Throws<ObjectDisposedException>(() => writer.WriteLineNoAlloc(420, "N0", null));
}
[Test]
public void WriteNoAlloc_ShouldWriteTextValue_GivenInt32()
{
Assert.That(_stream.Length, Is.Zero);
_writer.WriteNoAlloc(420);
_writer.Flush();
string actual = Encoding.UTF8.GetString(_stream.ToArray());
const string expected = "420";
Assert.That(actual, Is.EqualTo(expected));
}
[Test]
public void WriteNoAlloc_ShouldWriteTextValue_GivenInt32_AndFormatString()
{
Assert.That(_stream.Length, Is.Zero);
_writer.WriteNoAlloc(420, "N0");
_writer.Flush();
string actual = Encoding.UTF8.GetString(_stream.ToArray());
const string expected = "420";
Assert.That(actual, Is.EqualTo(expected));
}
[Test]
public void WriteNoAlloc_ShouldWriteTextValue_GivenInt32_AndFormatString_AndCultureInfo()
{
Assert.That(_stream.Length, Is.Zero);
_writer.WriteNoAlloc(420, "N0", CultureInfo.CurrentCulture);
_writer.Flush();
string actual = Encoding.UTF8.GetString(_stream.ToArray());
const string expected = "420";
Assert.That(actual, Is.EqualTo(expected));
}
[Test]
public void WriteLineNoAlloc_ShouldWriteTextValue_GivenInt32()
{
Assert.That(_stream.Length, Is.Zero);
_writer.WriteLineNoAlloc(420);
_writer.Flush();
string actual = Encoding.UTF8.GetString(_stream.ToArray());
var expected = $"420{Environment.NewLine}";
Assert.That(actual, Is.EqualTo(expected));
}
[Test]
public void WriteLineNoAlloc_ShouldWriteTextValue_GivenInt32_AndFormatString()
{
Assert.That(_stream.Length, Is.Zero);
_writer.WriteLineNoAlloc(420, "N0");
_writer.Flush();
string actual = Encoding.UTF8.GetString(_stream.ToArray());
var expected = $"420{Environment.NewLine}";
Assert.That(actual, Is.EqualTo(expected));
}
[Test]
public void WriteLineNoAlloc_ShouldWriteTextValue_GivenInt32_AndFormatString_AndCultureInfo()
{
Assert.That(_stream.Length, Is.Zero);
_writer.WriteLineNoAlloc(420, "N0", CultureInfo.CurrentCulture);
_writer.Flush();
string actual = Encoding.UTF8.GetString(_stream.ToArray());
var expected = $"420{Environment.NewLine}";
Assert.That(actual, Is.EqualTo(expected));
}
}

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