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

Compare commits

..

129 Commits

Author SHA1 Message Date
423fb90cc4
feat: add IBinaryInteger<T>.CountDigits 2023-08-25 02:34:55 +01:00
8bc7372ba4
Merge branch 'release/4.0.0' into feature/generic_math 2023-08-25 02:27:08 +01:00
129cbfb51f
refactor: revert 50d9cad2f3 2023-08-24 02:29:59 +01:00
f238d420f4
Merge branch 'main' into release/4.0.0 2023-08-24 01:54:42 +01:00
5ff7b68b37
[ci skip] ci: add workflow_dispatch trigger to docfx workflow 2023-08-24 01:54:25 +01:00
9aed06b533
[ci skip] docs: add X10D.Hosting to docfx project 2023-08-24 01:53:50 +01:00
71b0bec85c
style(test): format span tests 2023-08-24 01:53:24 +01:00
50d9cad2f3
perf: optimise subsequent GetHash and TryWriteHash calls 2023-08-23 17:06:44 +01:00
1157e36eff
refactor: separate stream Read/Write methods to partials 2023-08-23 17:00:55 +01:00
30b7a465a7
fix: fix marshal of decimal for netstandard 2.1 2023-08-23 16:54:20 +01:00
caa0070458
fix: fix incorrect endian swap 2023-08-23 16:43:33 +01:00
ed46bcd0d8
Merge branch 'main' into release/4.0.0 2023-08-23 16:15:21 +01:00
3e338eb2f5
fix(ci): build on subdir branch push 2023-08-23 16:15:10 +01:00
d90e949212
fix(ci): build on subdir branch push 2023-08-23 16:14:56 +01:00
28d7bee262
fix(tests): add support for trace logging during tests 2023-08-23 14:18:04 +01:00
0bf89bb82a
refactor!: change exception thrown by GetHash and TryWriteHash
The methods no longer throw TypeInitializationException, and instead now throw ArgumentException.
2023-08-23 14:17:42 +01:00
5c21c86a52
refactor!: replace Endianness enum with explicit Big/Little methods 2023-08-23 14:15:52 +01:00
15107ea90f
docs: fix xmldoc for Line3D 2023-08-22 23:53:13 +01:00
fa375e7758
refactor: conditionally import System.Runtime.Intrinsics.X86 2023-08-22 23:38:18 +01:00
b4ae55caaa
Merge branch 'main' into release/4.0.0 2023-08-22 23:27:35 +01:00
f57318a381
[ci skip] fix(docs): fix incorrect stable commit ref 2023-08-22 23:27:26 +01:00
c5f5ba9bb6
Merge branch 'main' into release/4.0.0 2023-08-22 23:25:33 +01:00
bf0930ee17
[ci skip] docs: update latest stable ref in X10D.Unity readme 2023-08-22 23:25:10 +01:00
457fbbb83c
[ci skip] docs: fix README branding header in X10D.Unity 2023-08-22 22:42:23 +01:00
0868b698c5
[ci skip] docs: fix README branding header in X10D.Unity 2023-08-22 22:42:07 +01:00
9c5ed12cad
chore: enable NRT for tools 2023-08-22 22:40:59 +01:00
5b2c83e2eb
chore: define TargetFrameworks in shared props 2023-08-22 22:40:49 +01:00
1e71029f38
refactor: remove X10D.DSharpPlus 2023-08-22 17:52:49 +01:00
27e0ec54be
chore: extract shared build props 2023-08-22 17:46:44 +01:00
1b71d94084
chore: remove redundant shared props 2023-08-22 17:44:29 +01:00
4593a21065
fix(tools): clear Package property groups 2023-08-22 17:43:16 +01:00
d17d94a8c1
chore: suppress NU1701 (#77) 2023-08-22 17:39:45 +01:00
24a7de7e8c
refactor: define test fixtures as internal 2023-08-22 17:32:47 +01:00
e8a331ff96
chore: use shared Build.props for all projects 2023-08-22 17:11:20 +01:00
a9cde347bd
[ci skip] docs: bump to 3.3.1 2023-08-21 17:42:59 +01:00
a14fe4ca64
Merge branch 'main' into release/4.0.0 2023-08-21 17:41:05 +01:00
71a9c787e2
Merge branch 'hotfix/3.3.1' into main 2023-08-21 17:39:56 +01:00
42cb9acb48
fix: fix AddHostedSingleton not accepting interface as service type 2023-08-21 17:39:35 +01:00
0afe45f4d6
chore: bump to 3.3.1 2023-08-21 17:39:28 +01:00
4c6ea59e2f
Merge branch 'main' into release/4.0.0 2023-08-21 17:28:32 +01:00
70cb1b7230
Merge branch 'release/3.3.0' into main 2023-08-21 17:26:01 +01:00
22532e8cef
feat: add service/impl register for AddHostedSingleton 2023-08-21 17:25:41 +01:00
a715384e98
chore: bump to 3.3.0 2023-08-21 17:23:27 +01:00
9b995524dd
feat: add service/impl register for AddHostedSingleton 2023-08-21 17:21:58 +01:00
b977b7a4ec
Merge branch 'main' into release/4.0.0 2023-08-09 15:24:33 +01:00
a0b07edc82
fix: replace Moq with a library that DOESN'T steal your pii
Moq has recently introduced a payload named SponsorLink which takes PII (your email address) to send to a third party server for remote verification.

This kind of suspicious data harvesting is simply unacceptable, and the developers have now destroyed all credibility and trust with their user base. This change replaces Moq with NSubstitute.

For further information, see:
https://github.com/moq/moq/issues/1372
2023-08-09 15:18:01 +01:00
7b844bd703
Merge branch 'release/3.2.2' into main 2023-06-05 21:50:03 +01:00
1a2f92c700
docs: update version in README 2023-06-05 21:47:42 +01:00
678dd914d4
feat: add support for new usernames
user discriminators become "0" if the user has a new username, distinct from "0000" for webhooks.
2023-06-05 21:47:24 +01:00
103e037dc8
docs: update changelog 2023-06-05 21:47:04 +01:00
f84fc044ba
chore: bump to 3.2.2 2023-06-05 21:46:51 +01:00
455b324071
feat: add support for new usernames
user discriminators become "0" if the user has a new username, distinct from "0000" for webhooks.
2023-06-05 21:38:09 +01:00
7222bbb496
Merge branch 'release/3.2.1' into main 2023-06-05 21:35:12 +01:00
35073d9c85
chore: bump to 3.2.1 2023-06-05 21:34:54 +01:00
8d7ca6ea0a
fix(tests): remove outdated tests
This should have been part of d8be858359
2023-05-14 16:31:57 +01:00
d8be858359
refactor: remove IEnumerable.ConcatOne 2023-05-14 16:27:42 +01:00
23dee3d2b8
feat: add value-passthru overloads for ConcatIf 2023-04-14 14:17:33 +01:00
6f3a667e37
feat: add string.ConcatIf 2023-04-14 13:55:52 +01:00
63e2f7b69e
Merge branch 'main' into release/4.0.0 2023-04-13 23:27:53 +01:00
334c64e995
[ci skip] ci: add workflow_dispatch trigger to nightly workflow 2023-04-13 23:27:08 +01:00
545994389d
[ci skip] ci: run dotnet and unity workflows from all branches 2023-04-13 23:26:54 +01:00
21907aef83
Merge branch 'main' into release/4.0.0 2023-04-13 23:15:16 +01:00
dbc63b9b26
[ci skip] docs: bump version in README 2023-04-13 23:14:32 +01:00
Oliver Booth
ccef1cd269
Merge pull request #81 from oliverbooth/dev/remove_throwhelpers
Remove throw helpers (resolves #80)
2023-04-13 23:12:04 +01:00
bb3659c047
refactor: remove throw helpers (#80) 2023-04-13 22:52:46 +01:00
3b5fb7b2be
refactor: remove throw helpers in X10D.DSharpPlus (#80) 2023-04-13 22:35:43 +01:00
a0d70eaa35
[ci skip] ci: add workflows for push to any branch 2023-04-13 21:55:38 +01:00
1c58403708
[ci skip] ci: add workflow_dispatch trigger for sonarcloud 2023-04-13 21:55:38 +01:00
Oliver Booth
b5f4c16266
[ci skip] update bug-report.yml
Adds 3.2.0 and "nightly/other" to version options.
2023-04-13 21:39:00 +01:00
af6534d23d
Merge branch 'develop' into main 2023-04-13 20:55:57 +01:00
0ae377250c
feat: add IEnumerable<T>.Except(T)
LINQ-provided Except method filters by array, but there's no way to filter a single value. This method introduces single-value filtering.
2023-04-13 20:55:24 +01:00
847af30945
docs: properly document ArgumentNullException 2023-04-13 20:54:07 +01:00
a07cc4118a
Merge branch 'main' into develop 2023-04-13 02:38:39 +01:00
a23be6dd77
[ci skip] fix(ci): mkdir docfx_project/images 2023-04-13 02:38:17 +01:00
4639fbd6a4
Merge branch 'develop' into main 2023-04-13 02:36:04 +01:00
25ef4e68ef
fix(docs): fix cp source (+g. oops) 2023-04-13 02:35:44 +01:00
3bd69dfa36
Merge branch 'develop' into main 2023-04-13 02:33:29 +01:00
2f5d1aee4c
docs: add favicon and app title to docfx project 2023-04-13 02:31:21 +01:00
1be3f75538
docs: add initial docfx intro 2023-04-13 02:27:35 +01:00
3655e33a9c
chore(test): update test project to 2021.3.22f1
ref b6c551784ba3
2023-04-13 01:50:26 +01:00
3f08f5270f
feat: add DebugUtility.DrawFunction 2023-04-13 01:48:58 +01:00
9b4ef5abb6
Merge branch 'develop' into main 2023-04-12 12:47:53 +01:00
c5ea6cca58
[ci skip] docs: add conventional commit to contrib guidelines 2023-04-12 12:47:32 +01:00
b8a63c0d5c
feat: add float/double support for WriteNoAlloc and WriteLineNoAlloc 2023-04-11 22:27:31 +01:00
f13907a4d0
style: move Write/WriteLine overloads to files
This change should help to organise this entire class a bit better, due to the number of overloads that exist.
2023-04-11 22:23:12 +01:00
e6025b1a4c
fix: validate null arguments in X10D.Unity
The CA runs are really testing me today.
2023-04-11 17:09:14 +01:00
2e9f27b6b7
fix: validate null arguments for Polygon and PolygonF extensions 2023-04-11 17:05:58 +01:00
5ff521073c
fix: suppress CA5394
This analysis warning is irrelevant. We're making extension methods here, dammit! This will be the consumer's responsibility to worry about.
2023-04-11 17:04:09 +01:00
ac499537ed
feat: add RaycastHit.GetComponent and RaycastHit.TryGetComponent 2023-04-11 16:58:16 +01:00
b70b704b63
Merge branch 'develop' into main 2023-04-10 13:54:05 +01:00
b2e4092ca7
[ci skip] docs: remove addition of component copy/move 2023-04-10 13:50:44 +01:00
98cd96d5cb
fix(test): fix malformed test
The child was not being assigned a new parent, causing GetComponentsInChildrenOnly to return empty array and the subsequent line:

Assert.That(components, Has.Length.EqualTo(1));

was resulting in a test fail.
2023-04-10 13:45:39 +01:00
f4d6c9083b
refactor(test): remove lingering IEnumerator test
Remant from 0b5bb074c8
2023-04-10 13:44:37 +01:00
a8ebe9c902
fix: fix issue with GetComponentsInChildrenOnly checking wrong Transform 2023-04-10 13:42:12 +01:00
0b5bb074c8
refactor(test): remove IEnumerator tests
Use synchronous NUnit tests
2023-04-10 13:38:56 +01:00
77ab429f72
refactor: remove Copy/Move component functionality
This may be returned at a later point.
2023-04-10 13:26:38 +01:00
844f697754
style: remove unused using directives 2023-04-10 12:45:18 +01:00
f6847315a1
feat: add Progress<T>.OnProgressChanged
Provides a mechanism to wrap the ProgressChanged event of a Progress<T> as an IObservable<T>.
2023-04-10 12:44:53 +01:00
a4a1d3b13a
fix: only copy Unity-serialized members 2023-04-07 13:09:07 +01:00
ad2d33aa88
style(test): use constraint API for length check 2023-04-07 01:34:34 +01:00
dc6d984fa8
test: suppress ReSharper.Unity.InefficientPropertyAccess
This is false positive being thrown by the analyzer. The values are - in fact - changing before being read each time.
2023-04-07 01:34:08 +01:00
420ec2433a
feat: add Component move/copy
As usual, experimental API - subject to change.
2023-04-07 01:21:56 +01:00
1fe2a26b7f
Merge branch 'develop' into main 2023-04-06 19:23:58 +01:00
75ac9e2d8f
chore: add MetaServices to sln 2023-04-06 19:22:27 +01:00
57ff32ee94
[ci skip] docs: add comment explaining my absolute pain 2023-04-06 19:18:20 +01:00
9d26f3da60
feat: add TextWriter.WriteNoAlloc/WriteLineNoAlloc
Allows writing of integer types without allocating a string.
2023-04-06 19:11:54 +01:00
ce35f8676e
chore: make attributes internal 2023-04-06 17:05:37 +01:00
7556efdfdd
chore: add AutoOverload and OverloadType attribute 2023-04-06 17:00:39 +01:00
172380c57d
[ci skip] chore: add meta services
This class library will contain attributes for future source generation.
2023-04-06 16:58:38 +01:00
0ca8253402
chore: remove X10D prefix from sourcegen 2023-04-06 16:05:02 +01:00
5289bd2595
chore: move SourceGenerator to tools folder 2023-04-06 16:03:20 +01:00
9791fd23bb
feat: add CountDigit for integer types 2023-04-06 14:40:27 +01:00
71b4ac5337
Merge branch 'develop' into main 2023-04-06 02:32:01 +01:00
0621c246a0
feat: add Span<T>.Replace 2023-04-06 02:31:22 +01:00
bafc327ee6
chore: add benchmarks project 2023-04-06 02:30:17 +01:00
8e6796607c
docs: explain use of ref return 2023-04-05 23:19:08 +01:00
4a0e3c10d7
test: return coverage to 100% (#76) 2023-04-05 23:18:14 +01:00
fcdcf54aa3
test: use NUnit constraint API in X10D.Unity.Tests (#76) 2023-04-05 22:51:59 +01:00
744f5e906b
test: remove redundant quality checks (#76) 2023-04-05 22:51:59 +01:00
dbeb13efcd
test: fix expected/actual value swap (#76) 2023-04-05 22:51:59 +01:00
ab62db2b37
chore: switch from MSTest to NUnit (#76) 2023-04-05 22:51:59 +01:00
5d2313fa20
test: replace playmode tests with NUnit tests (#76)
Using yield break; in a coroutine which does not need to be one, that's a paddlin'.
2023-04-05 22:51:59 +01:00
e84eef60e6
chore: suppress tfm support build warnings 2023-04-05 17:37:26 +01:00
b819e6a418
refactor: revert 47f3a138aa
Generic math features will be built in a feature branch to avoid merge conflicts with develop.
2023-04-05 15:13:21 +01:00
47f3a138aa
feat: add Unpack for IBinaryInteger<T>
This introduces an experiment, to add support for generic math in X10D. So far, build and tests remain passing - this is a good sign. There is potential here.

This API is subject to change and may be removed without warning.
2023-04-05 15:06:02 +01:00
65d8242f5c
Merge branch 'develop' into main 2023-04-05 11:09:30 +01:00
d09ea69e13
[ci skip] docs: update upm stable in README 2023-04-04 21:25:56 +01:00
3fede7e107
[ci skip] merge branch 'develop' into main 2023-04-03 18:12:40 +01:00
Oliver Booth
7ff391a52e
Merge pull request #68 from oliverbooth/develop
3.2.0 update
2023-04-03 17:51:01 +01:00
329 changed files with 13244 additions and 10916 deletions

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -8,11 +8,64 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## 4.0.0 - [Unreleased] ## 4.0.0 - [Unreleased]
### Added ### Added
- X10D: Added extension methods for `DateOnly`, for parity with `DateTime` and `DateTimeOffset`. - X10D: Added extension methods for `DateOnly`, for parity with `DateTime` and `DateTimeOffset`.
- X10D: Added math-related extension methods for `BigInteger`. - X10D: Added math-related extension methods for `BigInteger`.
- X10D: Added `Span<T>.Replace(T, T)`.
- X10D: Added `CountDigits` for integer types.
- X10D: Added `IEnumerable<T>.Except(T)`.
- X10D: Added `Progress<T>.OnProgressChanged([T])`.
- X10D: Added `TextWriter.WriteNoAlloc(int[, ReadOnlySpan<char>[, IFormatProvider]])`.
- X10D: Added `TextWriter.WriteNoAlloc(uint[, ReadOnlySpan<char>[, IFormatProvider]])`.
- X10D: Added `TextWriter.WriteNoAlloc(long[, ReadOnlySpan<char>[, IFormatProvider]])`.
- X10D: Added `TextWriter.WriteNoAlloc(ulong[, ReadOnlySpan<char>[, IFormatProvider]])`.
- X10D: Added `TextWriter.WriteLineNoAlloc(int[, ReadOnlySpan<char>[, IFormatProvider]])`.
- X10D: Added `TextWriter.WriteLineNoAlloc(uint[, ReadOnlySpan<char>[, IFormatProvider]])`.
- X10D: Added `TextWriter.WriteLineNoAlloc(long[, ReadOnlySpan<char>[, IFormatProvider]])`.
- X10D: Added `TextWriter.WriteLineNoAlloc(ulong[, ReadOnlySpan<char>[, IFormatProvider]])`.
- X10D: Added `string.ConcatIf`.
- X10D.Unity: Added `RaycastHit.GetComponent` and `RaycastHit.TryGetComponent`.
- X10D.Unity: Added `DebugUtility.DrawFunction`, and `DebugUtility.DrawUnjoinedPolyhedron` on which it relies.
### Fixed
- X10D: Fixed XMLDoc for `Line3D` to read "single-precision floating-point" instead of "32-bit signed integer".
### Changed ### Changed
- X10D: `DateTime.Age(DateTime)` and `DateTimeOffset.Age(DateTimeOffset)` parameter renamed from `asOf` to `referenceDate`.
- X10D: DateTime.Age(DateTime) and DateTimeOffset.Age(DateTimeOffset) parameter renamed from asOf to referenceDate.
- X10D: Methods which accepted the `Endianness` enum as an argument have been replaced with explicit
BigEndian/LittleEndian methods.
- X10D: `Stream.GetHash<>` and `Stream.TryWriteHash<>` now throw ArgumentException in lieu of
TypeInitializationException.
### Removed
- X10D: Removed `IEnumerable<T>.ConcatOne` - this functionality already exists with `Append`.
- X10D: Removed `Endianness` enum.
- X10D.DSharpPlus: Complete sunset of library. This library will not be updated to support DSharpPlus v5.0.0.
## [3.3.1] - 2023-08-21
### Fixed
- X10D.Hosting: Fixed `AddHostedSingleton` not accepting an interface as the service type.
## [3.3.0] - 2023-08-21
### Added
- X10D.Hosting: Added support for service/implementation registration with `AddHostedSingleton`.
## [3.2.2] - 2023-06-05
### Added
- X10D.DSharpPlus: Added support for new usernames. See https://discord.com/blog/usernames
## 3.2.1 - 2023-06-05
ERRONEOUS RELEASE.
## [3.2.0] - 2023-04-03 ## [3.2.0] - 2023-04-03
@ -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. 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.2.0]: https://github.com/oliverbooth/X10D/releases/tag/v3.2.0
[3.1.0]: https://github.com/oliverbooth/X10D/releases/tag/v3.1.0 [3.1.0]: https://github.com/oliverbooth/X10D/releases/tag/v3.1.0
[3.0.0]: https://github.com/oliverbooth/X10D/releases/tag/v3.0.0 [3.0.0]: https://github.com/oliverbooth/X10D/releases/tag/v3.0.0

View File

@ -9,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 There is an `.editorconfig` included in this repository. For quick and painless pull requests, ensure that the analyzer does not
throw warnings. throw warnings.
Please ensure that you follow the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/)
specification, as the GitHub release for this project is automatically generated from the commit history, and formatted using the
convetional commits specification.
### Code style ### Code style
Below are a few pointers to which you may refer, but keep in mind this is not an exhaustive list: Below are a few pointers to which you may refer, but keep in mind this is not an exhaustive list:

View File

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

View File

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

View File

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

View File

@ -2,24 +2,25 @@
<PropertyGroup> <PropertyGroup>
<TargetFrameworks>net7.0;net6.0;netcoreapp3.1</TargetFrameworks> <TargetFrameworks>net7.0;net6.0;netcoreapp3.1</TargetFrameworks>
<LangVersion>11.0</LangVersion>
<IsPackable>false</IsPackable> <IsPackable>false</IsPackable>
<Nullable>enable</Nullable>
<ImplicitUsings>true</ImplicitUsings>
<CoverletOutputFormat>json,cobertura</CoverletOutputFormat> <CoverletOutputFormat>json,cobertura</CoverletOutputFormat>
<CollectCoverage>true</CollectCoverage> <CollectCoverage>true</CollectCoverage>
<CodeAnalysisTreatWarningsAsErrors>false</CodeAnalysisTreatWarningsAsErrors>
</PropertyGroup>
<PropertyGroup Condition="'$(TargetFramework)' == 'netcoreapp3.1'">
<SuppressTfmSupportBuildWarnings>true</SuppressTfmSupportBuildWarnings>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.0"/> <PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.1"/>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.5.0"/> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.5.0"/>
<PackageReference Include="Moq" Version="4.18.4"/> <PackageReference Include="NSubstitute" Version="5.0.0"/>
<PackageReference Include="MSTest.TestAdapter" Version="3.0.2"/> <PackageReference Include="NUnit" Version="3.13.3"/>
<PackageReference Include="MSTest.TestFramework" Version="3.0.2"/> <PackageReference Include="NUnit3TestAdapter" Version="4.4.2"/>
<PackageReference Include="coverlet.collector" Version="3.2.0"> <PackageReference Include="NUnit.Analyzers" Version="3.6.1"/>
<PrivateAssets>all</PrivateAssets> <PackageReference Include="coverlet.collector" Version="3.2.0"/>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <PackageReference Include="System.Reactive" Version="5.0.0"/>
</PackageReference>
</ItemGroup> </ItemGroup>
<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; using X10D.Collections;
namespace X10D.Tests.Collections; namespace X10D.Tests.Collections;
public partial class ArrayTests internal static partial class ArrayTests
{ {
[TestClass] [TestFixture]
public class AsReadOnlyTests internal class AsReadOnlyTests
{ {
[TestMethod] [Test]
public void AsReadOnly_ShouldReturnReadOnlyCollection_WhenArrayIsNotNull() public void AsReadOnly_ShouldReturnReadOnlyCollection_WhenArrayIsNotNull()
{ {
int[] array = {1, 2, 3}; int[] array = {1, 2, 3};
IReadOnlyCollection<int> result = array.AsReadOnly(); IReadOnlyCollection<int> result = array.AsReadOnly();
Assert.IsInstanceOfType(result, typeof(IReadOnlyCollection<int>)); Assert.That(result, Is.InstanceOf<IReadOnlyCollection<int>>());
} }
[TestMethod] [Test]
public void AsReadOnly_ShouldThrowArgumentNullException_WhenArrayIsNull() public void AsReadOnly_ShouldThrowArgumentNullException_WhenArrayIsNull()
{ {
int[]? array = null; int[] array = null!;
Assert.ThrowsException<ArgumentNullException>(() => array!.AsReadOnly()); Assert.Throws<ArgumentNullException>(() => _ = array.AsReadOnly());
} }
[TestMethod] [Test]
public void AsReadOnly_ShouldReturnCorrectCount_WhenArrayIsNotEmpty() public void AsReadOnly_ShouldReturnCorrectCount_WhenArrayIsNotEmpty()
{ {
int[] array = {1, 2, 3}; int[] array = {1, 2, 3};
IReadOnlyCollection<int> result = array.AsReadOnly(); IReadOnlyCollection<int> result = array.AsReadOnly();
Assert.AreEqual(array.Length, result.Count); Assert.That(result, Has.Count.EqualTo(array.Length));
} }
[TestMethod] [Test]
public void AsReadOnly_ShouldReturnEmptyCollection_WhenArrayIsEmpty() public void AsReadOnly_ShouldReturnEmptyCollection_WhenArrayIsEmpty()
{ {
int[] array = Array.Empty<int>(); int[] array = Array.Empty<int>();
IReadOnlyCollection<int> result = array.AsReadOnly(); IReadOnlyCollection<int> result = array.AsReadOnly();
Assert.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; using X10D.Collections;
namespace X10D.Tests.Collections; namespace X10D.Tests.Collections;
public partial class ArrayTests internal static partial class ArrayTests
{ {
[TestClass] [TestFixture]
public class ClearTests public class ClearTests
{ {
[TestMethod] [Test]
public void Clear_ShouldClearTheArray() public void Clear_ShouldClearTheArray()
{ {
var array = new int?[] {1, 2, 3, null, 4}; var array = new int?[] {1, 2, 3, null, 4};
array.Clear(); array.Clear();
Assert.IsTrue(array.All(x => x == null)); Assert.That(array.All(x => x == null));
} }
[TestMethod] [Test]
public void Clear_ShouldDoNothing_WhenArrayIsEmpty() public void Clear_ShouldDoNothing_WhenArrayIsEmpty()
{ {
int[] array = Array.Empty<int>(); int[] array = Array.Empty<int>();
array.Clear(); array.Clear();
} }
[TestMethod] [Test]
public void Clear_WithRange_ShouldClearTheSpecifiedRangeOfTheArray() public void Clear_WithRange_ShouldClearTheSpecifiedRangeOfTheArray()
{ {
var array = new int?[] {1, 2, 3, null, 4}; var array = new int?[] {1, 2, 3, null, 4};
array.Clear(1..4); array.Clear(1..4);
Assert.AreEqual(5, array.Length); Assert.That(array.Length, Is.EqualTo(5));
Assert.AreEqual(1, array[0]); Assert.That(array[0], Is.EqualTo(1));
Assert.AreEqual(4, array[4]); Assert.That(array[4], Is.EqualTo(4));
Assert.IsTrue(array[1..4].All(x => x == null)); Assert.That(array[1..4].All(x => x == null));
} }
[TestMethod] [Test]
public void Clear_WithIndexAndLength_ShouldClearTheSpecifiedRangeOfTheArray() public void Clear_WithIndexAndLength_ShouldClearTheSpecifiedRangeOfTheArray()
{ {
var array = new int?[] {1, 2, 3, null, 4}; var array = new int?[] {1, 2, 3, null, 4};
array.Clear(1, 3); array.Clear(1, 3);
Assert.AreEqual(5, array.Length); Assert.That(array.Length, Is.EqualTo(5));
Assert.AreEqual(1, array[0]); Assert.That(array[0], Is.EqualTo(1));
Assert.AreEqual(4, array[4]); Assert.That(array[4], Is.EqualTo(4));
Assert.IsTrue(array[1..4].All(x => x == null)); Assert.That(array[1..4].All(x => x == null));
} }
[TestMethod] [Test]
public void Clear_ShouldThrowArgumentNullException_WhenArrayIsNull() public void Clear_ShouldThrowArgumentNullException_WhenArrayIsNull()
{ {
int[] array = null!; int[] array = null!;
Assert.ThrowsException<ArgumentNullException>(() => array.Clear()); Assert.Throws<ArgumentNullException>(() => array.Clear());
Assert.ThrowsException<ArgumentNullException>(() => array.Clear(0, 1)); Assert.Throws<ArgumentNullException>(() => array.Clear(0, 1));
Assert.ThrowsException<ArgumentNullException>(() => array.Clear(..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; namespace X10D.Tests.Collections;
[TestClass] [TestFixture]
public partial class ArrayTests internal static partial class ArrayTests
{ {
} }

View File

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

View File

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

View File

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

View File

@ -1,176 +1,231 @@
using Microsoft.VisualStudio.TestTools.UnitTesting; using NUnit.Framework;
using X10D.Collections; using X10D.Collections;
namespace X10D.Tests.Collections; namespace X10D.Tests.Collections;
[TestClass] [TestFixture]
public class DictionaryTests internal class DictionaryTests
{ {
[TestMethod] [Test]
public void AddOrUpdate_ShouldAddNewKey_IfNotExists_GivenConcreteDictionary() public void AddOrUpdate_ShouldAddNewKey_IfNotExists_GivenConcreteDictionary()
{ {
var dictionary = new Dictionary<int, string>(); var dictionary = new Dictionary<int, string>();
Assert.IsFalse(dictionary.ContainsKey(1)); Assert.That(dictionary.ContainsKey(1), Is.False);
dictionary.AddOrUpdate(1, "one", (_, _) => string.Empty); dictionary.AddOrUpdate(1, "one", (_, _) => string.Empty);
Assert.IsTrue(dictionary.ContainsKey(1)); Assert.Multiple(() =>
Assert.AreEqual("one", dictionary[1]); {
Assert.That(dictionary.ContainsKey(1));
Assert.That(dictionary[1], Is.EqualTo("one"));
});
dictionary.Clear(); dictionary.Clear();
Assert.IsFalse(dictionary.ContainsKey(1)); Assert.That(dictionary.ContainsKey(1), Is.False);
dictionary.AddOrUpdate(1, _ => "one", (_, _) => string.Empty); dictionary.AddOrUpdate(1, _ => "one", (_, _) => string.Empty);
Assert.IsTrue(dictionary.ContainsKey(1)); Assert.Multiple(() =>
Assert.AreEqual("one", dictionary[1]); {
Assert.That(dictionary.ContainsKey(1));
Assert.That(dictionary[1], Is.EqualTo("one"));
});
dictionary.Clear(); 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); dictionary.AddOrUpdate(1, (_, _) => "one", (_, _, _) => string.Empty, 0);
Assert.IsTrue(dictionary.ContainsKey(1)); Assert.Multiple(() =>
Assert.AreEqual("one", dictionary[1]); {
Assert.That(dictionary.ContainsKey(1), Is.True);
Assert.That(dictionary[1], Is.EqualTo("one"));
});
} }
[TestMethod] [Test]
public void AddOrUpdate_ShouldAddNewKey_IfNotExists_GivenIDictionary() public void AddOrUpdate_ShouldAddNewKey_IfNotExists_GivenIDictionary()
{ {
IDictionary<int, string> dictionary = new Dictionary<int, string>(); IDictionary<int, string> dictionary = new Dictionary<int, string>();
Assert.IsFalse(dictionary.ContainsKey(1)); Assert.That(dictionary.ContainsKey(1), Is.False);
dictionary.AddOrUpdate(1, "one", (_, _) => string.Empty); dictionary.AddOrUpdate(1, "one", (_, _) => string.Empty);
Assert.IsTrue(dictionary.ContainsKey(1)); Assert.Multiple(() =>
Assert.AreEqual("one", dictionary[1]); {
Assert.That(dictionary.ContainsKey(1), Is.True);
Assert.That(dictionary[1], Is.EqualTo("one"));
});
dictionary.Clear(); dictionary.Clear();
Assert.IsFalse(dictionary.ContainsKey(1)); Assert.That(dictionary.ContainsKey(1), Is.False);
dictionary.AddOrUpdate(1, _ => "one", (_, _) => string.Empty); dictionary.AddOrUpdate(1, _ => "one", (_, _) => string.Empty);
Assert.IsTrue(dictionary.ContainsKey(1)); Assert.Multiple(() =>
Assert.AreEqual("one", dictionary[1]); {
Assert.That(dictionary.ContainsKey(1), Is.True);
Assert.That(dictionary[1], Is.EqualTo("one"));
});
dictionary.Clear(); 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); dictionary.AddOrUpdate(1, (_, _) => "one", (_, _, _) => string.Empty, 0);
Assert.IsTrue(dictionary.ContainsKey(1)); Assert.Multiple(() =>
Assert.AreEqual("one", dictionary[1]); {
Assert.That(dictionary.ContainsKey(1), Is.True);
Assert.That(dictionary[1], Is.EqualTo("one"));
});
} }
[TestMethod] [Test]
public void AddOrUpdate_ShouldUpdateKey_IfExists_GivenConcreteDirection() public void AddOrUpdate_ShouldUpdateKey_IfExists_GivenConcreteDirection()
{ {
var dictionary = new Dictionary<int, string> {[1] = "one"}; var dictionary = new Dictionary<int, string> {[1] = "one"};
Assert.IsTrue(dictionary.ContainsKey(1)); Assert.Multiple(() =>
Assert.AreEqual("one", dictionary[1]); {
Assert.That(dictionary.ContainsKey(1));
Assert.That(dictionary[1], Is.EqualTo("one"));
});
dictionary.AddOrUpdate(1, string.Empty, (_, _) => "two"); dictionary.AddOrUpdate(1, string.Empty, (_, _) => "two");
Assert.IsTrue(dictionary.ContainsKey(1)); Assert.Multiple(() =>
Assert.AreEqual("two", dictionary[1]); {
Assert.That(dictionary.ContainsKey(1));
Assert.That(dictionary[1], Is.EqualTo("two"));
});
dictionary.Clear(); dictionary.Clear();
Assert.IsFalse(dictionary.ContainsKey(1)); Assert.That(dictionary, Is.Empty);
Assert.That(dictionary.ContainsKey(1), Is.False);
dictionary[1] = "one"; dictionary[1] = "one";
dictionary.AddOrUpdate(1, _ => string.Empty, (_, _) => "two"); dictionary.AddOrUpdate(1, _ => string.Empty, (_, _) => "two");
Assert.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(); dictionary.Clear();
Assert.IsFalse(dictionary.ContainsKey(1)); Assert.That(dictionary, Is.Empty);
Assert.That(dictionary.ContainsKey(1), Is.False);
dictionary[1] = "one"; dictionary[1] = "one";
dictionary.AddOrUpdate(1, (_, _) => string.Empty, (_, _, _) => "two", 0); dictionary.AddOrUpdate(1, (_, _) => string.Empty, (_, _, _) => "two", 0);
Assert.IsTrue(dictionary.ContainsKey(1)); Assert.Multiple(() =>
Assert.AreEqual("two", dictionary[1]); {
Assert.That(dictionary.ContainsKey(1));
Assert.That(dictionary[1], Is.EqualTo("two"));
});
} }
[TestMethod] [Test]
public void AddOrUpdate_ShouldUpdateKey_IfExists_GivenIDictionary() public void AddOrUpdate_ShouldUpdateKey_IfExists_GivenIDictionary()
{ {
IDictionary<int, string> dictionary = new Dictionary<int, string> {[1] = "one"}; IDictionary<int, string> dictionary = new Dictionary<int, string> {[1] = "one"};
Assert.IsTrue(dictionary.ContainsKey(1)); Assert.Multiple(() =>
Assert.AreEqual("one", dictionary[1]); {
Assert.That(dictionary.ContainsKey(1));
Assert.That(dictionary[1], Is.EqualTo("one"));
});
dictionary.AddOrUpdate(1, string.Empty, (_, _) => "two"); dictionary.AddOrUpdate(1, string.Empty, (_, _) => "two");
Assert.IsTrue(dictionary.ContainsKey(1)); Assert.Multiple(() =>
Assert.AreEqual("two", dictionary[1]); {
Assert.That(dictionary.ContainsKey(1));
Assert.That(dictionary[1], Is.EqualTo("two"));
});
dictionary.Clear(); dictionary.Clear();
Assert.IsFalse(dictionary.ContainsKey(1)); Assert.Multiple(() =>
dictionary[1] = "one"; {
Assert.That(dictionary, Is.Empty);
Assert.That(dictionary.ContainsKey(1), Is.False);
});
dictionary[1] = "one";
dictionary.AddOrUpdate(1, _ => string.Empty, (_, _) => "two"); dictionary.AddOrUpdate(1, _ => string.Empty, (_, _) => "two");
Assert.IsTrue(dictionary.ContainsKey(1)); Assert.Multiple(() =>
Assert.AreEqual("two", dictionary[1]); {
Assert.That(dictionary.ContainsKey(1));
Assert.That(dictionary[1], Is.EqualTo("two"));
});
dictionary.Clear(); dictionary.Clear();
Assert.IsFalse(dictionary.ContainsKey(1)); Assert.Multiple(() =>
{
Assert.That(dictionary, Is.Empty);
Assert.That(dictionary.ContainsKey(1), Is.False);
dictionary[1] = "one"; dictionary[1] = "one";
});
dictionary.AddOrUpdate(1, (_, _) => string.Empty, (_, _, _) => "two", 0); dictionary.AddOrUpdate(1, (_, _) => string.Empty, (_, _, _) => "two", 0);
Assert.IsTrue(dictionary.ContainsKey(1)); Assert.Multiple(() =>
Assert.AreEqual("two", dictionary[1]); {
Assert.That(dictionary.ContainsKey(1));
Assert.That(dictionary[1], Is.EqualTo("two"));
});
} }
[TestMethod] [Test]
public void AddOrUpdate_ShouldThrow_GivenNullDictionary_GivenConcreteDictionary() public void AddOrUpdate_ShouldThrow_GivenNullDictionary_GivenConcreteDictionary()
{ {
Dictionary<int, string>? dictionary = null; Dictionary<int, string>? dictionary = null;
Assert.ThrowsException<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)); dictionary!.AddOrUpdate(1, _ => string.Empty, (_, _) => string.Empty));
Assert.ThrowsException<ArgumentNullException>(() => Assert.Throws<ArgumentNullException>(() =>
dictionary!.AddOrUpdate(1, (_, _) => string.Empty, (_, _, _) => string.Empty, 0)); dictionary!.AddOrUpdate(1, (_, _) => string.Empty, (_, _, _) => string.Empty, 0));
} }
[TestMethod] [Test]
public void AddOrUpdate_ShouldThrow_GivenNullDictionary_GivenIDictionary() public void AddOrUpdate_ShouldThrow_GivenNullDictionary_GivenIDictionary()
{ {
IDictionary<int, string>? dictionary = null; IDictionary<int, string>? dictionary = null;
Assert.ThrowsException<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)); dictionary!.AddOrUpdate(1, _ => string.Empty, (_, _) => string.Empty));
Assert.ThrowsException<ArgumentNullException>(() => Assert.Throws<ArgumentNullException>(() =>
dictionary!.AddOrUpdate(1, (_, _) => string.Empty, (_, _, _) => string.Empty, 0)); dictionary!.AddOrUpdate(1, (_, _) => string.Empty, (_, _, _) => string.Empty, 0));
} }
[TestMethod] [Test]
public void AddOrUpdate_ShouldThrow_GivenNullUpdateValueFactory_GivenConcreteDictionary() public void AddOrUpdate_ShouldThrow_GivenNullUpdateValueFactory_GivenConcreteDictionary()
{ {
var dictionary = new Dictionary<int, string>(); var dictionary = new Dictionary<int, string>();
Assert.ThrowsException<ArgumentNullException>(() => dictionary.AddOrUpdate(1, string.Empty, null!)); Assert.Throws<ArgumentNullException>(() => dictionary.AddOrUpdate(1, string.Empty, null!));
Assert.ThrowsException<ArgumentNullException>(() => dictionary.AddOrUpdate(1, _ => string.Empty, null!)); Assert.Throws<ArgumentNullException>(() => dictionary.AddOrUpdate(1, _ => string.Empty, null!));
Assert.ThrowsException<ArgumentNullException>(() => dictionary.AddOrUpdate(1, (_, _) => string.Empty, null!, 0)); Assert.Throws<ArgumentNullException>(() => dictionary.AddOrUpdate(1, (_, _) => string.Empty, null!, 0));
} }
[TestMethod] [Test]
public void AddOrUpdate_ShouldThrow_GivenNullUpdateValueFactory_GivenIDictionary() public void AddOrUpdate_ShouldThrow_GivenNullUpdateValueFactory_GivenIDictionary()
{ {
IDictionary<int, string> dictionary = new Dictionary<int, string>(); IDictionary<int, string> dictionary = new Dictionary<int, string>();
Assert.ThrowsException<ArgumentNullException>(() => dictionary.AddOrUpdate(1, string.Empty, null!)); Assert.Throws<ArgumentNullException>(() => dictionary.AddOrUpdate(1, string.Empty, null!));
Assert.ThrowsException<ArgumentNullException>(() => dictionary.AddOrUpdate(1, _ => string.Empty, null!)); Assert.Throws<ArgumentNullException>(() => dictionary.AddOrUpdate(1, _ => string.Empty, null!));
Assert.ThrowsException<ArgumentNullException>(() => dictionary.AddOrUpdate(1, (_, _) => string.Empty, null!, 0)); Assert.Throws<ArgumentNullException>(() => dictionary.AddOrUpdate(1, (_, _) => string.Empty, null!, 0));
} }
[TestMethod] [Test]
public void AddOrUpdate_ShouldThrow_GivenNullAddValueFactory_GivenConcreteDictionary() public void AddOrUpdate_ShouldThrow_GivenNullAddValueFactory_GivenConcreteDictionary()
{ {
var dictionary = new Dictionary<int, string>(); var dictionary = new Dictionary<int, string>();
Func<int, string>? addValueFactory = null; Func<int, string>? addValueFactory = null;
Assert.ThrowsException<ArgumentNullException>(() => dictionary.AddOrUpdate(1, addValueFactory!, (_, _) => "one")); Assert.Throws<ArgumentNullException>(() => dictionary.AddOrUpdate(1, addValueFactory!, (_, _) => "one"));
Assert.ThrowsException<ArgumentNullException>(() => dictionary.AddOrUpdate(1, null!, (_, _, _) => "one", 0)); Assert.Throws<ArgumentNullException>(() => dictionary.AddOrUpdate(1, null!, (_, _, _) => "one", 0));
} }
[TestMethod] [Test]
public void AddOrUpdate_ShouldThrow_GivenNullAddValueFactory_GivenIDictionary() public void AddOrUpdate_ShouldThrow_GivenNullAddValueFactory_GivenIDictionary()
{ {
IDictionary<int, string> dictionary = new Dictionary<int, string>(); IDictionary<int, string> dictionary = new Dictionary<int, string>();
Func<int, string>? addValueFactory = null; Func<int, string>? addValueFactory = null;
Assert.ThrowsException<ArgumentNullException>(() => dictionary.AddOrUpdate(1, addValueFactory!, (_, _) => "one")); Assert.Throws<ArgumentNullException>(() => dictionary.AddOrUpdate(1, addValueFactory!, (_, _) => "one"));
Assert.ThrowsException<ArgumentNullException>(() => dictionary.AddOrUpdate(1, null!, (_, _, _) => "one", 0)); Assert.Throws<ArgumentNullException>(() => dictionary.AddOrUpdate(1, null!, (_, _, _) => "one", 0));
} }
[TestMethod] [Test]
public void ToConnectionString_ShouldReturnConnectionString() public void ToConnectionString_ShouldReturnConnectionString()
{ {
var dictionary = new Dictionary<string, string?> var dictionary = new Dictionary<string, string?>
@ -179,10 +234,10 @@ public class DictionaryTests
}; };
string connectionString = dictionary.ToConnectionString(); 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() public void ToConnectionString_ShouldReturnTransformedValueConnectionString()
{ {
var dictionary = new Dictionary<string, string?> var dictionary = new Dictionary<string, string?>
@ -191,10 +246,10 @@ public class DictionaryTests
}; };
string connectionString = dictionary.ToConnectionString(v => v?.ToUpperInvariant()); 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() public void ToConnectionString_ShouldReturnTransformedKeyValueConnectionString()
{ {
var dictionary = new Dictionary<string, string?> var dictionary = new Dictionary<string, string?>
@ -203,69 +258,69 @@ public class DictionaryTests
}; };
string connectionString = dictionary.ToConnectionString(k => k.ToUpper(), v => v?.ToUpperInvariant()); 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() public void ToConnectionString_ShouldThrow_GivenNullSource()
{ {
Dictionary<string, string>? dictionary = null; Dictionary<string, string> dictionary = null!;
Assert.ThrowsException<ArgumentNullException>(() => dictionary!.ToConnectionString()); Assert.Throws<ArgumentNullException>(() => _ = dictionary.ToConnectionString());
Assert.ThrowsException<ArgumentNullException>(() => dictionary!.ToConnectionString(null!)); Assert.Throws<ArgumentNullException>(() => _ = dictionary.ToConnectionString(null!));
Assert.ThrowsException<ArgumentNullException>(() => dictionary!.ToConnectionString(null!, null!)); Assert.Throws<ArgumentNullException>(() => _ = dictionary.ToConnectionString(null!, null!));
} }
[TestMethod] [Test]
public void ToConnectionString_ShouldThrow_GivenNullSelector() public void ToConnectionString_ShouldThrow_GivenNullSelector()
{ {
var dictionary = new Dictionary<string, string>(); var dictionary = new Dictionary<string, string>();
Assert.ThrowsException<ArgumentNullException>(() => dictionary.ToConnectionString(null!)); Assert.Throws<ArgumentNullException>(() => _ = dictionary.ToConnectionString(null!));
Assert.ThrowsException<ArgumentNullException>(() => dictionary.ToConnectionString(null!, _ => _)); Assert.Throws<ArgumentNullException>(() => _ = dictionary.ToConnectionString(null!, _ => _));
Assert.ThrowsException<ArgumentNullException>(() => dictionary.ToConnectionString(_ => _, null!)); Assert.Throws<ArgumentNullException>(() => _ = dictionary.ToConnectionString(_ => _, null!));
} }
[TestMethod] [Test]
public void ToGetParameters_ShouldReturnParameters() public void ToGetParameters_ShouldReturnParameters()
{ {
var dictionary = new Dictionary<string, string> {["id"] = "1", ["user"] = "hello world", ["foo"] = "bar"}; var dictionary = new Dictionary<string, string> {["id"] = "1", ["user"] = "hello world", ["foo"] = "bar"};
string queryString = dictionary.ToGetParameters(); string queryString = dictionary.ToGetParameters();
Assert.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() public void ToGetParameters_ShouldReturnTransformedValueParameters()
{ {
var dictionary = new Dictionary<string, string?> {["id"] = "1", ["user"] = "hello world", ["foo"] = null}; var dictionary = new Dictionary<string, string?> {["id"] = "1", ["user"] = "hello world", ["foo"] = null};
string queryString = dictionary.ToGetParameters(v => v?.ToUpper()); string queryString = dictionary.ToGetParameters(v => v?.ToUpper());
Assert.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() public void ToGetParameters_ShouldReturnTransformedKeyValueParameters()
{ {
var dictionary = new Dictionary<string, string?> {["id"] = "1", ["user"] = "hello world", ["foo"] = null}; var dictionary = new Dictionary<string, string?> {["id"] = "1", ["user"] = "hello world", ["foo"] = null};
string queryString = dictionary.ToGetParameters(k => k.ToUpper(), v => v?.ToUpper()); string queryString = dictionary.ToGetParameters(k => k.ToUpper(), v => v?.ToUpper());
Assert.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() public void ToGetParameters_ShouldThrow_GivenNullSource()
{ {
Dictionary<string, string>? dictionary = null; Dictionary<string, string> dictionary = null!;
Assert.ThrowsException<ArgumentNullException>(() => dictionary!.ToGetParameters()); Assert.Throws<ArgumentNullException>(() => _ = dictionary.ToGetParameters());
Assert.ThrowsException<ArgumentNullException>(() => dictionary!.ToGetParameters(null!)); Assert.Throws<ArgumentNullException>(() => _ = dictionary.ToGetParameters(null!));
Assert.ThrowsException<ArgumentNullException>(() => dictionary!.ToGetParameters(null!, null!)); Assert.Throws<ArgumentNullException>(() => _ = dictionary.ToGetParameters(null!, null!));
} }
[TestMethod] [Test]
public void ToGetParameters_ShouldThrow_GivenNullSelector() public void ToGetParameters_ShouldThrow_GivenNullSelector()
{ {
var dictionary = new Dictionary<string, string>(); var dictionary = new Dictionary<string, string>();
Assert.ThrowsException<ArgumentNullException>(() => dictionary.ToGetParameters(null!)); Assert.Throws<ArgumentNullException>(() => _ = dictionary.ToGetParameters(null!));
Assert.ThrowsException<ArgumentNullException>(() => dictionary.ToGetParameters(null!, _ => _)); Assert.Throws<ArgumentNullException>(() => _ = dictionary.ToGetParameters(null!, _ => _));
Assert.ThrowsException<ArgumentNullException>(() => dictionary.ToGetParameters(_ => _, null!)); Assert.Throws<ArgumentNullException>(() => _ = dictionary.ToGetParameters(_ => _, null!));
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,52 +1,76 @@
using Microsoft.VisualStudio.TestTools.UnitTesting; using NUnit.Framework;
using X10D.Collections; using X10D.Collections;
namespace X10D.Tests.Collections; namespace X10D.Tests.Collections;
[TestClass] [TestFixture]
public class SpanTest internal class SpanTest
{ {
[TestMethod] [Test]
public void Count_ShouldReturn0_GivenEmptySpan() public void Count_ShouldReturn0_GivenEmptySpan()
{ {
Span<int> span = Span<int>.Empty; Span<int> span = Span<int>.Empty;
int count = span.Count(2); int count = span.Count(2);
Assert.AreEqual(0, count); Assert.That(count, Is.Zero);
} }
[TestMethod] [Test]
public void Count_ShouldReturn0_GivenEmptyReadOnlySpan() public void Count_ShouldReturn0_GivenEmptyReadOnlySpan()
{ {
ReadOnlySpan<int> span = ReadOnlySpan<int>.Empty; ReadOnlySpan<int> span = ReadOnlySpan<int>.Empty;
int count = span.Count(2); int count = span.Count(2);
Assert.AreEqual(0, count); Assert.That(count, Is.Zero);
} }
[TestMethod] [Test]
public void Count_ShouldReturn8_GivenSpanWith8MatchingElements() public void Count_ShouldReturn8_GivenSpanWith8MatchingElements()
{ {
Span<int> span = stackalloc int[16] {1, 2, 3, 2, 5, 2, 7, 2, 9, 2, 11, 2, 13, 2, 15, 2}; Span<int> span = stackalloc int[16] {1, 2, 3, 2, 5, 2, 7, 2, 9, 2, 11, 2, 13, 2, 15, 2};
int count = span.Count(2); int count = span.Count(2);
Assert.AreEqual(8, count); Assert.That(count, Is.EqualTo(8));
} }
[TestMethod] [Test]
public void Count_ShouldReturn8_GivenReadOnlySpanWith8MatchingElements() public void Count_ShouldReturn8_GivenReadOnlySpanWith8MatchingElements()
{ {
ReadOnlySpan<int> span = stackalloc int[16] {1, 2, 3, 2, 5, 2, 7, 2, 9, 2, 11, 2, 13, 2, 15, 2}; ReadOnlySpan<int> span = stackalloc int[16] {1, 2, 3, 2, 5, 2, 7, 2, 9, 2, 11, 2, 13, 2, 15, 2};
int count = span.Count(2); int count = span.Count(2);
Assert.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() public void Split_OnEmptySpan_ShouldYieldNothing_UsingCharDelimiter_GivenReadOnlySpan()
{ {
ReadOnlySpan<char> span = ReadOnlySpan<char>.Empty; ReadOnlySpan<char> span = ReadOnlySpan<char>.Empty;
@ -57,10 +81,10 @@ public class SpanTest
index++; index++;
} }
Assert.AreEqual(0, index); Assert.That(index, Is.Zero);
} }
[TestMethod] [Test]
public void Split_OnEmptySpan_ShouldYieldNothing_UsingCharDelimiter_GivenSpan() public void Split_OnEmptySpan_ShouldYieldNothing_UsingCharDelimiter_GivenSpan()
{ {
Span<char> span = Span<char>.Empty; Span<char> span = Span<char>.Empty;
@ -71,10 +95,10 @@ public class SpanTest
index++; index++;
} }
Assert.AreEqual(0, index); Assert.That(index, Is.Zero);
} }
[TestMethod] [Test]
public void Split_OnEmptySpan_ShouldYieldNothing_UsingStringDelimiter_GivenReadOnlySpan() public void Split_OnEmptySpan_ShouldYieldNothing_UsingStringDelimiter_GivenReadOnlySpan()
{ {
ReadOnlySpan<char> span = ReadOnlySpan<char>.Empty; ReadOnlySpan<char> span = ReadOnlySpan<char>.Empty;
@ -85,10 +109,10 @@ public class SpanTest
index++; index++;
} }
Assert.AreEqual(0, index); Assert.That(index, Is.Zero);
} }
[TestMethod] [Test]
public void Split_OnEmptySpan_ShouldYieldNothing_UsingStringDelimiter_GivenSpan() public void Split_OnEmptySpan_ShouldYieldNothing_UsingStringDelimiter_GivenSpan()
{ {
Span<char> span = Span<char>.Empty; Span<char> span = Span<char>.Empty;
@ -99,10 +123,10 @@ public class SpanTest
index++; index++;
} }
Assert.AreEqual(0, index); Assert.That(index, Is.Zero);
} }
[TestMethod] [Test]
public void Split_OnOneWord_ShouldYieldLength1_UsingCharDelimiter_GivenReadOnlySpan() public void Split_OnOneWord_ShouldYieldLength1_UsingCharDelimiter_GivenReadOnlySpan()
{ {
ReadOnlySpan<char> span = "Hello ".AsSpan(); ReadOnlySpan<char> span = "Hello ".AsSpan();
@ -112,16 +136,16 @@ public class SpanTest
{ {
if (index == 0) if (index == 0)
{ {
Assert.AreEqual("Hello", subSpan.ToString()); Assert.That(subSpan.ToString(), Is.EqualTo("Hello"));
} }
index++; index++;
} }
Assert.AreEqual(1, index); Assert.That(index, Is.EqualTo(1));
} }
[TestMethod] [Test]
public void Split_OnOneWord_ShouldYieldLength1_UsingCharDelimiter_GivenSpan() public void Split_OnOneWord_ShouldYieldLength1_UsingCharDelimiter_GivenSpan()
{ {
ReadOnlySpan<char> source = "Hello ".AsSpan(); ReadOnlySpan<char> source = "Hello ".AsSpan();
@ -133,16 +157,16 @@ public class SpanTest
{ {
if (index == 0) if (index == 0)
{ {
Assert.AreEqual("Hello", subSpan.ToString()); Assert.That(subSpan.ToString(), Is.EqualTo("Hello"));
} }
index++; index++;
} }
Assert.AreEqual(1, index); Assert.That(index, Is.EqualTo(1));
} }
[TestMethod] [Test]
public void Split_OnOneWord_ShouldYieldLength1_UsingStringDelimiter_GivenReadOnlySpan() public void Split_OnOneWord_ShouldYieldLength1_UsingStringDelimiter_GivenReadOnlySpan()
{ {
ReadOnlySpan<char> span = "Hello ".AsSpan(); ReadOnlySpan<char> span = "Hello ".AsSpan();
@ -152,16 +176,16 @@ public class SpanTest
{ {
if (index == 0) if (index == 0)
{ {
Assert.AreEqual("Hello", subSpan.ToString()); Assert.That(subSpan.ToString(), Is.EqualTo("Hello"));
} }
index++; index++;
} }
Assert.AreEqual(1, index); Assert.That(index, Is.EqualTo(1));
} }
[TestMethod] [Test]
public void Split_OnOneWord_ShouldYieldLength1_UsingStringDelimiter_GivenSpan() public void Split_OnOneWord_ShouldYieldLength1_UsingStringDelimiter_GivenSpan()
{ {
ReadOnlySpan<char> source = "Hello ".AsSpan(); ReadOnlySpan<char> source = "Hello ".AsSpan();
@ -173,16 +197,16 @@ public class SpanTest
{ {
if (index == 0) if (index == 0)
{ {
Assert.AreEqual("Hello", subSpan.ToString()); Assert.That(subSpan.ToString(), Is.EqualTo("Hello"));
} }
index++; index++;
} }
Assert.AreEqual(1, index); Assert.That(index, Is.EqualTo(1));
} }
[TestMethod] [Test]
public void Split_OnOneWordWithoutDelimiter_ShouldYieldLength1_UsingCharDelimiter_GivenReadOnlySpan() public void Split_OnOneWordWithoutDelimiter_ShouldYieldLength1_UsingCharDelimiter_GivenReadOnlySpan()
{ {
ReadOnlySpan<char> span = "Hello".AsSpan(); ReadOnlySpan<char> span = "Hello".AsSpan();
@ -192,16 +216,16 @@ public class SpanTest
{ {
if (index == 0) if (index == 0)
{ {
Assert.AreEqual("Hello", subSpan.ToString()); Assert.That(subSpan.ToString(), Is.EqualTo("Hello"));
} }
index++; index++;
} }
Assert.AreEqual(1, index); Assert.That(index, Is.EqualTo(1));
} }
[TestMethod] [Test]
public void Split_OnOneWordWithoutDelimiter_ShouldYieldLength1_UsingCharDelimiter_GivenSpan() public void Split_OnOneWordWithoutDelimiter_ShouldYieldLength1_UsingCharDelimiter_GivenSpan()
{ {
ReadOnlySpan<char> source = "Hello".AsSpan(); ReadOnlySpan<char> source = "Hello".AsSpan();
@ -213,16 +237,16 @@ public class SpanTest
{ {
if (index == 0) if (index == 0)
{ {
Assert.AreEqual("Hello", subSpan.ToString()); Assert.That(subSpan.ToString(), Is.EqualTo("Hello"));
} }
index++; index++;
} }
Assert.AreEqual(1, index); Assert.That(index, Is.EqualTo(1));
} }
[TestMethod] [Test]
public void Split_OnOneWordWithoutDelimiter_ShouldYieldLength1_UsingStringDelimiter_GivenReadOnlySpan() public void Split_OnOneWordWithoutDelimiter_ShouldYieldLength1_UsingStringDelimiter_GivenReadOnlySpan()
{ {
ReadOnlySpan<char> span = "Hello".AsSpan(); ReadOnlySpan<char> span = "Hello".AsSpan();
@ -232,16 +256,16 @@ public class SpanTest
{ {
if (index == 0) if (index == 0)
{ {
Assert.AreEqual("Hello", subSpan.ToString()); Assert.That(subSpan.ToString(), Is.EqualTo("Hello"));
} }
index++; index++;
} }
Assert.AreEqual(1, index); Assert.That(index, Is.EqualTo(1));
} }
[TestMethod] [Test]
public void Split_OnOneWordWithoutDelimiter_ShouldYieldLength1_UsingStringDelimiter_GivenSpan() public void Split_OnOneWordWithoutDelimiter_ShouldYieldLength1_UsingStringDelimiter_GivenSpan()
{ {
ReadOnlySpan<char> source = "Hello".AsSpan(); ReadOnlySpan<char> source = "Hello".AsSpan();
@ -253,16 +277,16 @@ public class SpanTest
{ {
if (index == 0) if (index == 0)
{ {
Assert.AreEqual("Hello", subSpan.ToString()); Assert.That(subSpan.ToString(), Is.EqualTo("Hello"));
} }
index++; index++;
} }
Assert.AreEqual(1, index); Assert.That(index, Is.EqualTo(1));
} }
[TestMethod] [Test]
public void Split_OnTwoWords_ShouldYieldLength2_UsingCharDelimiter_GivenReadOnlySpan() public void Split_OnTwoWords_ShouldYieldLength2_UsingCharDelimiter_GivenReadOnlySpan()
{ {
ReadOnlySpan<char> span = "Hello World ".AsSpan(); ReadOnlySpan<char> span = "Hello World ".AsSpan();
@ -273,20 +297,20 @@ public class SpanTest
switch (index) switch (index)
{ {
case 0: case 0:
Assert.AreEqual("Hello", subSpan.ToString()); Assert.That(subSpan.ToString(), Is.EqualTo("Hello"));
break; break;
case 1: case 1:
Assert.AreEqual("World", subSpan.ToString()); Assert.That(subSpan.ToString(), Is.EqualTo("World"));
break; break;
} }
index++; index++;
} }
Assert.AreEqual(2, index); Assert.That(index, Is.EqualTo(2));
} }
[TestMethod] [Test]
public void Split_OnTwoWords_ShouldYieldLength2_UsingCharDelimiter_GivenSpan() public void Split_OnTwoWords_ShouldYieldLength2_UsingCharDelimiter_GivenSpan()
{ {
ReadOnlySpan<char> source = "Hello World ".AsSpan(); ReadOnlySpan<char> source = "Hello World ".AsSpan();
@ -299,20 +323,20 @@ public class SpanTest
switch (index) switch (index)
{ {
case 0: case 0:
Assert.AreEqual("Hello", subSpan.ToString()); Assert.That(subSpan.ToString(), Is.EqualTo("Hello"));
break; break;
case 1: case 1:
Assert.AreEqual("World", subSpan.ToString()); Assert.That(subSpan.ToString(), Is.EqualTo("World"));
break; break;
} }
index++; index++;
} }
Assert.AreEqual(2, index); Assert.That(index, Is.EqualTo(2));
} }
[TestMethod] [Test]
public void Split_OnTwoWords_ShouldYieldLength2_UsingStringDelimiter_GivenReadOnlySpan() public void Split_OnTwoWords_ShouldYieldLength2_UsingStringDelimiter_GivenReadOnlySpan()
{ {
ReadOnlySpan<char> span = "Hello World ".AsSpan(); ReadOnlySpan<char> span = "Hello World ".AsSpan();
@ -323,20 +347,20 @@ public class SpanTest
switch (index) switch (index)
{ {
case 0: case 0:
Assert.AreEqual("Hello", subSpan.ToString()); Assert.That(subSpan.ToString(), Is.EqualTo("Hello"));
break; break;
case 1: case 1:
Assert.AreEqual("World", subSpan.ToString()); Assert.That(subSpan.ToString(), Is.EqualTo("World"));
break; break;
} }
index++; index++;
} }
Assert.AreEqual(2, index); Assert.That(index, Is.EqualTo(2));
} }
[TestMethod] [Test]
public void Split_OnTwoWords_ShouldYieldLength2_UsingStringDelimiter_GivenSpan() public void Split_OnTwoWords_ShouldYieldLength2_UsingStringDelimiter_GivenSpan()
{ {
ReadOnlySpan<char> source = "Hello World ".AsSpan(); ReadOnlySpan<char> source = "Hello World ".AsSpan();
@ -349,20 +373,20 @@ public class SpanTest
switch (index) switch (index)
{ {
case 0: case 0:
Assert.AreEqual("Hello", subSpan.ToString()); Assert.That(subSpan.ToString(), Is.EqualTo("Hello"));
break; break;
case 1: case 1:
Assert.AreEqual("World", subSpan.ToString()); Assert.That(subSpan.ToString(), Is.EqualTo("World"));
break; break;
} }
index++; index++;
} }
Assert.AreEqual(2, index); Assert.That(index, Is.EqualTo(2));
} }
[TestMethod] [Test]
public void Split_OnThreeWords_ShouldYieldLength3_UsingCharDelimiter_GivenReadOnlySpan() public void Split_OnThreeWords_ShouldYieldLength3_UsingCharDelimiter_GivenReadOnlySpan()
{ {
ReadOnlySpan<char> span = "Hello, the World ".AsSpan(); ReadOnlySpan<char> span = "Hello, the World ".AsSpan();
@ -373,23 +397,23 @@ public class SpanTest
switch (index) switch (index)
{ {
case 0: case 0:
Assert.AreEqual("Hello,", subSpan.ToString()); Assert.That(subSpan.ToString(), Is.EqualTo("Hello,"));
break; break;
case 1: case 1:
Assert.AreEqual("the", subSpan.ToString()); Assert.That(subSpan.ToString(), Is.EqualTo("the"));
break; break;
case 2: case 2:
Assert.AreEqual("World", subSpan.ToString()); Assert.That(subSpan.ToString(), Is.EqualTo("World"));
break; break;
} }
index++; index++;
} }
Assert.AreEqual(3, index); Assert.That(index, Is.EqualTo(3));
} }
[TestMethod] [Test]
public void Split_OnThreeWords_ShouldYieldLength3_UsingCharDelimiter_GivenSpan() public void Split_OnThreeWords_ShouldYieldLength3_UsingCharDelimiter_GivenSpan()
{ {
ReadOnlySpan<char> source = "Hello, the World ".AsSpan(); ReadOnlySpan<char> source = "Hello, the World ".AsSpan();
@ -402,23 +426,23 @@ public class SpanTest
switch (index) switch (index)
{ {
case 0: case 0:
Assert.AreEqual("Hello,", subSpan.ToString()); Assert.That(subSpan.ToString(), Is.EqualTo("Hello,"));
break; break;
case 1: case 1:
Assert.AreEqual("the", subSpan.ToString()); Assert.That(subSpan.ToString(), Is.EqualTo("the"));
break; break;
case 2: case 2:
Assert.AreEqual("World", subSpan.ToString()); Assert.That(subSpan.ToString(), Is.EqualTo("World"));
break; break;
} }
index++; index++;
} }
Assert.AreEqual(3, index); Assert.That(index, Is.EqualTo(3));
} }
[TestMethod] [Test]
public void Split_OnThreeWords_ShouldYieldLength3_UsingStringDelimiter_GivenReadOnlySpan() public void Split_OnThreeWords_ShouldYieldLength3_UsingStringDelimiter_GivenReadOnlySpan()
{ {
ReadOnlySpan<char> span = "Hello, the World ".AsSpan(); ReadOnlySpan<char> span = "Hello, the World ".AsSpan();
@ -429,23 +453,23 @@ public class SpanTest
switch (index) switch (index)
{ {
case 0: case 0:
Assert.AreEqual("Hello,", subSpan.ToString()); Assert.That(subSpan.ToString(), Is.EqualTo("Hello,"));
break; break;
case 1: case 1:
Assert.AreEqual("the", subSpan.ToString()); Assert.That(subSpan.ToString(), Is.EqualTo("the"));
break; break;
case 2: case 2:
Assert.AreEqual("World", subSpan.ToString()); Assert.That(subSpan.ToString(), Is.EqualTo("World"));
break; break;
} }
index++; index++;
} }
Assert.AreEqual(3, index); Assert.That(index, Is.EqualTo(3));
} }
[TestMethod] [Test]
public void Split_OnThreeWords_ShouldYieldLength3_UsingStringDelimiter_GivenSpan() public void Split_OnThreeWords_ShouldYieldLength3_UsingStringDelimiter_GivenSpan()
{ {
ReadOnlySpan<char> source = "Hello, the World ".AsSpan(); ReadOnlySpan<char> source = "Hello, the World ".AsSpan();
@ -458,19 +482,19 @@ public class SpanTest
switch (index) switch (index)
{ {
case 0: case 0:
Assert.AreEqual("Hello,", subSpan.ToString()); Assert.That(subSpan.ToString(), Is.EqualTo("Hello,"));
break; break;
case 1: case 1:
Assert.AreEqual("the", subSpan.ToString()); Assert.That(subSpan.ToString(), Is.EqualTo("the"));
break; break;
case 2: case 2:
Assert.AreEqual("World", subSpan.ToString()); Assert.That(subSpan.ToString(), Is.EqualTo("World"));
break; break;
} }
index++; 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; using X10D.Core;
namespace X10D.Tests.Core; namespace X10D.Tests.Core;
[TestClass] [TestFixture]
public class CoreTests internal class CoreTests
{ {
[TestMethod] [Test]
[DataRow(1)] [TestCase(1)]
[DataRow("f")] [TestCase("f")]
[DataRow(true)] [TestCase(true)]
public void AsArrayValue_ShouldBeLength1_GivenValue(object o) public void AsArrayValue_ShouldBeLength1_GivenValue(object o)
{ {
object[] array = o.AsArrayValue()!; object[] array = o.AsArrayValue();
Assert.IsNotNull(array); Assert.That(array, Is.Not.Null);
Assert.IsTrue(array.Length == 1); Assert.That(array, Has.Length.EqualTo(1));
} }
[TestMethod] [Test]
[DataRow(1)] [TestCase(1)]
[DataRow("f")] [TestCase("f")]
[DataRow(true)] [TestCase(true)]
public void AsArrayValue_ShouldContainValue_Given_Value(object o) public void AsArrayValue_ShouldContainValue_Given_Value(object o)
{ {
object[] array = o.AsArrayValue()!; object[] array = o.AsArrayValue();
Assert.IsNotNull(array); Assert.That(array, Is.Not.Null);
Assert.AreEqual(o, array[0]); Assert.That(array[0], Is.EqualTo(o));
} }
[TestMethod] [Test]
[DataRow(1)] [TestCase(1)]
[DataRow("f")] [TestCase("f")]
[DataRow(true)] [TestCase(true)]
public void AsEnumerableValue_ShouldBeLength1_GivenValue(object o) public void AsEnumerableValue_ShouldBeLength1_GivenValue(object o)
{ {
IEnumerable<object> enumerable = o.AsEnumerableValue()!; object[] enumerable = o.AsEnumerableValue().ToArray();
Assert.IsNotNull(enumerable); Assert.That(enumerable, Is.Not.Null);
Assert.IsTrue(enumerable.Count() == 1); Assert.That(enumerable, Has.Length.EqualTo(1));
} }
[TestMethod] [Test]
[DataRow(1)] [TestCase(1)]
[DataRow("f")] [TestCase("f")]
[DataRow(true)] [TestCase(true)]
public void AsEnumerableValue_ShouldContainValue_Given_Value(object o) public void AsEnumerableValue_ShouldContainValue_Given_Value(object o)
{ {
IEnumerable<object> enumerable = o.AsEnumerableValue()!; object[] enumerable = o.AsEnumerableValue().ToArray();
Assert.IsNotNull(enumerable); Assert.That(enumerable, Is.Not.Null);
Assert.AreEqual(o, enumerable.ElementAt(0)); Assert.That(enumerable.ElementAt(0), Is.EqualTo(o));
} }
[TestMethod] [Test]
[DataRow(1)] [TestCase(1)]
[DataRow("f")] [TestCase("f")]
[DataRow(true)] [TestCase(true)]
public void RepeatValue_ShouldContainRepeatedValue_GivenValue(object o) public void RepeatValue_ShouldContainRepeatedValue_GivenValue(object o)
{ {
IEnumerable<object> enumerable = o.RepeatValue(10); IEnumerable<object> enumerable = o.RepeatValue(10);
Assert.IsNotNull(enumerable); // ReSharper disable once PossibleMultipleEnumeration
Assert.That(enumerable, Is.Not.Null);
// ReSharper disable once PossibleMultipleEnumeration
object[] array = enumerable.ToArray(); 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); CollectionAssert.AreEqual(new[] {o, o, o, o, o, o, o, o, o, o}, array);
} }
[TestMethod] [Test]
[DataRow(1)] [TestCase(1)]
[DataRow("f")] [TestCase("f")]
[DataRow(true)] [TestCase(true)]
public void RepeatValue_ShouldThrow_GivenNegativeCount(object o) public void RepeatValue_ShouldThrow_GivenNegativeCount(object o)
{ {
// we must force enumeration via ToArray() to ensure the exception is thrown // we must force enumeration via ToArray() to ensure the exception is thrown
Assert.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; using X10D.Core;
namespace X10D.Tests.Core; namespace X10D.Tests.Core;
[TestClass] [TestFixture]
public class EnumTests internal class EnumTests
{ {
// Microsoft wrongfully decided to have Sunday be 0, Monday be 1, etc. // Microsoft wrongfully decided to have Sunday be 0, Monday be 1, etc.
// I personally hate this, Sunday is not the first day of the week. // I personally hate this, Sunday is not the first day of the week.
@ -12,51 +12,63 @@ public class EnumTests
// but Microsoft can't fix this without breaking compatibility. // but Microsoft can't fix this without breaking compatibility.
// I have feelings... // I have feelings...
[TestMethod] [Test]
public void Next() public void Next()
{ {
Assert.AreEqual(DayOfWeek.Monday, DayOfWeek.Sunday.Next()); Assert.Multiple(() =>
Assert.AreEqual(DayOfWeek.Tuesday, DayOfWeek.Monday.Next()); {
Assert.AreEqual(DayOfWeek.Wednesday, DayOfWeek.Tuesday.Next()); Assert.That(DayOfWeek.Sunday.Next(), Is.EqualTo(DayOfWeek.Monday));
Assert.AreEqual(DayOfWeek.Thursday, DayOfWeek.Wednesday.Next()); Assert.That(DayOfWeek.Monday.Next(), Is.EqualTo(DayOfWeek.Tuesday));
Assert.AreEqual(DayOfWeek.Friday, DayOfWeek.Thursday.Next()); Assert.That(DayOfWeek.Tuesday.Next(), Is.EqualTo(DayOfWeek.Wednesday));
Assert.AreEqual(DayOfWeek.Saturday, DayOfWeek.Friday.Next()); Assert.That(DayOfWeek.Wednesday.Next(), Is.EqualTo(DayOfWeek.Thursday));
Assert.AreEqual(DayOfWeek.Sunday, DayOfWeek.Saturday.Next()); // Saturday is the "last" day. wrap to "first" 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() public void NextUnchecked()
{ {
Assert.AreEqual(DayOfWeek.Monday, DayOfWeek.Sunday.NextUnchecked()); Assert.Multiple(() =>
Assert.AreEqual(DayOfWeek.Tuesday, DayOfWeek.Monday.NextUnchecked()); {
Assert.AreEqual(DayOfWeek.Wednesday, DayOfWeek.Tuesday.NextUnchecked()); Assert.That(DayOfWeek.Sunday.NextUnchecked(), Is.EqualTo(DayOfWeek.Monday));
Assert.AreEqual(DayOfWeek.Thursday, DayOfWeek.Wednesday.NextUnchecked()); Assert.That(DayOfWeek.Monday.NextUnchecked(), Is.EqualTo(DayOfWeek.Tuesday));
Assert.AreEqual(DayOfWeek.Friday, DayOfWeek.Thursday.NextUnchecked()); Assert.That(DayOfWeek.Tuesday.NextUnchecked(), Is.EqualTo(DayOfWeek.Wednesday));
Assert.AreEqual(DayOfWeek.Saturday, DayOfWeek.Friday.NextUnchecked()); Assert.That(DayOfWeek.Wednesday.NextUnchecked(), Is.EqualTo(DayOfWeek.Thursday));
Assert.ThrowsException<IndexOutOfRangeException>(() => DayOfWeek.Saturday.NextUnchecked()); 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() public void Previous()
{ {
Assert.AreEqual(DayOfWeek.Saturday, DayOfWeek.Sunday.Previous()); // Sunday is the "first" day. wrap to "last" Assert.Multiple(() =>
Assert.AreEqual(DayOfWeek.Sunday, DayOfWeek.Monday.Previous()); {
Assert.AreEqual(DayOfWeek.Monday, DayOfWeek.Tuesday.Previous()); Assert.That(DayOfWeek.Sunday.Previous(), Is.EqualTo(DayOfWeek.Saturday)); // Sunday is the "first" day. wrap to "last"
Assert.AreEqual(DayOfWeek.Tuesday, DayOfWeek.Wednesday.Previous()); Assert.That(DayOfWeek.Monday.Previous(), Is.EqualTo(DayOfWeek.Sunday));
Assert.AreEqual(DayOfWeek.Wednesday, DayOfWeek.Thursday.Previous()); Assert.That(DayOfWeek.Tuesday.Previous(), Is.EqualTo(DayOfWeek.Monday));
Assert.AreEqual(DayOfWeek.Thursday, DayOfWeek.Friday.Previous()); Assert.That(DayOfWeek.Wednesday.Previous(), Is.EqualTo(DayOfWeek.Tuesday));
Assert.AreEqual(DayOfWeek.Friday, DayOfWeek.Saturday.Previous()); 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() public void PreviousUnchecked()
{ {
Assert.AreEqual(DayOfWeek.Sunday, DayOfWeek.Monday.PreviousUnchecked()); Assert.Multiple(() =>
Assert.AreEqual(DayOfWeek.Monday, DayOfWeek.Tuesday.PreviousUnchecked()); {
Assert.AreEqual(DayOfWeek.Tuesday, DayOfWeek.Wednesday.PreviousUnchecked()); Assert.That(DayOfWeek.Monday.PreviousUnchecked(), Is.EqualTo(DayOfWeek.Sunday));
Assert.AreEqual(DayOfWeek.Wednesday, DayOfWeek.Thursday.PreviousUnchecked()); Assert.That(DayOfWeek.Tuesday.PreviousUnchecked(), Is.EqualTo(DayOfWeek.Monday));
Assert.AreEqual(DayOfWeek.Thursday, DayOfWeek.Friday.PreviousUnchecked()); Assert.That(DayOfWeek.Wednesday.PreviousUnchecked(), Is.EqualTo(DayOfWeek.Tuesday));
Assert.AreEqual(DayOfWeek.Friday, DayOfWeek.Saturday.PreviousUnchecked()); Assert.That(DayOfWeek.Thursday.PreviousUnchecked(), Is.EqualTo(DayOfWeek.Wednesday));
Assert.ThrowsException<IndexOutOfRangeException>(() => DayOfWeek.Sunday.PreviousUnchecked()); 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 #if NET6_0_OR_GREATER
using System.Runtime.Intrinsics; using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86; using System.Runtime.Intrinsics.X86;
using Microsoft.VisualStudio.TestTools.UnitTesting; using NUnit.Framework;
using X10D.Core; using X10D.Core;
namespace X10D.Tests.Core; namespace X10D.Tests.Core;
[TestClass] [TestFixture]
public class IntrinsicTests internal class IntrinsicTests
{ {
[TestMethod] [Test]
public void CorrectBoolean_ShouldReturnExpectedVector64Result_GivenInputVector() public void CorrectBoolean_ShouldReturnExpectedVector64Result_GivenInputVector()
{ {
var inputVector = Vector64.Create(0, 1, 2, 0, 3, 0, 0, (byte)4); var inputVector = Vector64.Create(0, 1, 2, 0, 3, 0, 0, (byte)4);
@ -17,10 +17,10 @@ public class IntrinsicTests
Vector64<byte> result = inputVector.CorrectBoolean(); Vector64<byte> result = inputVector.CorrectBoolean();
Assert.AreEqual(expectedResult, result); Assert.That(result, Is.EqualTo(expectedResult));
} }
[TestMethod] [Test]
public void CorrectBooleanInternal_Fallback_ShouldReturnExpectedVector128Result_GivenInputVector() public void CorrectBooleanInternal_Fallback_ShouldReturnExpectedVector128Result_GivenInputVector()
{ {
var inputVector = Vector128.Create(0, 1, 2, 0, 3, 0, 0, 4, 5, 0, 0, 6, 0, 0, 7, (byte)8); var inputVector = Vector128.Create(0, 1, 2, 0, 3, 0, 0, 4, 5, 0, 0, 6, 0, 0, 7, (byte)8);
@ -28,10 +28,10 @@ public class IntrinsicTests
Vector128<byte> result = inputVector.CorrectBooleanInternal_Fallback(); Vector128<byte> result = inputVector.CorrectBooleanInternal_Fallback();
Assert.AreEqual(expectedResult, result); Assert.That(result, Is.EqualTo(expectedResult));
} }
[TestMethod] [Test]
public void CorrectBooleanInternal_Sse2_ShouldReturnExpectedVector128Result_GivenInputVector() public void CorrectBooleanInternal_Sse2_ShouldReturnExpectedVector128Result_GivenInputVector()
{ {
if (!Sse2.IsSupported) if (!Sse2.IsSupported)
@ -44,10 +44,10 @@ public class IntrinsicTests
Vector128<byte> result = inputVector.CorrectBooleanInternal_Sse2(); Vector128<byte> result = inputVector.CorrectBooleanInternal_Sse2();
Assert.AreEqual(expectedResult, result); Assert.That(result, Is.EqualTo(expectedResult));
} }
[TestMethod] [Test]
public void CorrectBooleanInternal_Avx2_ShouldReturnExpectedVector256Result_GivenInputVector() public void CorrectBooleanInternal_Avx2_ShouldReturnExpectedVector256Result_GivenInputVector()
{ {
if (!Avx2.IsSupported) if (!Avx2.IsSupported)
@ -62,10 +62,10 @@ public class IntrinsicTests
Vector256<byte> result = inputVector.CorrectBooleanInternal_Avx2(); Vector256<byte> result = inputVector.CorrectBooleanInternal_Avx2();
Assert.AreEqual(expectedResult, result); Assert.That(result, Is.EqualTo(expectedResult));
} }
[TestMethod] [Test]
public void CorrectBooleanInternal_Fallback_ShouldReturnExpectedVector256Result_GivenInputVector() public void CorrectBooleanInternal_Fallback_ShouldReturnExpectedVector256Result_GivenInputVector()
{ {
var inputVector = Vector256.Create(0, 1, 2, 0, 3, 0, 0, 4, 5, 0, 0, 6, 0, 0, 7, 8, 0, 1, 2, 0, 3, 0, 0, 4, 5, 0, 0, 6, 0, var inputVector = Vector256.Create(0, 1, 2, 0, 3, 0, 0, 4, 5, 0, 0, 6, 0, 0, 7, 8, 0, 1, 2, 0, 3, 0, 0, 4, 5, 0, 0, 6, 0,
@ -75,10 +75,10 @@ public class IntrinsicTests
Vector256<byte> result = inputVector.CorrectBooleanInternal_Fallback(); Vector256<byte> result = inputVector.CorrectBooleanInternal_Fallback();
Assert.AreEqual(expectedResult, result); Assert.That(result, Is.EqualTo(expectedResult));
} }
[TestMethod] [Test]
public void HorizontalOr_ShouldReturnCombinedVector_GivenInputVector128OfUInt32() public void HorizontalOr_ShouldReturnCombinedVector_GivenInputVector128OfUInt32()
{ {
Vector128<uint> left = Vector128.Create(1U, 2U, 3U, 4U); Vector128<uint> left = Vector128.Create(1U, 2U, 3U, 4U);
@ -87,10 +87,10 @@ public class IntrinsicTests
Vector128<uint> expected = Vector128.Create(3U, 7U, 7U, 15U); Vector128<uint> expected = Vector128.Create(3U, 7U, 7U, 15U);
Vector128<uint> actual = IntrinsicUtility.HorizontalOr(left, right); Vector128<uint> actual = IntrinsicUtility.HorizontalOr(left, right);
Assert.AreEqual(expected, actual); Assert.That(actual, Is.EqualTo(expected));
} }
[TestMethod] [Test]
public void HorizontalOrInternal_Sse_ShouldReturnCombinedVector_GivenInputVector128OfInt32() public void HorizontalOrInternal_Sse_ShouldReturnCombinedVector_GivenInputVector128OfInt32()
{ {
Vector128<int> left = Vector128.Create(1, 2, 3, 4); Vector128<int> left = Vector128.Create(1, 2, 3, 4);
@ -99,10 +99,10 @@ public class IntrinsicTests
Vector128<int> expected = Vector128.Create(3, 7, 7, 15); Vector128<int> expected = Vector128.Create(3, 7, 7, 15);
Vector128<int> actual = IntrinsicUtility.HorizontalOr_Sse(left, right); Vector128<int> actual = IntrinsicUtility.HorizontalOr_Sse(left, right);
Assert.AreEqual(expected, actual); Assert.That(actual, Is.EqualTo(expected));
} }
[TestMethod] [Test]
public void HorizontalOrInternal_Fallback_ShouldReturnCombinedVector_GivenInputVector128OfInt32() public void HorizontalOrInternal_Fallback_ShouldReturnCombinedVector_GivenInputVector128OfInt32()
{ {
Vector128<int> left = Vector128.Create(1, 2, 3, 4); Vector128<int> left = Vector128.Create(1, 2, 3, 4);
@ -111,10 +111,10 @@ public class IntrinsicTests
Vector128<int> expected = Vector128.Create(3, 7, 7, 15); Vector128<int> expected = Vector128.Create(3, 7, 7, 15);
Vector128<int> actual = IntrinsicUtility.HorizontalOrInternal_Fallback(left, right); Vector128<int> actual = IntrinsicUtility.HorizontalOrInternal_Fallback(left, right);
Assert.AreEqual(expected, actual); Assert.That(actual, Is.EqualTo(expected));
} }
[TestMethod] [Test]
public void Multiply_ShouldReturnMultipliedVector_GivenInputVector128OfInt64() public void Multiply_ShouldReturnMultipliedVector_GivenInputVector128OfInt64()
{ {
Vector128<long> left = Vector128.Create(6L, 4L); Vector128<long> left = Vector128.Create(6L, 4L);
@ -123,10 +123,10 @@ public class IntrinsicTests
Vector128<long> expected = Vector128.Create(12L, 12L); Vector128<long> expected = Vector128.Create(12L, 12L);
Vector128<long> actual = IntrinsicUtility.Multiply(left, right); Vector128<long> actual = IntrinsicUtility.Multiply(left, right);
Assert.AreEqual(expected, actual); Assert.That(actual, Is.EqualTo(expected));
} }
[TestMethod] [Test]
public void MultiplyInternal_Sse2_ShouldReturnMultipliedVector_GivenInputVector128OfUInt64() public void MultiplyInternal_Sse2_ShouldReturnMultipliedVector_GivenInputVector128OfUInt64()
{ {
if (!Sse2.IsSupported) if (!Sse2.IsSupported)
@ -140,10 +140,10 @@ public class IntrinsicTests
Vector128<ulong> expected = Vector128.Create(12UL, 12UL); Vector128<ulong> expected = Vector128.Create(12UL, 12UL);
Vector128<ulong> actual = IntrinsicUtility.MultiplyInternal_Sse2(left, right); Vector128<ulong> actual = IntrinsicUtility.MultiplyInternal_Sse2(left, right);
Assert.AreEqual(expected, actual); Assert.That(actual, Is.EqualTo(expected));
} }
[TestMethod] [Test]
public void MultiplyInternal_Fallback_ShouldReturnMultipliedVector_GivenInputVector128OfUInt64() public void MultiplyInternal_Fallback_ShouldReturnMultipliedVector_GivenInputVector128OfUInt64()
{ {
Vector128<ulong> left = Vector128.Create(6UL, 4UL); Vector128<ulong> left = Vector128.Create(6UL, 4UL);
@ -152,10 +152,10 @@ public class IntrinsicTests
Vector128<ulong> expected = Vector128.Create(12UL, 12UL); Vector128<ulong> expected = Vector128.Create(12UL, 12UL);
Vector128<ulong> actual = IntrinsicUtility.MultiplyInternal_Fallback(left, right); Vector128<ulong> actual = IntrinsicUtility.MultiplyInternal_Fallback(left, right);
Assert.AreEqual(expected, actual); Assert.That(actual, Is.EqualTo(expected));
} }
[TestMethod] [Test]
public void Multiply_ShouldReturnMultipliedVector_GivenInputVector256OfInt64() public void Multiply_ShouldReturnMultipliedVector_GivenInputVector256OfInt64()
{ {
Vector256<long> left = Vector256.Create(4L, 6L, 8L, 10L); Vector256<long> left = Vector256.Create(4L, 6L, 8L, 10L);
@ -164,10 +164,10 @@ public class IntrinsicTests
Vector256<long> expected = Vector256.Create(8L, 18L, 32L, 50L); Vector256<long> expected = Vector256.Create(8L, 18L, 32L, 50L);
Vector256<long> actual = IntrinsicUtility.Multiply(left, right); Vector256<long> actual = IntrinsicUtility.Multiply(left, right);
Assert.AreEqual(expected, actual); Assert.That(actual, Is.EqualTo(expected));
} }
[TestMethod] [Test]
public void MultiplyInternal_Avx2_ShouldReturnMultipliedVector_GivenInputVector256OfUInt64() public void MultiplyInternal_Avx2_ShouldReturnMultipliedVector_GivenInputVector256OfUInt64()
{ {
if (!Avx2.IsSupported) if (!Avx2.IsSupported)
@ -181,10 +181,10 @@ public class IntrinsicTests
Vector256<ulong> expected = Vector256.Create(8UL, 18UL, 32UL, 50UL); Vector256<ulong> expected = Vector256.Create(8UL, 18UL, 32UL, 50UL);
Vector256<ulong> actual = IntrinsicUtility.MultiplyInternal_Avx2(left, right); Vector256<ulong> actual = IntrinsicUtility.MultiplyInternal_Avx2(left, right);
Assert.AreEqual(expected, actual); Assert.That(actual, Is.EqualTo(expected));
} }
[TestMethod] [Test]
public void MultiplyInternal_Fallback_ShouldReturnMultipliedVector_GivenInputVector256OfUInt64() public void MultiplyInternal_Fallback_ShouldReturnMultipliedVector_GivenInputVector256OfUInt64()
{ {
Vector256<ulong> left = Vector256.Create(4UL, 6UL, 8UL, 10UL); Vector256<ulong> left = Vector256.Create(4UL, 6UL, 8UL, 10UL);
@ -193,10 +193,10 @@ public class IntrinsicTests
Vector256<ulong> expected = Vector256.Create(8UL, 18UL, 32UL, 50UL); Vector256<ulong> expected = Vector256.Create(8UL, 18UL, 32UL, 50UL);
Vector256<ulong> actual = IntrinsicUtility.MultiplyInternal_Fallback(left, right); Vector256<ulong> actual = IntrinsicUtility.MultiplyInternal_Fallback(left, right);
Assert.AreEqual(expected, actual); Assert.That(actual, Is.EqualTo(expected));
} }
[TestMethod] [Test]
public void ReverseElementsInternal_Fallback_ShouldReturnExpectedVector128Result_GivenInputVector() public void ReverseElementsInternal_Fallback_ShouldReturnExpectedVector128Result_GivenInputVector()
{ {
var inputVector = Vector128.Create(42UL, 69UL); var inputVector = Vector128.Create(42UL, 69UL);
@ -204,10 +204,10 @@ public class IntrinsicTests
Vector128<ulong> result = inputVector.ReverseElementsInternal_Fallback(); Vector128<ulong> result = inputVector.ReverseElementsInternal_Fallback();
Assert.AreEqual(expectedResult, result); Assert.That(result, Is.EqualTo(expectedResult));
} }
[TestMethod] [Test]
public void ReverseElementsInternal_Sse2_ShouldReturnExpectedVector128Result_GivenInputVector() public void ReverseElementsInternal_Sse2_ShouldReturnExpectedVector128Result_GivenInputVector()
{ {
if (!Sse2.IsSupported) if (!Sse2.IsSupported)
@ -220,7 +220,7 @@ public class IntrinsicTests
Vector128<ulong> result = inputVector.ReverseElementsInternal_Sse2(); Vector128<ulong> result = inputVector.ReverseElementsInternal_Sse2();
Assert.AreEqual(expectedResult, result); Assert.That(result, Is.EqualTo(expectedResult));
} }
} }
#endif #endif

View File

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

View File

@ -1,121 +1,121 @@
using Microsoft.VisualStudio.TestTools.UnitTesting; using NUnit.Framework;
using X10D.Collections; using X10D.Collections;
using X10D.Core; using X10D.Core;
namespace X10D.Tests.Core; namespace X10D.Tests.Core;
[TestClass] [TestFixture]
public class RandomTests internal class RandomTests
{ {
[TestMethod] [Test]
public void NextBoolean_ShouldBeFalse_GivenSeed1234() public void NextBoolean_ShouldBeFalse_GivenSeed1234()
{ {
var random = new Random(1234); var random = new Random(1234);
Assert.IsFalse(random.NextBoolean()); Assert.That(random.NextBoolean(), Is.False);
} }
[TestMethod] [Test]
public void NextBoolean_ShouldThrow_GivenNull() public void NextBoolean_ShouldThrow_GivenNull()
{ {
Random? random = null; Random random = null!;
Assert.ThrowsException<ArgumentNullException>(() => random!.NextBoolean()); Assert.Throws<ArgumentNullException>(() => random.NextBoolean());
} }
[TestMethod] [Test]
public void NextByte_ShouldBe101_GivenSeed1234() public void NextByte_ShouldBe101_GivenSeed1234()
{ {
var random = new Random(1234); 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() public void NextByte_WithMax10_ShouldBe3_GivenSeed1234()
{ {
var random = new Random(1234); 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() public void NextByte_WithMin0Max10_ShouldBe3_GivenSeed1234()
{ {
var random = new Random(1234); 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() public void NextByte_ShouldThrow_GivenNull()
{ {
Random? random = null; Random? random = null;
Assert.ThrowsException<ArgumentNullException>(() => random!.NextByte()); Assert.Throws<ArgumentNullException>(() => random!.NextByte());
Assert.ThrowsException<ArgumentNullException>(() => random!.NextByte(10)); Assert.Throws<ArgumentNullException>(() => random!.NextByte(10));
Assert.ThrowsException<ArgumentNullException>(() => random!.NextByte(0, 10)); Assert.Throws<ArgumentNullException>(() => random!.NextByte(0, 10));
} }
[TestMethod] [Test]
public void NextDouble_WithMax10_ShouldBe3point9908097935797695_GivenSeed1234() public void NextDouble_WithMax10_ShouldBe3point9908097935797695_GivenSeed1234()
{ {
var random = new Random(1234); 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() public void NextDouble_WithMin0Max10_ShouldBe3point9908097935797695_GivenSeed1234()
{ {
var random = new Random(1234); 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() public void NextDouble_ShouldThrow_GivenNull()
{ {
Random? random = null; Random? random = null;
Assert.ThrowsException<ArgumentNullException>(() => random!.NextDouble(10)); Assert.Throws<ArgumentNullException>(() => random!.NextDouble(10));
Assert.ThrowsException<ArgumentNullException>(() => random!.NextDouble(0, 10)); Assert.Throws<ArgumentNullException>(() => random!.NextDouble(0, 10));
} }
[TestMethod] [Test]
public void NextDouble_ShouldThrow_GivenMaxLessThan0() public void NextDouble_ShouldThrow_GivenMaxLessThan0()
{ {
var random = new Random(1234); var random = new Random(1234);
Assert.ThrowsException<ArgumentOutOfRangeException>(() => random.NextDouble(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => random.NextDouble(-1));
} }
[TestMethod] [Test]
public void NextDouble_ShouldThrow_GivenMaxLessThanMin() public void NextDouble_ShouldThrow_GivenMaxLessThanMin()
{ {
var random = new Random(1234); 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() public void NextEnum_ShouldBeTuesday_GivenSeed1234()
{ {
var random = new Random(1234); 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() public void NextEnum_ShouldThrow_GivenNull()
{ {
Random? random = null; Random? random = null;
Assert.ThrowsException<ArgumentNullException>(() => random!.Next<DayOfWeek>()); Assert.Throws<ArgumentNullException>(() => random!.Next<DayOfWeek>());
} }
[TestMethod] [Test]
public void NextFrom_ShouldThrow_GivenNullRandom() public void NextFrom_ShouldThrow_GivenNullRandom()
{ {
Random? random = null; Random? random = null;
Assert.ThrowsException<ArgumentNullException>(() => random!.NextFrom("")); Assert.Throws<ArgumentNullException>(() => random!.NextFrom(""));
} }
[TestMethod] [Test]
public void NextFrom_ShouldThrow_GivenNullSource() public void NextFrom_ShouldThrow_GivenNullSource()
{ {
var random = new Random(1234); 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() public void NextFrom_ShouldEnumerate_GivenNonList()
{ {
IEnumerable<int> Source() IEnumerable<int> Source()
@ -124,168 +124,168 @@ public class RandomTests
} }
var random = new Random(1234); 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() public void NextFromSpan_ShouldThrow_GivenNullRandom()
{ {
Random? random = null; Random? random = null;
Assert.ThrowsException<ArgumentNullException>(() => Assert.Throws<ArgumentNullException>(() =>
{ {
Span<int> span = stackalloc int[1]; Span<int> span = stackalloc int[1];
return random!.NextFrom(span); _ = random!.NextFrom(span);
}); });
} }
[TestMethod] [Test]
public void NextFromReadOnlySpan_ShouldThrow_GivenNullRandom() public void NextFromReadOnlySpan_ShouldThrow_GivenNullRandom()
{ {
Random? random = null; Random? random = null;
Assert.ThrowsException<ArgumentNullException>(() => Assert.Throws<ArgumentNullException>(() =>
{ {
Span<int> span = stackalloc int[1]; Span<int> span = stackalloc int[1];
return random!.NextFrom(span.AsReadOnly()); _ = random!.NextFrom(span.AsReadOnly());
}); });
} }
[TestMethod] [Test]
public void NextFromSpan_ShouldReturnOnlyValue_GivenSpanWithLength1() public void NextFromSpan_ShouldReturnOnlyValue_GivenSpanWithLength1()
{ {
Span<int> span = stackalloc int[1]; Span<int> span = stackalloc int[1];
span[0] = 42; span[0] = 42;
var random = new Random(1234); var random = new Random(1234);
Assert.AreEqual(42, random.NextFrom(span)); Assert.That(random.NextFrom(span), Is.EqualTo(42));
} }
[TestMethod] [Test]
public void NextFromReadOnlySpan_ShouldReturnOnlyValue_GivenSpanWithLength1() public void NextFromReadOnlySpan_ShouldReturnOnlyValue_GivenSpanWithLength1()
{ {
Span<int> span = stackalloc int[1]; Span<int> span = stackalloc int[1];
span[0] = 42; span[0] = 42;
var random = new Random(1234); var random = new Random(1234);
Assert.AreEqual(42, random.NextFrom(span.AsReadOnly())); Assert.That(random.NextFrom(span.AsReadOnly()), Is.EqualTo(42));
} }
[TestMethod] [Test]
public void NextInt16_ShouldBe13076_GivenSeed1234() public void NextInt16_ShouldBe13076_GivenSeed1234()
{ {
var random = new Random(1234); 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() public void NextInt16_WithMax10_ShouldBe3_GivenSeed1234()
{ {
var random = new Random(1234); 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() public void NextInt16_WithMin0Max10_ShouldBe3_GivenSeed1234()
{ {
var random = new Random(1234); 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() public void NextInt16_ShouldThrow_GivenMaxLessThan0()
{ {
var random = new Random(1234); var random = new Random(1234);
Assert.ThrowsException<ArgumentOutOfRangeException>(() => random.NextInt16(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => random.NextInt16(-1));
} }
[TestMethod] [Test]
public void NextInt16_ShouldThrow_GivenNull() public void NextInt16_ShouldThrow_GivenNull()
{ {
Random? random = null; Random? random = null;
Assert.ThrowsException<ArgumentNullException>(() => random!.NextInt16()); Assert.Throws<ArgumentNullException>(() => random!.NextInt16());
Assert.ThrowsException<ArgumentNullException>(() => random!.NextInt16(10)); Assert.Throws<ArgumentNullException>(() => random!.NextInt16(10));
Assert.ThrowsException<ArgumentNullException>(() => random!.NextInt16(0, 10)); Assert.Throws<ArgumentNullException>(() => random!.NextInt16(0, 10));
} }
[TestMethod] [Test]
public void NextSingle_WithMax10_ShouldBe3point99081_GivenSeed1234() public void NextSingle_WithMax10_ShouldBe3point99081_GivenSeed1234()
{ {
var random = new Random(1234); 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() public void NextSingle_WithMin0Max10_ShouldBe3point99081_GivenSeed1234()
{ {
var random = new Random(1234); 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() public void NextSingle_ShouldThrow_GivenNull()
{ {
Random? random = null; Random? random = null;
Assert.ThrowsException<ArgumentNullException>(() => random!.NextSingle(10)); Assert.Throws<ArgumentNullException>(() => random!.NextSingle(10));
Assert.ThrowsException<ArgumentNullException>(() => random!.NextSingle(0, 10)); Assert.Throws<ArgumentNullException>(() => random!.NextSingle(0, 10));
#if !NET6_0_OR_GREATER #if !NET6_0_OR_GREATER
Assert.ThrowsException<ArgumentNullException>(() => random!.NextSingle()); Assert.Throws<ArgumentNullException>(() => random!.NextSingle());
#endif #endif
} }
[TestMethod] [Test]
public void NextSingle_ShouldThrow_GivenMaxLessThan0() public void NextSingle_ShouldThrow_GivenMaxLessThan0()
{ {
var random = new Random(1234); var random = new Random(1234);
Assert.ThrowsException<ArgumentOutOfRangeException>(() => random.NextSingle(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => random.NextSingle(-1));
} }
[TestMethod] [Test]
public void NextSingle_ShouldThrow_GivenMaxLessThanMin() public void NextSingle_ShouldThrow_GivenMaxLessThanMin()
{ {
var random = new Random(1234); 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() public void NextString_ShouldBe_kxiyiyvnqi_GivenSeed1234()
{ {
const string alphabet = "abcdefghijklmnopqrstuvwxyz"; const string alphabet = "abcdefghijklmnopqrstuvwxyz";
var random = new Random(1234); var random = new Random(1234);
Assert.AreEqual("kxiyiyvnqi", random.NextString(alphabet.ToCharArray(), 10)); Assert.That(random.NextString(alphabet.ToCharArray(), 10), Is.EqualTo("kxiyiyvnqi"));
} }
[TestMethod] [Test]
public void NextString_ShouldBeEmpty_GivenLength0() public void NextString_ShouldBeEmpty_GivenLength0()
{ {
var random = new Random(1234); 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() public void NextString_ShouldBeLength1_GivenLength1()
{ {
var random = new Random(1234); 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() public void NextString_ShouldThrow_GivenNullRandom()
{ {
Random? random = null; 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() public void NextString_ShouldThrow_GivenNullSource()
{ {
var random = new Random(1234); 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() public void NextString_ShouldThrow_GivenNegativeLength()
{ {
var random = new Random(1234); 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.Arm;
using System.Runtime.Intrinsics.X86; using System.Runtime.Intrinsics.X86;
#endif #endif
using Microsoft.VisualStudio.TestTools.UnitTesting; using NUnit.Framework;
using X10D.Core; using X10D.Core;
namespace X10D.Tests.Core; namespace X10D.Tests.Core;
[TestClass] [TestFixture]
public class SpanTest internal class SpanTest
{ {
[TestMethod] [Test]
public void Contains_ShouldReturnFalse_GivenReadOnlySpanWithNoMatchingElements_UsingByteEnum() public void Contains_ShouldReturnFalse_GivenReadOnlySpanWithNoMatchingElements_UsingByteEnum()
{
Assert.Multiple(() =>
{ {
ReadOnlySpan<EnumByte> span = stackalloc EnumByte[1] {EnumByte.B}; ReadOnlySpan<EnumByte> span = stackalloc EnumByte[1] {EnumByte.B};
Assert.That(span.Contains(EnumByte.A), Is.False);
Assert.IsFalse(span.Contains(EnumByte.A)); Assert.That(span.Contains(EnumByte.C), Is.False);
Assert.IsFalse(span.Contains(EnumByte.C)); });
} }
[TestMethod] [Test]
public void Contains_ShouldReturnFalse_GivenReadOnlySpanWithNoMatchingElements_UsingInt16Enum() public void Contains_ShouldReturnFalse_GivenReadOnlySpanWithNoMatchingElements_UsingInt16Enum()
{
Assert.Multiple(() =>
{ {
ReadOnlySpan<EnumInt16> span = stackalloc EnumInt16[1] {EnumInt16.B}; ReadOnlySpan<EnumInt16> span = stackalloc EnumInt16[1] {EnumInt16.B};
Assert.That(span.Contains(EnumInt16.A), Is.False);
Assert.IsFalse(span.Contains(EnumInt16.A)); Assert.That(span.Contains(EnumInt16.C), Is.False);
Assert.IsFalse(span.Contains(EnumInt16.C)); });
} }
[TestMethod] [Test]
public void Contains_ShouldReturnFalse_GivenReadOnlySpanWithNoMatchingElements_UsingInt32Enum() public void Contains_ShouldReturnFalse_GivenReadOnlySpanWithNoMatchingElements_UsingInt32Enum()
{
Assert.Multiple(() =>
{ {
ReadOnlySpan<EnumInt32> span = stackalloc EnumInt32[1] {EnumInt32.B}; ReadOnlySpan<EnumInt32> span = stackalloc EnumInt32[1] {EnumInt32.B};
Assert.That(span.Contains(EnumInt32.A), Is.False);
Assert.IsFalse(span.Contains(EnumInt32.A)); Assert.That(span.Contains(EnumInt32.C), Is.False);
Assert.IsFalse(span.Contains(EnumInt32.C)); });
} }
[TestMethod] [Test]
public void Contains_ShouldReturnFalse_GivenReadOnlySpanWithNoMatchingElements_UsingInt64Enum() public void Contains_ShouldReturnFalse_GivenReadOnlySpanWithNoMatchingElements_UsingInt64Enum()
{
Assert.Multiple(() =>
{ {
ReadOnlySpan<EnumInt64> span = stackalloc EnumInt64[1] {EnumInt64.B}; ReadOnlySpan<EnumInt64> span = stackalloc EnumInt64[1] {EnumInt64.B};
Assert.IsFalse(span.Contains(EnumInt64.A)); Assert.That(span.Contains(EnumInt64.A), Is.False);
Assert.IsFalse(span.Contains(EnumInt64.C)); Assert.That(span.Contains(EnumInt64.C), Is.False);
});
} }
[TestMethod] [Test]
public void Contains_ShouldReturnTrue_GivenReadOnlySpanWithMatchingElements_UsingByteEnum() public void Contains_ShouldReturnTrue_GivenReadOnlySpanWithMatchingElements_UsingByteEnum()
{ {
ReadOnlySpan<EnumByte> span = stackalloc EnumByte[1] {EnumByte.B}; ReadOnlySpan<EnumByte> span = stackalloc EnumByte[1] {EnumByte.B};
Assert.IsTrue(span.Contains(EnumByte.B)); Assert.That(span.Contains(EnumByte.B));
} }
[TestMethod] [Test]
public void Contains_ShouldReturnTrue_GivenReadOnlySpanWithMatchingElements_UsingInt16Enum() public void Contains_ShouldReturnTrue_GivenReadOnlySpanWithMatchingElements_UsingInt16Enum()
{ {
ReadOnlySpan<EnumInt16> span = stackalloc EnumInt16[1] {EnumInt16.B}; ReadOnlySpan<EnumInt16> span = stackalloc EnumInt16[1] {EnumInt16.B};
Assert.IsTrue(span.Contains(EnumInt16.B)); Assert.That(span.Contains(EnumInt16.B));
} }
[TestMethod] [Test]
public void Contains_ShouldReturnTrue_GivenReadOnlySpanWithMatchingElements_UsingInt32Enum() public void Contains_ShouldReturnTrue_GivenReadOnlySpanWithMatchingElements_UsingInt32Enum()
{ {
ReadOnlySpan<EnumInt32> span = stackalloc EnumInt32[1] {EnumInt32.B}; ReadOnlySpan<EnumInt32> span = stackalloc EnumInt32[1] {EnumInt32.B};
Assert.IsTrue(span.Contains(EnumInt32.B)); Assert.That(span.Contains(EnumInt32.B));
} }
[TestMethod] [Test]
public void Contains_ShouldReturnTrue_GivenReadOnlySpanWithMatchingElements_UsingInt64Enum() public void Contains_ShouldReturnTrue_GivenReadOnlySpanWithMatchingElements_UsingInt64Enum()
{ {
ReadOnlySpan<EnumInt64> span = stackalloc EnumInt64[1] {EnumInt64.B}; ReadOnlySpan<EnumInt64> span = stackalloc EnumInt64[1] {EnumInt64.B};
Assert.IsTrue(span.Contains(EnumInt64.B)); Assert.That(span.Contains(EnumInt64.B));
} }
[TestMethod] [Test]
public void Contains_ShouldReturnFalse_GivenSpanWithNoMatchingElements_UsingByteEnum() public void Contains_ShouldReturnFalse_GivenSpanWithNoMatchingElements_UsingByteEnum()
{
Assert.Multiple(() =>
{ {
Span<EnumByte> span = stackalloc EnumByte[1] {EnumByte.B}; Span<EnumByte> span = stackalloc EnumByte[1] {EnumByte.B};
Assert.IsFalse(span.Contains(EnumByte.A)); Assert.That(span.Contains(EnumByte.A), Is.False);
Assert.IsFalse(span.Contains(EnumByte.C)); Assert.That(span.Contains(EnumByte.C), Is.False);
});
} }
[TestMethod] [Test]
public void Contains_ShouldReturnFalse_GivenSpanWithNoMatchingElements_UsingInt16Enum() public void Contains_ShouldReturnFalse_GivenSpanWithNoMatchingElements_UsingInt16Enum()
{ {
Span<EnumInt16> span = stackalloc EnumInt16[1] {EnumInt16.B}; Span<EnumInt16> span = stackalloc EnumInt16[1] {EnumInt16.B};
Assert.IsFalse(span.Contains(EnumInt16.A)); Assert.That(span.Contains(EnumInt16.A), Is.False);
Assert.IsFalse(span.Contains(EnumInt16.C)); Assert.That(span.Contains(EnumInt16.C), Is.False);
} }
[TestMethod] [Test]
public void Contains_ShouldReturnFalse_GivenSpanWithNoMatchingElements_UsingInt32Enum() public void Contains_ShouldReturnFalse_GivenSpanWithNoMatchingElements_UsingInt32Enum()
{ {
Span<EnumInt32> span = stackalloc EnumInt32[1] {EnumInt32.B}; Span<EnumInt32> span = stackalloc EnumInt32[1] {EnumInt32.B};
Assert.IsFalse(span.Contains(EnumInt32.A)); Assert.That(span.Contains(EnumInt32.A), Is.False);
Assert.IsFalse(span.Contains(EnumInt32.C)); Assert.That(span.Contains(EnumInt32.C), Is.False);
} }
[TestMethod] [Test]
public void Contains_ShouldReturnFalse_GivenSpanWithNoMatchingElements_UsingInt64Enum() public void Contains_ShouldReturnFalse_GivenSpanWithNoMatchingElements_UsingInt64Enum()
{ {
Span<EnumInt64> span = stackalloc EnumInt64[1] {EnumInt64.B}; Span<EnumInt64> span = stackalloc EnumInt64[1] {EnumInt64.B};
Assert.IsFalse(span.Contains(EnumInt64.A)); Assert.That(span.Contains(EnumInt64.A), Is.False);
Assert.IsFalse(span.Contains(EnumInt64.C)); Assert.That(span.Contains(EnumInt64.C), Is.False);
} }
[TestMethod] [Test]
public void Contains_ShouldReturnTrue_GivenSpanWithMatchingElements_UsingByteEnum() public void Contains_ShouldReturnTrue_GivenSpanWithMatchingElements_UsingByteEnum()
{ {
Span<EnumByte> span = stackalloc EnumByte[1] {EnumByte.B}; Span<EnumByte> span = stackalloc EnumByte[1] {EnumByte.B};
Assert.IsTrue(span.Contains(EnumByte.B)); Assert.That(span.Contains(EnumByte.B));
} }
[TestMethod] [Test]
public void Contains_ShouldReturnTrue_GivenSpanWithMatchingElements_UsingInt16Enum() public void Contains_ShouldReturnTrue_GivenSpanWithMatchingElements_UsingInt16Enum()
{ {
Span<EnumInt16> span = stackalloc EnumInt16[1] {EnumInt16.B}; Span<EnumInt16> span = stackalloc EnumInt16[1] {EnumInt16.B};
Assert.IsTrue(span.Contains(EnumInt16.B)); Assert.That(span.Contains(EnumInt16.B));
} }
[TestMethod] [Test]
public void Contains_ShouldReturnTrue_GivenSpanWithMatchingElements_UsingInt32Enum() public void Contains_ShouldReturnTrue_GivenSpanWithMatchingElements_UsingInt32Enum()
{ {
Span<EnumInt32> span = stackalloc EnumInt32[1] {EnumInt32.B}; Span<EnumInt32> span = stackalloc EnumInt32[1] {EnumInt32.B};
Assert.IsTrue(span.Contains(EnumInt32.B)); Assert.That(span.Contains(EnumInt32.B));
} }
[TestMethod] [Test]
public void Contains_ShouldReturnTrue_GivenSpanWithMatchingElements_UsingInt64Enum() public void Contains_ShouldReturnTrue_GivenSpanWithMatchingElements_UsingInt64Enum()
{ {
Span<EnumInt64> span = stackalloc EnumInt64[1] {EnumInt64.B}; Span<EnumInt64> span = stackalloc EnumInt64[1] {EnumInt64.B};
Assert.IsTrue(span.Contains(EnumInt64.B)); Assert.That(span.Contains(EnumInt64.B));
} }
[TestMethod] [Test]
public void PackByte_ShouldThrowArgumentException_GivenSpanLengthGreaterThan8() public void PackByte_ShouldThrowArgumentException_GivenSpanLengthGreaterThan8()
{ {
Assert.ThrowsException<ArgumentException>(() => Assert.Throws<ArgumentException>(() =>
{ {
Span<bool> span = stackalloc bool[9]; Span<bool> span = stackalloc bool[9];
return span.PackByte(); _ = span.PackByte();
}); });
} }
[TestMethod] [Test]
public void PackInt16_ShouldThrowArgumentException_GivenSpanLengthGreaterThan16() public void PackInt16_ShouldThrowArgumentException_GivenSpanLengthGreaterThan16()
{ {
Assert.ThrowsException<ArgumentException>(() => Assert.Throws<ArgumentException>(() =>
{ {
Span<bool> span = stackalloc bool[17]; Span<bool> span = stackalloc bool[17];
return span.PackInt16(); _ = span.PackInt16();
}); });
} }
[TestMethod] [Test]
public void PackInt32_ShouldThrowArgumentException_GivenSpanLengthGreaterThan32() public void PackInt32_ShouldThrowArgumentException_GivenSpanLengthGreaterThan32()
{ {
Assert.ThrowsException<ArgumentException>(() => Assert.Throws<ArgumentException>(() =>
{ {
Span<bool> span = stackalloc bool[33]; Span<bool> span = stackalloc bool[33];
return span.PackInt32(); _ = span.PackInt32();
}); });
} }
[TestMethod] [Test]
public void PackInt64_ShouldThrowArgumentException_GivenSpanLengthGreaterThan64() public void PackInt64_ShouldThrowArgumentException_GivenSpanLengthGreaterThan64()
{ {
Assert.ThrowsException<ArgumentException>(() => Assert.Throws<ArgumentException>(() =>
{ {
Span<bool> span = stackalloc bool[65]; Span<bool> span = stackalloc bool[65];
return span.PackInt64(); _ = span.PackInt64();
}); });
} }
[TestMethod] [Test]
public void PackByteInternal_Fallback_ShouldReturnCorrectByte_GivenReadOnlySpan_Using() public void PackByteInternal_Fallback_ShouldReturnCorrectByte_GivenReadOnlySpan_Using()
{ {
const byte expected = 0b00110011; const byte expected = 0b00110011;
@ -194,11 +206,11 @@ public class SpanTest
byte actual = span.PackByteInternal_Fallback(); byte actual = span.PackByteInternal_Fallback();
Assert.AreEqual(expected, actual); Assert.That(actual, Is.EqualTo(expected));
} }
#if NET5_0_OR_GREATER #if NET5_0_OR_GREATER
[TestMethod] [Test]
public void PackByteInternal_Sse2_ShouldReturnCorrectByte_GivenReadOnlySpan_Using() public void PackByteInternal_Sse2_ShouldReturnCorrectByte_GivenReadOnlySpan_Using()
{ {
if (!Sse2.IsSupported) if (!Sse2.IsSupported)
@ -211,10 +223,10 @@ public class SpanTest
byte actual = span.PackByteInternal_Sse2(); byte actual = span.PackByteInternal_Sse2();
Assert.AreEqual(expected, actual); Assert.That(actual, Is.EqualTo(expected));
} }
[TestMethod] [Test]
public void PackByteInternal_AdvSimd_ShouldReturnCorrectByte_GivenReadOnlySpan_Using() public void PackByteInternal_AdvSimd_ShouldReturnCorrectByte_GivenReadOnlySpan_Using()
{ {
if (!AdvSimd.IsSupported) if (!AdvSimd.IsSupported)
@ -227,11 +239,11 @@ public class SpanTest
byte actual = span.PackByteInternal_AdvSimd(); byte actual = span.PackByteInternal_AdvSimd();
Assert.AreEqual(expected, actual); Assert.That(actual, Is.EqualTo(expected));
} }
#endif #endif
[TestMethod] [Test]
public void PackInt16_ShouldReturnSameAsPackByte_WhenSpanHasLength8() public void PackInt16_ShouldReturnSameAsPackByte_WhenSpanHasLength8()
{ {
ReadOnlySpan<bool> span = stackalloc bool[8] {true, true, false, false, true, true, false, false}; ReadOnlySpan<bool> span = stackalloc bool[8] {true, true, false, false, true, true, false, false};
@ -239,10 +251,10 @@ public class SpanTest
short expected = span.PackByte(); short expected = span.PackByte();
short actual = span.PackInt16(); short actual = span.PackInt16();
Assert.AreEqual(expected, actual); Assert.That(actual, Is.EqualTo(expected));
} }
[TestMethod] [Test]
public void PackInt16Internal_Fallback_ShouldReturnCorrectInt16_GivenReadOnlySpan() public void PackInt16Internal_Fallback_ShouldReturnCorrectInt16_GivenReadOnlySpan()
{ {
const short expected = 0b00101101_11010100; const short expected = 0b00101101_11010100;
@ -253,11 +265,11 @@ public class SpanTest
short actual = span.PackInt16Internal_Fallback(); short actual = span.PackInt16Internal_Fallback();
Assert.AreEqual(expected, actual); Assert.That(actual, Is.EqualTo(expected));
} }
#if NET5_0_OR_GREATER #if NET5_0_OR_GREATER
[TestMethod] [Test]
public void PackInt16Internal_Sse2_ShouldReturnCorrectInt16_GivenReadOnlySpan_Using() public void PackInt16Internal_Sse2_ShouldReturnCorrectInt16_GivenReadOnlySpan_Using()
{ {
if (!Sse2.IsSupported) if (!Sse2.IsSupported)
@ -273,11 +285,11 @@ public class SpanTest
short actual = span.PackInt16Internal_Sse2(); short actual = span.PackInt16Internal_Sse2();
Assert.AreEqual(expected, actual); Assert.That(actual, Is.EqualTo(expected));
} }
#endif #endif
[TestMethod] [Test]
public void PackInt32Internal_Fallback_ShouldReturnCorrectInt32_GivenReadOnlySpan() public void PackInt32Internal_Fallback_ShouldReturnCorrectInt32_GivenReadOnlySpan()
{ {
const int expected = 0b01010101_10101010_01010101_10101010; const int expected = 0b01010101_10101010_01010101_10101010;
@ -289,11 +301,11 @@ public class SpanTest
int actual = span.PackInt32Internal_Fallback(); int actual = span.PackInt32Internal_Fallback();
Assert.AreEqual(expected, actual); Assert.That(actual, Is.EqualTo(expected));
} }
#if NET5_0_OR_GREATER #if NET5_0_OR_GREATER
[TestMethod] [Test]
public void PackInt32Internal_Sse2_ShouldReturnCorrectInt32_GivenReadOnlySpan() public void PackInt32Internal_Sse2_ShouldReturnCorrectInt32_GivenReadOnlySpan()
{ {
if (!Sse2.IsSupported) if (!Sse2.IsSupported)
@ -310,10 +322,10 @@ public class SpanTest
int actual = span.PackInt32Internal_Sse2(); int actual = span.PackInt32Internal_Sse2();
Assert.AreEqual(expected, actual); Assert.That(actual, Is.EqualTo(expected));
} }
[TestMethod] [Test]
public void PackInt32Internal_Avx2_ShouldReturnCorrectInt32_GivenReadOnlySpan() public void PackInt32Internal_Avx2_ShouldReturnCorrectInt32_GivenReadOnlySpan()
{ {
if (!Avx2.IsSupported) if (!Avx2.IsSupported)
@ -330,10 +342,10 @@ public class SpanTest
int actual = span.PackInt32Internal_Avx2(); int actual = span.PackInt32Internal_Avx2();
Assert.AreEqual(expected, actual); Assert.That(actual, Is.EqualTo(expected));
} }
[TestMethod] [Test]
public void PackInt32Internal_AdvSimd_ShouldReturnCorrectInt32_GivenReadOnlySpan() public void PackInt32Internal_AdvSimd_ShouldReturnCorrectInt32_GivenReadOnlySpan()
{ {
if (!AdvSimd.IsSupported) if (!AdvSimd.IsSupported)
@ -350,11 +362,11 @@ public class SpanTest
int actual = span.PackInt32Internal_AdvSimd(); int actual = span.PackInt32Internal_AdvSimd();
Assert.AreEqual(expected, actual); Assert.That(actual, Is.EqualTo(expected));
} }
#endif #endif
[TestMethod] [Test]
public void PackInt32_ShouldReturnSameAsPackByte_WhenSpanHasLength8_UsingReadOnlySpan() public void PackInt32_ShouldReturnSameAsPackByte_WhenSpanHasLength8_UsingReadOnlySpan()
{ {
ReadOnlySpan<bool> span = stackalloc bool[8] {true, true, false, false, true, true, false, false}; ReadOnlySpan<bool> span = stackalloc bool[8] {true, true, false, false, true, true, false, false};
@ -362,10 +374,10 @@ public class SpanTest
int expected = span.PackByte(); int expected = span.PackByte();
int actual = span.PackInt32(); int actual = span.PackInt32();
Assert.AreEqual(expected, actual); Assert.That(actual, Is.EqualTo(expected));
} }
[TestMethod] [Test]
public void PackInt32_ShouldReturnSameAsPackByte_WhenSpanHasLength8_UsingSpan() public void PackInt32_ShouldReturnSameAsPackByte_WhenSpanHasLength8_UsingSpan()
{ {
Span<bool> span = stackalloc bool[8] {true, true, false, false, true, true, false, false}; Span<bool> span = stackalloc bool[8] {true, true, false, false, true, true, false, false};
@ -373,10 +385,10 @@ public class SpanTest
int expected = span.PackByte(); int expected = span.PackByte();
int actual = span.PackInt32(); int actual = span.PackInt32();
Assert.AreEqual(expected, actual); Assert.That(actual, Is.EqualTo(expected));
} }
[TestMethod] [Test]
public void PackInt32_ShouldReturnSameAsPackInt16_WhenSpanHasLength16_UsingReadOnlySpan() public void PackInt32_ShouldReturnSameAsPackInt16_WhenSpanHasLength16_UsingReadOnlySpan()
{ {
ReadOnlySpan<bool> span = stackalloc bool[16] ReadOnlySpan<bool> span = stackalloc bool[16]
@ -387,10 +399,10 @@ public class SpanTest
int expected = span.PackInt16(); int expected = span.PackInt16();
int actual = span.PackInt32(); int actual = span.PackInt32();
Assert.AreEqual(expected, actual); Assert.That(actual, Is.EqualTo(expected));
} }
[TestMethod] [Test]
public void PackInt32_ShouldReturnSameAsPackInt16_WhenSpanHasLength16_UsingSpan() public void PackInt32_ShouldReturnSameAsPackInt16_WhenSpanHasLength16_UsingSpan()
{ {
Span<bool> span = stackalloc bool[16] Span<bool> span = stackalloc bool[16]
@ -401,10 +413,10 @@ public class SpanTest
int expected = span.PackInt16(); int expected = span.PackInt16();
int actual = span.PackInt32(); int actual = span.PackInt32();
Assert.AreEqual(expected, actual); Assert.That(actual, Is.EqualTo(expected));
} }
[TestMethod] [Test]
public void PackInt64_ShouldReturnCorrectInt64_GivenReadOnlySpan() public void PackInt64_ShouldReturnCorrectInt64_GivenReadOnlySpan()
{ {
const long expected = 0b01010101_11010110_01101001_11010110_00010010_10010111_00101100_10100101; const long expected = 0b01010101_11010110_01101001_11010110_00010010_10010111_00101100_10100101;
@ -418,10 +430,10 @@ public class SpanTest
long actual = span.PackInt64(); long actual = span.PackInt64();
Assert.AreEqual(expected, actual); Assert.That(actual, Is.EqualTo(expected));
} }
[TestMethod] [Test]
public void PackInt64_ShouldReturnCorrectInt64_GivenSpan() public void PackInt64_ShouldReturnCorrectInt64_GivenSpan()
{ {
const long expected = 0b01010101_11010110_01101001_11010110_00010010_10010111_00101100_10100101; const long expected = 0b01010101_11010110_01101001_11010110_00010010_10010111_00101100_10100101;
@ -435,10 +447,10 @@ public class SpanTest
long actual = span.PackInt64(); long actual = span.PackInt64();
Assert.AreEqual(expected, actual); Assert.That(actual, Is.EqualTo(expected));
} }
[TestMethod] [Test]
public void PackInt64_ShouldReturnSameAsPackByte_WhenSpanHasLength8_UsingReadOnlySpan() public void PackInt64_ShouldReturnSameAsPackByte_WhenSpanHasLength8_UsingReadOnlySpan()
{ {
ReadOnlySpan<bool> span = stackalloc bool[8] {true, true, false, false, true, true, false, false}; ReadOnlySpan<bool> span = stackalloc bool[8] {true, true, false, false, true, true, false, false};
@ -446,10 +458,10 @@ public class SpanTest
long expected = span.PackByte(); long expected = span.PackByte();
long actual = span.PackInt64(); long actual = span.PackInt64();
Assert.AreEqual(expected, actual); Assert.That(actual, Is.EqualTo(expected));
} }
[TestMethod] [Test]
public void PackInt64_ShouldReturnSameAsPackByte_WhenSpanHasLength8_UsingSpan() public void PackInt64_ShouldReturnSameAsPackByte_WhenSpanHasLength8_UsingSpan()
{ {
Span<bool> span = stackalloc bool[8] {true, true, false, false, true, true, false, false}; Span<bool> span = stackalloc bool[8] {true, true, false, false, true, true, false, false};
@ -457,10 +469,10 @@ public class SpanTest
long expected = span.PackByte(); long expected = span.PackByte();
long actual = span.PackInt64(); long actual = span.PackInt64();
Assert.AreEqual(expected, actual); Assert.That(actual, Is.EqualTo(expected));
} }
[TestMethod] [Test]
public void PackInt64_ShouldReturnSameAsPackInt16_WhenSpanHasLength16_UsingReadOnlySpan() public void PackInt64_ShouldReturnSameAsPackInt16_WhenSpanHasLength16_UsingReadOnlySpan()
{ {
ReadOnlySpan<bool> span = stackalloc bool[16] ReadOnlySpan<bool> span = stackalloc bool[16]
@ -471,10 +483,10 @@ public class SpanTest
long expected = span.PackInt16(); long expected = span.PackInt16();
long actual = span.PackInt64(); long actual = span.PackInt64();
Assert.AreEqual(expected, actual); Assert.That(actual, Is.EqualTo(expected));
} }
[TestMethod] [Test]
public void PackInt64_ShouldReturnSameAsPackInt16_WhenSpanHasLength16_UsingSpan() public void PackInt64_ShouldReturnSameAsPackInt16_WhenSpanHasLength16_UsingSpan()
{ {
Span<bool> span = stackalloc bool[16] Span<bool> span = stackalloc bool[16]
@ -485,10 +497,10 @@ public class SpanTest
long expected = span.PackInt16(); long expected = span.PackInt16();
long actual = span.PackInt64(); long actual = span.PackInt64();
Assert.AreEqual(expected, actual); Assert.That(actual, Is.EqualTo(expected));
} }
[TestMethod] [Test]
public void PackInt64_ShouldReturnSameAsPackInt32_WhenSpanHasLength16_UsingReadOnlySpan() public void PackInt64_ShouldReturnSameAsPackInt32_WhenSpanHasLength16_UsingReadOnlySpan()
{ {
ReadOnlySpan<bool> span = stackalloc bool[32] ReadOnlySpan<bool> span = stackalloc bool[32]
@ -500,10 +512,10 @@ public class SpanTest
long expected = span.PackInt32(); long expected = span.PackInt32();
long actual = span.PackInt64(); long actual = span.PackInt64();
Assert.AreEqual(expected, actual); Assert.That(actual, Is.EqualTo(expected));
} }
[TestMethod] [Test]
public void PackInt64_ShouldReturnSameAsPackInt32_WhenSpanHasLength16_UsingSpan() public void PackInt64_ShouldReturnSameAsPackInt32_WhenSpanHasLength16_UsingSpan()
{ {
Span<bool> span = stackalloc bool[32] Span<bool> span = stackalloc bool[32]
@ -515,10 +527,10 @@ public class SpanTest
long expected = span.PackInt32(); long expected = span.PackInt32();
long actual = span.PackInt64(); long actual = span.PackInt64();
Assert.AreEqual(expected, actual); Assert.That(actual, Is.EqualTo(expected));
} }
[TestMethod] [Test]
public void PackInt64_ShouldFallbackAndReturnCorrectValue_GivenNonPowerOfTwoLength_UsingReadOnlySpan() public void PackInt64_ShouldFallbackAndReturnCorrectValue_GivenNonPowerOfTwoLength_UsingReadOnlySpan()
{ {
const long expected = 0b00000000_00000000_00000000_00000000_00000000_00000000_00000001_01010011; const long expected = 0b00000000_00000000_00000000_00000000_00000000_00000000_00000001_01010011;
@ -526,10 +538,10 @@ public class SpanTest
long actual = span.PackInt64(); long actual = span.PackInt64();
Assert.AreEqual(expected, actual); Assert.That(actual, Is.EqualTo(expected));
} }
[TestMethod] [Test]
public void PackInt64_ShouldFallbackAndReturnCorrectValue_GivenNonPowerOfTwoLength_UsingSpan() public void PackInt64_ShouldFallbackAndReturnCorrectValue_GivenNonPowerOfTwoLength_UsingSpan()
{ {
const long expected = 0b00000000_00000000_00000000_00000000_00000000_00000000_00000001_01010011; const long expected = 0b00000000_00000000_00000000_00000000_00000000_00000000_00000001_01010011;
@ -537,7 +549,7 @@ public class SpanTest
long actual = span.PackInt64(); long actual = span.PackInt64();
Assert.AreEqual(expected, actual); Assert.That(actual, Is.EqualTo(expected));
} }
private enum EnumByte : byte private enum EnumByte : byte

View File

@ -1,167 +1,193 @@
using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Drawing;
using NUnit.Framework;
using X10D.Drawing; using X10D.Drawing;
namespace X10D.Tests.Drawing; namespace X10D.Tests.Drawing;
[TestClass] [TestFixture]
public class CircleFTests internal class CircleFTests
{ {
[TestMethod] [Test]
public void Area_ShouldBePiRadiusRadius_GivenUnitCircle() public void Area_ShouldBePiRadiusRadius_GivenUnitCircle()
{ {
var unitCircle = CircleF.Unit; 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() public void Circumference_ShouldBe2PiRadius_GivenUnitCircle()
{ {
var unitCircle = CircleF.Unit; 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() 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() 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() 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() 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() public void CompareTo_ShouldBeZero_GivenUnitCircle()
{ {
var unitCircle = CircleF.Unit; var unitCircle = CircleF.Unit;
Assert.AreEqual(0, unitCircle.CompareTo(unitCircle)); Assert.That(unitCircle.CompareTo(unitCircle), Is.Zero);
} }
[TestMethod] [Test]
public void CompareTo_ShouldThrowArgumentException_GivenInvalidType() 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() 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() public void Equals_ShouldBeTrue_GivenTwoUnitCircles()
{ {
var unitCircle1 = CircleF.Unit; var unitCircle1 = CircleF.Unit;
var unitCircle2 = CircleF.Unit; var unitCircle2 = CircleF.Unit;
Assert.AreEqual(unitCircle1, unitCircle2); Assert.Multiple(() =>
Assert.IsTrue(unitCircle1 == unitCircle2); {
Assert.IsFalse(unitCircle1 != unitCircle2); Assert.That(unitCircle2, Is.EqualTo(unitCircle1));
Assert.That(unitCircle1, Is.EqualTo(unitCircle2));
Assert.That(unitCircle1 == unitCircle2);
Assert.That(unitCircle2 == unitCircle1);
});
} }
[TestMethod] [Test]
public void Equals_ShouldBeTrue_GivenUnitCirclesAsObjects() public void Equals_ShouldBeTrue_GivenUnitCirclesAsObjects()
{ {
CircleF unitCircle1 = CircleF.Unit; CircleF unitCircle1 = CircleF.Unit;
object unitCircle2 = CircleF.Unit; object unitCircle2 = CircleF.Unit;
Assert.AreEqual(unitCircle1, unitCircle2); Assert.Multiple(() =>
Assert.IsTrue(unitCircle1.Equals(unitCircle2)); {
Assert.That(unitCircle2, Is.EqualTo(unitCircle1));
Assert.That(unitCircle1, Is.EqualTo(unitCircle2));
});
} }
[TestMethod] [Test]
public void Equals_ShouldBeFalse_GivenDifferentCircles() public void Equals_ShouldBeFalse_GivenDifferentCircles()
{ {
Assert.AreNotEqual(CircleF.Unit, CircleF.Empty); Assert.Multiple(() =>
Assert.IsFalse(CircleF.Unit == CircleF.Empty); {
Assert.IsTrue(CircleF.Unit != CircleF.Empty); 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() public void Equals_ShouldBeFalse_GivenDifferentObjects()
{ {
Assert.AreNotEqual((object?)null, CircleF.Empty); Assert.That(CircleF.Empty, Is.Not.EqualTo(null));
Assert.IsFalse(CircleF.Empty.Equals(null)); Assert.That(CircleF.Empty.Equals(null), Is.False);
} }
[TestMethod] [Test]
public void GetHashCode_ShouldBeCorrect_GivenEmptyCircle() public void GetHashCode_ShouldBeCorrect_GivenEmptyCircle()
{ {
// this test is pretty pointless, it exists only for code coverage purposes // this test is pretty pointless, it exists only for code coverage purposes
int hashCode = CircleF.Empty.GetHashCode(); int hashCode = CircleF.Empty.GetHashCode();
Assert.AreEqual(hashCode, CircleF.Empty.GetHashCode()); Assert.That(CircleF.Empty.GetHashCode(), Is.EqualTo(hashCode));
} }
[TestMethod] [Test]
public void GetHashCode_ShouldBeCorrect_GivenUnitCircle() public void GetHashCode_ShouldBeCorrect_GivenUnitCircle()
{ {
// this test is pretty pointless, it exists only for code coverage purposes // this test is pretty pointless, it exists only for code coverage purposes
int hashCode = CircleF.Unit.GetHashCode(); int hashCode = CircleF.Unit.GetHashCode();
Assert.AreEqual(hashCode, CircleF.Unit.GetHashCode()); Assert.That(CircleF.Unit.GetHashCode(), Is.EqualTo(hashCode));
} }
[TestMethod] [Test]
public void op_Explicit_ShouldReturnEquivalentCircle_GivenCircle() public void op_Explicit_ShouldReturnEquivalentCircle_GivenCircle()
{ {
CircleF unitCircle = CircleF.Unit; CircleF unitCircle = CircleF.Unit;
Circle converted = (Circle)unitCircle; Circle converted = (Circle)unitCircle;
Assert.AreEqual(unitCircle, converted); Assert.Multiple(() =>
Assert.AreEqual(unitCircle.Radius, converted.Radius); {
Assert.AreEqual(unitCircle.Center, converted.Center); 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() public void op_GreaterThan_True_GivenUnitAndEmptyCircle()
{ {
Assert.IsTrue(CircleF.Unit > CircleF.Empty); Assert.That(CircleF.Unit, Is.GreaterThan(CircleF.Empty));
Assert.IsTrue(CircleF.Unit >= CircleF.Empty); Assert.That(CircleF.Unit, Is.GreaterThanOrEqualTo(CircleF.Empty));
Assert.IsFalse(CircleF.Unit < CircleF.Empty);
Assert.IsFalse(CircleF.Unit <= CircleF.Empty); Assert.That(CircleF.Unit > CircleF.Empty);
Assert.That(CircleF.Unit >= CircleF.Empty);
} }
[TestMethod] [Test]
public void op_Implicit_ShouldReturnEquivalentCircle_GivenCircle() public void op_Implicit_ShouldReturnEquivalentCircle_GivenCircle()
{ {
Circle unitCircle = Circle.Unit; Circle unitCircle = Circle.Unit;
CircleF converted = unitCircle; CircleF converted = unitCircle;
Assert.AreEqual(unitCircle, converted); Assert.Multiple(() =>
Assert.AreEqual(unitCircle.Radius, converted.Radius); {
Assert.AreEqual(unitCircle.Center, converted.Center); 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() public void op_LessThan_True_GivenEmptyAndUnitCircle()
{ {
Assert.IsTrue(CircleF.Empty < CircleF.Unit); Assert.Multiple(() =>
Assert.IsTrue(CircleF.Empty <= CircleF.Unit); {
Assert.IsFalse(CircleF.Empty > CircleF.Unit); Assert.That(CircleF.Empty, Is.LessThan(CircleF.Unit));
Assert.IsFalse(CircleF.Empty >= CircleF.Unit); Assert.That(CircleF.Empty, Is.LessThanOrEqualTo(CircleF.Unit));
Assert.That(CircleF.Empty < CircleF.Unit);
Assert.That(CircleF.Empty <= CircleF.Unit);
});
} }
[TestMethod] [Test]
public void Radius_ShouldBe0_GivenEmptyCircle() 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() 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; using X10D.Drawing;
namespace X10D.Tests.Drawing; namespace X10D.Tests.Drawing;
[TestClass] [TestFixture]
public class CircleTests internal class CircleTests
{ {
[TestMethod] [Test]
public void Area_ShouldBePiRadiusRadius_GivenUnitCircle() public void Area_ShouldBePiRadiusRadius_GivenUnitCircle()
{ {
var unitCircle = Circle.Unit; 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() public void Circumference_ShouldBe2PiRadius_GivenUnitCircle()
{ {
var unitCircle = Circle.Unit; 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() 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() 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() 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() 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() public void CompareTo_ShouldBeZero_GivenUnitCircle()
{ {
var unitCircle = Circle.Unit; var unitCircle = Circle.Unit;
Assert.AreEqual(0, unitCircle.CompareTo(unitCircle)); Assert.That(unitCircle.CompareTo(unitCircle), Is.Zero);
} }
[TestMethod] [Test]
public void CompareTo_ShouldThrowArgumentException_GivenInvalidType() 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() 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() public void Equals_ShouldBeTrue_GivenTwoUnitCircles()
{ {
var unitCircle1 = Circle.Unit; var unitCircle1 = Circle.Unit;
var unitCircle2 = Circle.Unit; var unitCircle2 = Circle.Unit;
Assert.AreEqual(unitCircle1, unitCircle2); Assert.Multiple(() =>
Assert.IsTrue(unitCircle1 == unitCircle2); {
Assert.IsFalse(unitCircle1 != unitCircle2); Assert.That(unitCircle2, Is.EqualTo(unitCircle1));
Assert.That(unitCircle1, Is.EqualTo(unitCircle2));
});
} }
[TestMethod] [Test]
public void Equals_ShouldBeTrue_GivenUnitCirclesAsObjects() public void Equals_ShouldBeTrue_GivenUnitCirclesAsObjects()
{ {
Circle unitCircle1 = Circle.Unit; Circle unitCircle1 = Circle.Unit;
object unitCircle2 = Circle.Unit; object unitCircle2 = Circle.Unit;
Assert.AreEqual(unitCircle1, unitCircle2); Assert.Multiple(() =>
Assert.IsTrue(unitCircle1.Equals(unitCircle2)); {
Assert.That(unitCircle2, Is.EqualTo(unitCircle1));
Assert.That(unitCircle1, Is.EqualTo(unitCircle2));
});
} }
[TestMethod] [Test]
public void Equals_ShouldBeFalse_GivenDifferentCircles() public void Equals_ShouldBeFalse_GivenDifferentCircles()
{ {
Assert.AreNotEqual(Circle.Unit, Circle.Empty); Assert.Multiple(() =>
Assert.IsFalse(Circle.Unit == Circle.Empty); {
Assert.IsTrue(Circle.Unit != Circle.Empty); 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() public void Equals_ShouldBeFalse_GivenDifferentObjects()
{ {
Assert.AreNotEqual((object?)null, Circle.Empty); Assert.That(Circle.Empty, Is.Not.EqualTo(null));
Assert.IsFalse(Circle.Empty.Equals(null)); Assert.That(Circle.Empty.Equals(null), Is.False);
} }
[TestMethod] [Test]
public void GetHashCode_ShouldBeCorrect_GivenEmptyCircle() public void GetHashCode_ShouldBeCorrect_GivenEmptyCircle()
{ {
// this test is pretty pointless, it exists only for code coverage purposes // this test is pretty pointless, it exists only for code coverage purposes
int hashCode = Circle.Empty.GetHashCode(); int hashCode = Circle.Empty.GetHashCode();
Assert.AreEqual(hashCode, Circle.Empty.GetHashCode()); Assert.That(Circle.Empty.GetHashCode(), Is.EqualTo(hashCode));
} }
[TestMethod] [Test]
public void GetHashCode_ShouldBeCorrect_GivenUnitCircle() public void GetHashCode_ShouldBeCorrect_GivenUnitCircle()
{ {
// this test is pretty pointless, it exists only for code coverage purposes // this test is pretty pointless, it exists only for code coverage purposes
int hashCode = Circle.Unit.GetHashCode(); int hashCode = Circle.Unit.GetHashCode();
Assert.AreEqual(hashCode, Circle.Unit.GetHashCode()); Assert.That(Circle.Unit.GetHashCode(), Is.EqualTo(hashCode));
} }
[TestMethod] [Test]
public void op_GreaterThan_True_GivenUnitAndEmptyCircle() public void op_GreaterThan_True_GivenUnitAndEmptyCircle()
{ {
Assert.IsTrue(Circle.Unit > Circle.Empty); Assert.Multiple(() =>
Assert.IsTrue(Circle.Unit >= Circle.Empty); {
Assert.IsFalse(Circle.Unit < Circle.Empty); Assert.That(Circle.Unit, Is.GreaterThan(Circle.Empty));
Assert.IsFalse(Circle.Unit <= Circle.Empty); Assert.That(Circle.Unit, Is.GreaterThanOrEqualTo(Circle.Empty));
Assert.That(Circle.Unit > Circle.Empty);
Assert.That(Circle.Unit >= Circle.Empty);
});
} }
[TestMethod] [Test]
public void op_LessThan_True_GivenEmptyAndUnitCircle() public void op_LessThan_True_GivenEmptyAndUnitCircle()
{ {
Assert.IsTrue(Circle.Empty < Circle.Unit); Assert.Multiple(() =>
Assert.IsTrue(Circle.Empty <= Circle.Unit); {
Assert.IsFalse(Circle.Empty > Circle.Unit); Assert.That(Circle.Empty, Is.LessThan(Circle.Unit));
Assert.IsFalse(Circle.Empty >= Circle.Unit); Assert.That(Circle.Empty, Is.LessThanOrEqualTo(Circle.Unit));
Assert.That(Circle.Empty < Circle.Unit);
Assert.That(Circle.Empty <= Circle.Unit);
});
} }
[TestMethod] [Test]
public void Radius_ShouldBe0_GivenEmptyCircle() 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() 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 System.Drawing;
using Microsoft.VisualStudio.TestTools.UnitTesting; using NUnit.Framework;
using X10D.Drawing; using X10D.Drawing;
namespace X10D.Tests.Drawing; namespace X10D.Tests.Drawing;
[TestClass] [TestFixture]
public class ColorTests internal class ColorTests
{ {
private static readonly Color Black = Color.FromArgb(0, 0, 0); private static readonly Color Black = Color.FromArgb(0, 0, 0);
private static readonly Color White = Color.FromArgb(255, 255, 255); private static readonly Color White = Color.FromArgb(255, 255, 255);
@ -16,251 +16,278 @@ public class ColorTests
private static readonly Color Magenta = Color.FromArgb(255, 0, 255); private static readonly Color Magenta = Color.FromArgb(255, 0, 255);
private static readonly Color Yellow = Color.FromArgb(255, 255, 0); private static readonly Color Yellow = Color.FromArgb(255, 255, 0);
[TestMethod] [Test]
public void Deconstruct_ShouldDeconstructColor_GivenColor() public void Deconstruct_ShouldDeconstructColor_GivenColor()
{ {
(byte r, byte g, byte b) = Black; (byte r, byte g, byte b) = Black;
Assert.AreEqual(0, r); Assert.Multiple(() =>
Assert.AreEqual(0, g); {
Assert.AreEqual(0, b); Assert.That(r, Is.Zero);
Assert.That(g, Is.Zero);
Assert.That(b, Is.Zero);
});
(byte a, r, g, b) = Black; (byte a, r, g, b) = Black;
Assert.AreEqual(255, a); Assert.Multiple(() =>
Assert.AreEqual(0, r); {
Assert.AreEqual(0, g); Assert.That(a, Is.EqualTo(255));
Assert.AreEqual(0, b); Assert.That(r, Is.Zero);
Assert.That(g, Is.Zero);
Assert.That(b, Is.Zero);
});
(r, g, b) = Red; (r, g, b) = Red;
Assert.AreEqual(255, r); Assert.Multiple(() =>
Assert.AreEqual(0, g); {
Assert.AreEqual(0, b); Assert.That(r, Is.EqualTo(255));
Assert.That(g, Is.Zero);
Assert.That(b, Is.Zero);
});
(a, r, g, b) = Red; (a, r, g, b) = Red;
Assert.AreEqual(255, a); Assert.Multiple(() =>
Assert.AreEqual(255, r); {
Assert.AreEqual(0, g); Assert.That(a, Is.EqualTo(255));
Assert.AreEqual(0, b); Assert.That(r, Is.EqualTo(255));
Assert.That(g, Is.Zero);
Assert.That(b, Is.Zero);
});
(r, g, b) = Green; (r, g, b) = Green;
Assert.AreEqual(0, r); Assert.Multiple(() =>
Assert.AreEqual(255, g); {
Assert.AreEqual(0, b); Assert.That(r, Is.Zero);
Assert.That(g, Is.EqualTo(255));
Assert.That(b, Is.Zero);
});
(a, r, g, b) = Green; (a, r, g, b) = Green;
Assert.AreEqual(255, a); Assert.Multiple(() =>
Assert.AreEqual(0, r); {
Assert.AreEqual(255, g); Assert.That(a, Is.EqualTo(255));
Assert.AreEqual(0, b); Assert.That(r, Is.Zero);
Assert.That(g, Is.EqualTo(255));
Assert.That(b, Is.Zero);
});
(r, g, b) = Blue; (r, g, b) = Blue;
Assert.AreEqual(0, r); Assert.Multiple(() =>
Assert.AreEqual(0, g); {
Assert.AreEqual(255, b); Assert.That(r, Is.Zero);
Assert.That(g, Is.Zero);
Assert.That(b, Is.EqualTo(255));
});
(a, r, g, b) = Blue; (a, r, g, b) = Blue;
Assert.AreEqual(255, a); Assert.Multiple(() =>
Assert.AreEqual(0, r); {
Assert.AreEqual(0, g); Assert.That(a, Is.EqualTo(255));
Assert.AreEqual(255, b); Assert.That(r, Is.Zero);
Assert.That(g, Is.Zero);
Assert.That(b, Is.EqualTo(255));
});
} }
[TestMethod] [Test]
public void GetClosestConsoleColor_ShouldReturnClosestColor_GivenValidColor() public void GetClosestConsoleColor_ShouldReturnClosestColor_GivenValidColor()
{ {
Assert.AreEqual(ConsoleColor.White, Color.Transparent.GetClosestConsoleColor()); Assert.Multiple(() =>
Assert.AreEqual(ConsoleColor.White, Color.AliceBlue.GetClosestConsoleColor()); {
Assert.AreEqual(ConsoleColor.White, Color.AntiqueWhite.GetClosestConsoleColor()); Assert.That(Color.Transparent.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White));
Assert.AreEqual(ConsoleColor.Cyan, Color.Aqua.GetClosestConsoleColor()); Assert.That(Color.AliceBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White));
Assert.AreEqual(ConsoleColor.DarkGray, Color.Aquamarine.GetClosestConsoleColor()); Assert.That(Color.AntiqueWhite.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White));
Assert.AreEqual(ConsoleColor.White, Color.Azure.GetClosestConsoleColor()); Assert.That(Color.Aqua.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Cyan));
Assert.AreEqual(ConsoleColor.White, Color.Beige.GetClosestConsoleColor()); Assert.That(Color.Aquamarine.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray));
Assert.AreEqual(ConsoleColor.White, Color.Bisque.GetClosestConsoleColor()); Assert.That(Color.Azure.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White));
Assert.AreEqual(ConsoleColor.Black, Color.Black.GetClosestConsoleColor()); Assert.That(Color.Beige.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White));
Assert.AreEqual(ConsoleColor.White, Color.BlanchedAlmond.GetClosestConsoleColor()); Assert.That(Color.Bisque.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White));
Assert.AreEqual(ConsoleColor.Blue, Color.Blue.GetClosestConsoleColor()); Assert.That(Color.Black.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Black));
Assert.AreEqual(ConsoleColor.DarkMagenta, Color.BlueViolet.GetClosestConsoleColor()); Assert.That(Color.BlanchedAlmond.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White));
Assert.AreEqual(ConsoleColor.DarkRed, Color.Brown.GetClosestConsoleColor()); Assert.That(Color.Blue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Blue));
Assert.AreEqual(ConsoleColor.DarkGray, Color.BurlyWood.GetClosestConsoleColor()); Assert.That(Color.BlueViolet.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkMagenta));
Assert.AreEqual(ConsoleColor.Gray, Color.CadetBlue.GetClosestConsoleColor()); Assert.That(Color.Brown.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkRed));
Assert.AreEqual(ConsoleColor.Yellow, Color.Chartreuse.GetClosestConsoleColor()); Assert.That(Color.BurlyWood.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray));
Assert.AreEqual(ConsoleColor.DarkYellow, Color.Chocolate.GetClosestConsoleColor()); Assert.That(Color.CadetBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Gray));
Assert.AreEqual(ConsoleColor.DarkYellow, Color.Coral.GetClosestConsoleColor()); Assert.That(Color.Chartreuse.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Yellow));
Assert.AreEqual(ConsoleColor.DarkGray, Color.CornflowerBlue.GetClosestConsoleColor()); Assert.That(Color.Chocolate.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkYellow));
Assert.AreEqual(ConsoleColor.White, Color.Cornsilk.GetClosestConsoleColor()); Assert.That(Color.Coral.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkYellow));
Assert.AreEqual(ConsoleColor.Red, Color.Crimson.GetClosestConsoleColor()); Assert.That(Color.CornflowerBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray));
Assert.AreEqual(ConsoleColor.Cyan, Color.Cyan.GetClosestConsoleColor()); Assert.That(Color.Cornsilk.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White));
Assert.AreEqual(ConsoleColor.DarkBlue, Color.DarkBlue.GetClosestConsoleColor()); Assert.That(Color.Crimson.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Red));
Assert.AreEqual(ConsoleColor.DarkCyan, Color.DarkCyan.GetClosestConsoleColor()); Assert.That(Color.Cyan.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Cyan));
Assert.AreEqual(ConsoleColor.DarkYellow, Color.DarkGoldenrod.GetClosestConsoleColor()); Assert.That(Color.DarkBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkBlue));
Assert.AreEqual(ConsoleColor.DarkGray, Color.DarkGray.GetClosestConsoleColor()); Assert.That(Color.DarkCyan.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkCyan));
Assert.AreEqual(ConsoleColor.DarkGreen, Color.DarkGreen.GetClosestConsoleColor()); Assert.That(Color.DarkGoldenrod.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkYellow));
Assert.AreEqual(ConsoleColor.DarkGray, Color.DarkKhaki.GetClosestConsoleColor()); Assert.That(Color.DarkGray.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray));
Assert.AreEqual(ConsoleColor.DarkMagenta, Color.DarkMagenta.GetClosestConsoleColor()); Assert.That(Color.DarkGreen.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGreen));
Assert.AreEqual(ConsoleColor.Gray, Color.DarkOliveGreen.GetClosestConsoleColor()); Assert.That(Color.DarkKhaki.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray));
Assert.AreEqual(ConsoleColor.DarkYellow, Color.DarkOrange.GetClosestConsoleColor()); Assert.That(Color.DarkMagenta.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkMagenta));
Assert.AreEqual(ConsoleColor.DarkMagenta, Color.DarkOrchid.GetClosestConsoleColor()); Assert.That(Color.DarkOliveGreen.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Gray));
Assert.AreEqual(ConsoleColor.DarkRed, Color.DarkRed.GetClosestConsoleColor()); Assert.That(Color.DarkOrange.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkYellow));
Assert.AreEqual(ConsoleColor.DarkGray, Color.DarkSalmon.GetClosestConsoleColor()); Assert.That(Color.DarkOrchid.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkMagenta));
Assert.AreEqual(ConsoleColor.DarkGray, Color.DarkSeaGreen.GetClosestConsoleColor()); Assert.That(Color.DarkRed.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkRed));
Assert.AreEqual(ConsoleColor.Gray, Color.DarkSlateBlue.GetClosestConsoleColor()); Assert.That(Color.DarkSalmon.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray));
Assert.AreEqual(ConsoleColor.DarkGreen, Color.DarkSlateGray.GetClosestConsoleColor()); Assert.That(Color.DarkSeaGreen.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray));
Assert.AreEqual(ConsoleColor.Cyan, Color.DarkTurquoise.GetClosestConsoleColor()); Assert.That(Color.DarkSlateBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Gray));
Assert.AreEqual(ConsoleColor.DarkMagenta, Color.DarkViolet.GetClosestConsoleColor()); Assert.That(Color.DarkSlateGray.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGreen));
Assert.AreEqual(ConsoleColor.Magenta, Color.DeepPink.GetClosestConsoleColor()); Assert.That(Color.DarkTurquoise.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Cyan));
Assert.AreEqual(ConsoleColor.Cyan, Color.DeepSkyBlue.GetClosestConsoleColor()); Assert.That(Color.DarkViolet.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkMagenta));
Assert.AreEqual(ConsoleColor.Gray, Color.DimGray.GetClosestConsoleColor()); Assert.That(Color.DeepPink.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Magenta));
Assert.AreEqual(ConsoleColor.Cyan, Color.DodgerBlue.GetClosestConsoleColor()); Assert.That(Color.DeepSkyBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Cyan));
Assert.AreEqual(ConsoleColor.DarkRed, Color.Firebrick.GetClosestConsoleColor()); Assert.That(Color.DimGray.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Gray));
Assert.AreEqual(ConsoleColor.White, Color.FloralWhite.GetClosestConsoleColor()); Assert.That(Color.DodgerBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Cyan));
Assert.AreEqual(ConsoleColor.Green, Color.ForestGreen.GetClosestConsoleColor()); Assert.That(Color.Firebrick.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkRed));
Assert.AreEqual(ConsoleColor.Magenta, Color.Fuchsia.GetClosestConsoleColor()); Assert.That(Color.FloralWhite.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White));
Assert.AreEqual(ConsoleColor.White, Color.Gainsboro.GetClosestConsoleColor()); Assert.That(Color.ForestGreen.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Green));
Assert.AreEqual(ConsoleColor.White, Color.GhostWhite.GetClosestConsoleColor()); Assert.That(Color.Fuchsia.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Magenta));
Assert.AreEqual(ConsoleColor.Yellow, Color.Gold.GetClosestConsoleColor()); Assert.That(Color.Gainsboro.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White));
Assert.AreEqual(ConsoleColor.DarkYellow, Color.Goldenrod.GetClosestConsoleColor()); Assert.That(Color.GhostWhite.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White));
Assert.AreEqual(ConsoleColor.Gray, Color.Gray.GetClosestConsoleColor()); Assert.That(Color.Gold.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Yellow));
Assert.AreEqual(ConsoleColor.Green, Color.Green.GetClosestConsoleColor()); Assert.That(Color.Goldenrod.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkYellow));
Assert.AreEqual(ConsoleColor.Yellow, Color.GreenYellow.GetClosestConsoleColor()); Assert.That(Color.Gray.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Gray));
Assert.AreEqual(ConsoleColor.White, Color.Honeydew.GetClosestConsoleColor()); Assert.That(Color.Green.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Green));
Assert.AreEqual(ConsoleColor.DarkGray, Color.HotPink.GetClosestConsoleColor()); Assert.That(Color.GreenYellow.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Yellow));
Assert.AreEqual(ConsoleColor.Gray, Color.IndianRed.GetClosestConsoleColor()); Assert.That(Color.Honeydew.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White));
Assert.AreEqual(ConsoleColor.DarkMagenta, Color.Indigo.GetClosestConsoleColor()); Assert.That(Color.HotPink.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray));
Assert.AreEqual(ConsoleColor.White, Color.Ivory.GetClosestConsoleColor()); Assert.That(Color.IndianRed.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Gray));
Assert.AreEqual(ConsoleColor.DarkGray, Color.Khaki.GetClosestConsoleColor()); Assert.That(Color.Indigo.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkMagenta));
Assert.AreEqual(ConsoleColor.White, Color.Lavender.GetClosestConsoleColor()); Assert.That(Color.Ivory.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White));
Assert.AreEqual(ConsoleColor.White, Color.LavenderBlush.GetClosestConsoleColor()); Assert.That(Color.Khaki.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray));
Assert.AreEqual(ConsoleColor.Yellow, Color.LawnGreen.GetClosestConsoleColor()); Assert.That(Color.Lavender.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White));
Assert.AreEqual(ConsoleColor.White, Color.LemonChiffon.GetClosestConsoleColor()); Assert.That(Color.LavenderBlush.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White));
Assert.AreEqual(ConsoleColor.DarkGray, Color.LightBlue.GetClosestConsoleColor()); Assert.That(Color.LawnGreen.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Yellow));
Assert.AreEqual(ConsoleColor.DarkGray, Color.LightCoral.GetClosestConsoleColor()); Assert.That(Color.LemonChiffon.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White));
Assert.AreEqual(ConsoleColor.White, Color.LightCyan.GetClosestConsoleColor()); Assert.That(Color.LightBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray));
Assert.AreEqual(ConsoleColor.White, Color.LightGoldenrodYellow.GetClosestConsoleColor()); Assert.That(Color.LightCoral.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray));
Assert.AreEqual(ConsoleColor.DarkGray, Color.LightGreen.GetClosestConsoleColor()); Assert.That(Color.LightCyan.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White));
Assert.AreEqual(ConsoleColor.DarkGray, Color.LightGray.GetClosestConsoleColor()); Assert.That(Color.LightGoldenrodYellow.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White));
Assert.AreEqual(ConsoleColor.DarkGray, Color.LightPink.GetClosestConsoleColor()); Assert.That(Color.LightGreen.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray));
Assert.AreEqual(ConsoleColor.DarkGray, Color.LightSalmon.GetClosestConsoleColor()); Assert.That(Color.LightGray.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray));
Assert.AreEqual(ConsoleColor.DarkCyan, Color.LightSeaGreen.GetClosestConsoleColor()); Assert.That(Color.LightPink.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray));
Assert.AreEqual(ConsoleColor.DarkGray, Color.LightSkyBlue.GetClosestConsoleColor()); Assert.That(Color.LightSalmon.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray));
Assert.AreEqual(ConsoleColor.Gray, Color.LightSlateGray.GetClosestConsoleColor()); Assert.That(Color.LightSeaGreen.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkCyan));
Assert.AreEqual(ConsoleColor.DarkGray, Color.LightSteelBlue.GetClosestConsoleColor()); Assert.That(Color.LightSkyBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray));
Assert.AreEqual(ConsoleColor.White, Color.LightYellow.GetClosestConsoleColor()); Assert.That(Color.LightSlateGray.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Gray));
Assert.AreEqual(ConsoleColor.Green, Color.Lime.GetClosestConsoleColor()); Assert.That(Color.LightSteelBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray));
Assert.AreEqual(ConsoleColor.Green, Color.LimeGreen.GetClosestConsoleColor()); Assert.That(Color.LightYellow.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White));
Assert.AreEqual(ConsoleColor.White, Color.Linen.GetClosestConsoleColor()); Assert.That(Color.Lime.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Green));
Assert.AreEqual(ConsoleColor.Magenta, Color.Magenta.GetClosestConsoleColor()); Assert.That(Color.LimeGreen.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Green));
Assert.AreEqual(ConsoleColor.DarkRed, Color.Maroon.GetClosestConsoleColor()); Assert.That(Color.Linen.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White));
Assert.AreEqual(ConsoleColor.DarkGray, Color.MediumAquamarine.GetClosestConsoleColor()); Assert.That(Color.Magenta.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Magenta));
Assert.AreEqual(ConsoleColor.Blue, Color.MediumBlue.GetClosestConsoleColor()); Assert.That(Color.Maroon.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkRed));
Assert.AreEqual(ConsoleColor.DarkGray, Color.MediumOrchid.GetClosestConsoleColor()); Assert.That(Color.MediumAquamarine.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray));
Assert.AreEqual(ConsoleColor.DarkGray, Color.MediumPurple.GetClosestConsoleColor()); Assert.That(Color.MediumBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Blue));
Assert.AreEqual(ConsoleColor.DarkCyan, Color.MediumSeaGreen.GetClosestConsoleColor()); Assert.That(Color.MediumOrchid.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray));
Assert.AreEqual(ConsoleColor.DarkGray, Color.MediumSlateBlue.GetClosestConsoleColor()); Assert.That(Color.MediumPurple.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray));
Assert.AreEqual(ConsoleColor.Cyan, Color.MediumSpringGreen.GetClosestConsoleColor()); Assert.That(Color.MediumSeaGreen.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkCyan));
Assert.AreEqual(ConsoleColor.Cyan, Color.MediumTurquoise.GetClosestConsoleColor()); Assert.That(Color.MediumSlateBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray));
Assert.AreEqual(ConsoleColor.DarkMagenta, Color.MediumVioletRed.GetClosestConsoleColor()); Assert.That(Color.MediumSpringGreen.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Cyan));
Assert.AreEqual(ConsoleColor.DarkBlue, Color.MidnightBlue.GetClosestConsoleColor()); Assert.That(Color.MediumTurquoise.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Cyan));
Assert.AreEqual(ConsoleColor.White, Color.MintCream.GetClosestConsoleColor()); Assert.That(Color.MediumVioletRed.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkMagenta));
Assert.AreEqual(ConsoleColor.White, Color.MistyRose.GetClosestConsoleColor()); Assert.That(Color.MidnightBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkBlue));
Assert.AreEqual(ConsoleColor.White, Color.Moccasin.GetClosestConsoleColor()); Assert.That(Color.MintCream.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White));
Assert.AreEqual(ConsoleColor.White, Color.NavajoWhite.GetClosestConsoleColor()); Assert.That(Color.MistyRose.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White));
Assert.AreEqual(ConsoleColor.DarkBlue, Color.Navy.GetClosestConsoleColor()); Assert.That(Color.Moccasin.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White));
Assert.AreEqual(ConsoleColor.White, Color.OldLace.GetClosestConsoleColor()); Assert.That(Color.NavajoWhite.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White));
Assert.AreEqual(ConsoleColor.Gray, Color.Olive.GetClosestConsoleColor()); Assert.That(Color.Navy.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkBlue));
Assert.AreEqual(ConsoleColor.Gray, Color.OliveDrab.GetClosestConsoleColor()); Assert.That(Color.OldLace.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White));
Assert.AreEqual(ConsoleColor.DarkYellow, Color.Orange.GetClosestConsoleColor()); Assert.That(Color.Olive.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Gray));
Assert.AreEqual(ConsoleColor.Red, Color.OrangeRed.GetClosestConsoleColor()); Assert.That(Color.OliveDrab.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Gray));
Assert.AreEqual(ConsoleColor.DarkGray, Color.Orchid.GetClosestConsoleColor()); Assert.That(Color.Orange.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkYellow));
Assert.AreEqual(ConsoleColor.White, Color.PaleGoldenrod.GetClosestConsoleColor()); Assert.That(Color.OrangeRed.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Red));
Assert.AreEqual(ConsoleColor.DarkGray, Color.PaleGreen.GetClosestConsoleColor()); Assert.That(Color.Orchid.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray));
Assert.AreEqual(ConsoleColor.White, Color.PaleTurquoise.GetClosestConsoleColor()); Assert.That(Color.PaleGoldenrod.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White));
Assert.AreEqual(ConsoleColor.DarkGray, Color.PaleVioletRed.GetClosestConsoleColor()); Assert.That(Color.PaleGreen.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray));
Assert.AreEqual(ConsoleColor.White, Color.PapayaWhip.GetClosestConsoleColor()); Assert.That(Color.PaleTurquoise.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White));
Assert.AreEqual(ConsoleColor.White, Color.PeachPuff.GetClosestConsoleColor()); Assert.That(Color.PaleVioletRed.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray));
Assert.AreEqual(ConsoleColor.DarkYellow, Color.Peru.GetClosestConsoleColor()); Assert.That(Color.PapayaWhip.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White));
Assert.AreEqual(ConsoleColor.White, Color.Pink.GetClosestConsoleColor()); Assert.That(Color.PeachPuff.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White));
Assert.AreEqual(ConsoleColor.DarkGray, Color.Plum.GetClosestConsoleColor()); Assert.That(Color.Peru.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkYellow));
Assert.AreEqual(ConsoleColor.DarkGray, Color.PowderBlue.GetClosestConsoleColor()); Assert.That(Color.Pink.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White));
Assert.AreEqual(ConsoleColor.DarkMagenta, Color.Purple.GetClosestConsoleColor()); 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 #if NET6_0_OR_GREATER
Assert.AreEqual(ConsoleColor.DarkMagenta, Color.RebeccaPurple.GetClosestConsoleColor()); Assert.That(Color.RebeccaPurple.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkMagenta));
#endif #endif
Assert.AreEqual(ConsoleColor.Red, Color.Red.GetClosestConsoleColor()); Assert.That(Color.Red.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Red));
Assert.AreEqual(ConsoleColor.DarkGray, Color.RosyBrown.GetClosestConsoleColor()); Assert.That(Color.RosyBrown.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray));
Assert.AreEqual(ConsoleColor.DarkCyan, Color.RoyalBlue.GetClosestConsoleColor()); Assert.That(Color.RoyalBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkCyan));
Assert.AreEqual(ConsoleColor.DarkRed, Color.SaddleBrown.GetClosestConsoleColor()); Assert.That(Color.SaddleBrown.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkRed));
Assert.AreEqual(ConsoleColor.DarkGray, Color.Salmon.GetClosestConsoleColor()); Assert.That(Color.Salmon.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray));
Assert.AreEqual(ConsoleColor.DarkYellow, Color.SandyBrown.GetClosestConsoleColor()); Assert.That(Color.SandyBrown.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkYellow));
Assert.AreEqual(ConsoleColor.DarkCyan, Color.SeaGreen.GetClosestConsoleColor()); Assert.That(Color.SeaGreen.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkCyan));
Assert.AreEqual(ConsoleColor.White, Color.SeaShell.GetClosestConsoleColor()); Assert.That(Color.SeaShell.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White));
Assert.AreEqual(ConsoleColor.DarkRed, Color.Sienna.GetClosestConsoleColor()); Assert.That(Color.Sienna.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkRed));
Assert.AreEqual(ConsoleColor.DarkGray, Color.Silver.GetClosestConsoleColor()); Assert.That(Color.Silver.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray));
Assert.AreEqual(ConsoleColor.DarkGray, Color.SkyBlue.GetClosestConsoleColor()); Assert.That(Color.SkyBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray));
Assert.AreEqual(ConsoleColor.Gray, Color.SlateBlue.GetClosestConsoleColor()); Assert.That(Color.SlateBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Gray));
Assert.AreEqual(ConsoleColor.Gray, Color.SlateGray.GetClosestConsoleColor()); Assert.That(Color.SlateGray.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Gray));
Assert.AreEqual(ConsoleColor.White, Color.Snow.GetClosestConsoleColor()); Assert.That(Color.Snow.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White));
Assert.AreEqual(ConsoleColor.DarkCyan, Color.SpringGreen.GetClosestConsoleColor()); Assert.That(Color.SpringGreen.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkCyan));
Assert.AreEqual(ConsoleColor.Gray, Color.SteelBlue.GetClosestConsoleColor()); Assert.That(Color.SteelBlue.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Gray));
Assert.AreEqual(ConsoleColor.DarkGray, Color.Tan.GetClosestConsoleColor()); Assert.That(Color.Tan.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray));
Assert.AreEqual(ConsoleColor.DarkCyan, Color.Teal.GetClosestConsoleColor()); Assert.That(Color.Teal.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkCyan));
Assert.AreEqual(ConsoleColor.DarkGray, Color.Thistle.GetClosestConsoleColor()); Assert.That(Color.Thistle.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray));
Assert.AreEqual(ConsoleColor.DarkYellow, Color.Tomato.GetClosestConsoleColor()); Assert.That(Color.Tomato.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkYellow));
Assert.AreEqual(ConsoleColor.Cyan, Color.Turquoise.GetClosestConsoleColor()); Assert.That(Color.Turquoise.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Cyan));
Assert.AreEqual(ConsoleColor.DarkGray, Color.Violet.GetClosestConsoleColor()); Assert.That(Color.Violet.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.DarkGray));
Assert.AreEqual(ConsoleColor.White, Color.Wheat.GetClosestConsoleColor()); Assert.That(Color.Wheat.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White));
Assert.AreEqual(ConsoleColor.White, Color.White.GetClosestConsoleColor()); Assert.That(Color.White.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White));
Assert.AreEqual(ConsoleColor.White, Color.WhiteSmoke.GetClosestConsoleColor()); Assert.That(Color.WhiteSmoke.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.White));
Assert.AreEqual(ConsoleColor.Yellow, Color.Yellow.GetClosestConsoleColor()); Assert.That(Color.Yellow.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Yellow));
Assert.AreEqual(ConsoleColor.Gray, Color.YellowGreen.GetClosestConsoleColor()); Assert.That(Color.YellowGreen.GetClosestConsoleColor(), Is.EqualTo(ConsoleColor.Gray));
});
} }
[TestMethod] [Test]
public void Inverted_ShouldReturnInvertedColor() public void Inverted_ShouldReturnInvertedColor()
{ {
Assert.AreEqual(White, Black.Inverted()); Assert.That(Black.Inverted(), Is.EqualTo(White));
Assert.AreEqual(Black, White.Inverted()); Assert.That(White.Inverted(), Is.EqualTo(Black));
Assert.AreEqual(Red, Cyan.Inverted()); Assert.That(Cyan.Inverted(), Is.EqualTo(Red));
Assert.AreEqual(Cyan, Red.Inverted()); Assert.That(Red.Inverted(), Is.EqualTo(Cyan));
Assert.AreEqual(Green, Magenta.Inverted()); Assert.That(Magenta.Inverted(), Is.EqualTo(Green));
Assert.AreEqual(Magenta, Green.Inverted()); Assert.That(Green.Inverted(), Is.EqualTo(Magenta));
Assert.AreEqual(Yellow, Blue.Inverted()); Assert.That(Blue.Inverted(), Is.EqualTo(Yellow));
Assert.AreEqual(Blue, Yellow.Inverted()); Assert.That(Yellow.Inverted(), Is.EqualTo(Blue));
} }
[TestMethod] [Test]
public void Inverted_ShouldIgnoreAlpha() public void Inverted_ShouldIgnoreAlpha()
{ {
Color expected = Color.FromArgb(255, 0, 0, 0); Color expected = Color.FromArgb(255, 0, 0, 0);
Color actual = Color.FromArgb(255, 255, 255, 255).Inverted(); Color actual = Color.FromArgb(255, 255, 255, 255).Inverted();
Assert.AreEqual(expected, actual); Assert.That(actual, Is.EqualTo(expected));
} }
[TestMethod] [Test]
public void WithA0_ShouldReturnSameColor_GivenWhite() public void WithA0_ShouldReturnSameColor_GivenWhite()
{ {
Color transparent = Color.FromArgb(0, 255, 255, 255); Color transparent = Color.FromArgb(0, 255, 255, 255);
Assert.AreEqual(transparent, White.WithA(0)); Assert.That(White.WithA(0), Is.EqualTo(transparent));
Assert.AreEqual(transparent, transparent.WithA(0)); Assert.That(transparent.WithA(0), Is.EqualTo(transparent));
} }
[TestMethod] [Test]
public void WithB0_ShouldReturnYellow_GivenWhite() public void WithB0_ShouldReturnYellow_GivenWhite()
{ {
Assert.AreEqual(Yellow, White.WithB(0)); Assert.That(White.WithB(0), Is.EqualTo(Yellow));
Assert.AreEqual(Yellow, Yellow.WithB(0)); Assert.That(Yellow.WithB(0), Is.EqualTo(Yellow));
} }
[TestMethod] [Test]
public void WithG0_ShouldReturnMagenta_GivenWhite() public void WithG0_ShouldReturnMagenta_GivenWhite()
{ {
Assert.AreEqual(Magenta, White.WithG(0)); Assert.That(White.WithG(0), Is.EqualTo(Magenta));
Assert.AreEqual(Magenta, Magenta.WithG(0)); Assert.That(Magenta.WithG(0), Is.EqualTo(Magenta));
} }
[TestMethod] [Test]
public void WithR0_ShouldReturnCyan_GivenWhite() public void WithR0_ShouldReturnCyan_GivenWhite()
{ {
Assert.AreEqual(Cyan, White.WithR(0)); Assert.That(White.WithR(0), Is.EqualTo(Cyan));
Assert.AreEqual(Cyan, Cyan.WithR(0)); Assert.That(Cyan.WithR(0), Is.EqualTo(Cyan));
} }
} }

View File

@ -1,82 +1,82 @@
using System.Numerics; using System.Numerics;
using Microsoft.VisualStudio.TestTools.UnitTesting; using NUnit.Framework;
using X10D.Drawing; using X10D.Drawing;
namespace X10D.Tests.Drawing; namespace X10D.Tests.Drawing;
[TestClass] [TestFixture]
public class CuboidTests internal class CuboidTests
{ {
[TestMethod] [Test]
public void Corners_ShouldBeCorrect_GivenCubeOfSize1() public void Corners_ShouldBeCorrect_GivenCubeOfSize1()
{ {
Cuboid cube = Cuboid.Cube; Cuboid cube = Cuboid.Cube;
Assert.AreEqual(new Vector3(0.5f, 0.5f, -0.5f), cube.FrontTopRight); Assert.That(cube.FrontTopRight, Is.EqualTo(new Vector3(0.5f, 0.5f, -0.5f)));
Assert.AreEqual(new Vector3(-0.5f, 0.5f, -0.5f), cube.FrontTopLeft); Assert.That(cube.FrontTopLeft, Is.EqualTo(new Vector3(-0.5f, 0.5f, -0.5f)));
Assert.AreEqual(new Vector3(0.5f, -0.5f, -0.5f), cube.FrontBottomRight); Assert.That(cube.FrontBottomRight, Is.EqualTo(new Vector3(0.5f, -0.5f, -0.5f)));
Assert.AreEqual(new Vector3(-0.5f, -0.5f, -0.5f), cube.FrontBottomLeft); Assert.That(cube.FrontBottomLeft, Is.EqualTo(new Vector3(-0.5f, -0.5f, -0.5f)));
Assert.AreEqual(new Vector3(0.5f, 0.5f, 0.5f), cube.BackTopRight); Assert.That(cube.BackTopRight, Is.EqualTo(new Vector3(0.5f, 0.5f, 0.5f)));
Assert.AreEqual(new Vector3(-0.5f, 0.5f, 0.5f), cube.BackTopLeft); Assert.That(cube.BackTopLeft, Is.EqualTo(new Vector3(-0.5f, 0.5f, 0.5f)));
Assert.AreEqual(new Vector3(0.5f, -0.5f, 0.5f), cube.BackBottomRight); Assert.That(cube.BackBottomRight, Is.EqualTo(new Vector3(0.5f, -0.5f, 0.5f)));
Assert.AreEqual(new Vector3(-0.5f, -0.5f, 0.5f), cube.BackBottomLeft); Assert.That(cube.BackBottomLeft, Is.EqualTo(new Vector3(-0.5f, -0.5f, 0.5f)));
} }
[TestMethod] [Test]
public void Equals_ShouldBeTrue_GivenTwoCubesOfSize1() public void Equals_ShouldBeTrue_GivenTwoCubesOfSize1()
{ {
var cube1 = Cuboid.Cube; var cube1 = Cuboid.Cube;
var cube2 = Cuboid.Cube; var cube2 = Cuboid.Cube;
Assert.AreEqual(cube1, cube2); Assert.That(cube1, Is.EqualTo(cube2));
Assert.IsTrue(cube1 == cube2); Assert.That(cube2, Is.EqualTo(cube1));
Assert.IsFalse(cube1 != cube2); Assert.That(cube1 == cube2);
Assert.That(cube2 == cube1);
} }
[TestMethod] [Test]
public void Equals_ShouldBeFalse_GivenDifferentCubes() public void Equals_ShouldBeFalse_GivenDifferentCubes()
{ {
Assert.AreNotEqual(Cuboid.Cube, Cuboid.Empty); Assert.That(Cuboid.Empty, Is.Not.EqualTo(Cuboid.Cube));
Assert.IsFalse(Cuboid.Cube == Cuboid.Empty); Assert.That(Cuboid.Empty != Cuboid.Cube);
Assert.IsTrue(Cuboid.Cube != Cuboid.Empty);
} }
[TestMethod] [Test]
public void Equals_ShouldBeFalse_GivenDifferentObjects() 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() public void GetHashCode_ShouldBeCorrect_GivenEmptyCircle()
{ {
// this test is pretty pointless, it exists only for code coverage purposes // this test is pretty pointless, it exists only for code coverage purposes
int hashCode = Cuboid.Empty.GetHashCode(); int hashCode = Cuboid.Empty.GetHashCode();
Assert.AreEqual(hashCode, Cuboid.Empty.GetHashCode()); Assert.That(Cuboid.Empty.GetHashCode(), Is.EqualTo(hashCode));
} }
[TestMethod] [Test]
public void GetHashCode_ShouldBeCorrect_GivenCubeOfSize1() public void GetHashCode_ShouldBeCorrect_GivenCubeOfSize1()
{ {
// this test is pretty pointless, it exists only for code coverage purposes // this test is pretty pointless, it exists only for code coverage purposes
int hashCode = Cuboid.Cube.GetHashCode(); int hashCode = Cuboid.Cube.GetHashCode();
Assert.AreEqual(hashCode, Cuboid.Cube.GetHashCode()); Assert.That(Cuboid.Cube.GetHashCode(), Is.EqualTo(hashCode));
} }
[TestMethod] [Test]
public void Size_ShouldBeOne_GivenCubeOfSize1() 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() 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() 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.Drawing;
using System.Numerics; using System.Numerics;
using Microsoft.VisualStudio.TestTools.UnitTesting; using NUnit.Framework;
using X10D.Drawing; using X10D.Drawing;
namespace X10D.Tests.Drawing; namespace X10D.Tests.Drawing;
[TestClass] [TestFixture]
public class EllipseFTests internal class EllipseFTests
{ {
[TestMethod] [Test]
public void Area_ShouldBePiRadiusRadius_GivenUnitEllipse() public void Area_ShouldBePiRadiusRadius_GivenUnitEllipse()
{ {
var unitEllipse = EllipseF.Unit; 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() public void ApproximateCircumference_ShouldBe2PiRadius_GivenUnitEllipse()
{ {
var unitEllipse = EllipseF.Unit; 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() public void Constructor_ShouldGiveCorrectEllipse()
{ {
var ellipse = new EllipseF(PointF.Empty, new SizeF(2, 1)); var ellipse = new EllipseF(PointF.Empty, new SizeF(2, 1));
Assert.AreEqual(new PointF(0, 0), ellipse.Center); Assert.That(ellipse.Center, Is.EqualTo(new PointF(0, 0)));
Assert.AreEqual(new SizeF(2, 1), ellipse.Radius); Assert.That(ellipse.Radius, Is.EqualTo(new SizeF(2, 1)));
ellipse = new EllipseF(0, 0, 2, 1); ellipse = new EllipseF(0, 0, 2, 1);
Assert.AreEqual(new PointF(0, 0), ellipse.Center); Assert.That(ellipse.Center, Is.EqualTo(new PointF(0, 0)));
Assert.AreEqual(new SizeF(2, 1), ellipse.Radius); Assert.That(ellipse.Radius, Is.EqualTo(new SizeF(2, 1)));
ellipse = new EllipseF(PointF.Empty, new Vector2(2, 1)); ellipse = new EllipseF(PointF.Empty, new Vector2(2, 1));
Assert.AreEqual(new PointF(0, 0), ellipse.Center); Assert.That(ellipse.Center, Is.EqualTo(new PointF(0, 0)));
Assert.AreEqual(new SizeF(2, 1), ellipse.Radius); Assert.That(ellipse.Radius, Is.EqualTo(new SizeF(2, 1)));
ellipse = new EllipseF(Vector2.Zero, new Vector2(2, 1)); ellipse = new EllipseF(Vector2.Zero, new Vector2(2, 1));
Assert.AreEqual(new PointF(0, 0), ellipse.Center); Assert.That(ellipse.Center, Is.EqualTo(new PointF(0, 0)));
Assert.AreEqual(new SizeF(2, 1), ellipse.Radius); Assert.That(ellipse.Radius, Is.EqualTo(new SizeF(2, 1)));
} }
[TestMethod] [Test]
public void Equals_ShouldBeTrue_GivenTwoUnitEllipses() public void Equals_ShouldBeTrue_GivenTwoUnitEllipses()
{ {
var unitEllipse1 = EllipseF.Unit; var unitEllipse1 = EllipseF.Unit;
var unitEllipse2 = EllipseF.Unit; var unitEllipse2 = EllipseF.Unit;
Assert.AreEqual(unitEllipse1, unitEllipse2); Assert.That(unitEllipse2, Is.EqualTo(unitEllipse1));
Assert.IsTrue(unitEllipse1 == unitEllipse2); Assert.That(unitEllipse1, Is.EqualTo(unitEllipse2));
Assert.IsFalse(unitEllipse1 != unitEllipse2); Assert.That(unitEllipse2 == unitEllipse1);
Assert.That(unitEllipse1 == unitEllipse2);
} }
[TestMethod] [Test]
public void Equals_ShouldBeFalse_GivenDifferentEllipses() public void Equals_ShouldBeFalse_GivenDifferentEllipses()
{ {
Assert.AreNotEqual(EllipseF.Unit, EllipseF.Empty); Assert.That(EllipseF.Empty, Is.Not.EqualTo(EllipseF.Unit));
Assert.IsFalse(EllipseF.Unit == EllipseF.Empty); Assert.That(EllipseF.Empty != EllipseF.Unit);
Assert.IsTrue(EllipseF.Unit != EllipseF.Empty);
} }
[TestMethod] [Test]
public void Equals_ShouldBeFalse_GivenDifferentObjects() 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() public void GetHashCode_ShouldBeCorrect_GivenEmptyEllipse()
{ {
// this test is pretty pointless, it exists only for code coverage purposes // this test is pretty pointless, it exists only for code coverage purposes
int hashCode = EllipseF.Empty.GetHashCode(); int hashCode = EllipseF.Empty.GetHashCode();
Assert.AreEqual(hashCode, EllipseF.Empty.GetHashCode()); Assert.That(EllipseF.Empty.GetHashCode(), Is.EqualTo(hashCode));
} }
[TestMethod] [Test]
public void GetHashCode_ShouldBeCorrect_GivenUnitEllipse() public void GetHashCode_ShouldBeCorrect_GivenUnitEllipse()
{ {
// this test is pretty pointless, it exists only for code coverage purposes // this test is pretty pointless, it exists only for code coverage purposes
int hashCode = EllipseF.Unit.GetHashCode(); int hashCode = EllipseF.Unit.GetHashCode();
Assert.AreEqual(hashCode, EllipseF.Unit.GetHashCode()); Assert.That(EllipseF.Unit.GetHashCode(), Is.EqualTo(hashCode));
} }
[TestMethod] [Test]
public void HorizontalRadius_ShouldBe0_GivenEmptyEllipse() 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() 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() public void op_Explicit_ShouldReturnEquivalentEllipse_GivenEllipse()
{ {
EllipseF unitEllipse = EllipseF.Unit; EllipseF unitEllipse = EllipseF.Unit;
Ellipse converted = (Ellipse)unitEllipse; Ellipse converted = (Ellipse)unitEllipse;
Assert.AreEqual(unitEllipse, converted); Assert.Multiple(() =>
Assert.AreEqual(unitEllipse.HorizontalRadius, converted.HorizontalRadius); {
Assert.AreEqual(unitEllipse.VerticalRadius, converted.VerticalRadius); Assert.That(converted, Is.EqualTo((Ellipse)unitEllipse));
Assert.AreEqual(unitEllipse.Center, converted.Center); 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() public void op_Implicit_ShouldReturnEquivalentEllipse_GivenCircle()
{ {
Circle unitCircle = Circle.Unit; Circle unitCircle = Circle.Unit;
EllipseF converted = unitCircle; EllipseF converted = unitCircle;
Assert.AreEqual(unitCircle, converted); Assert.Multiple(() =>
Assert.AreEqual(unitCircle.Radius, converted.HorizontalRadius); {
Assert.AreEqual(unitCircle.Radius, converted.VerticalRadius); Assert.That(converted, Is.EqualTo((EllipseF)unitCircle));
Assert.AreEqual(unitCircle.Center, converted.Center); 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() public void op_Implicit_ShouldReturnEquivalentEllipse_GivenCircleF()
{ {
CircleF unitCircle = CircleF.Unit; CircleF unitCircle = CircleF.Unit;
EllipseF converted = unitCircle; EllipseF converted = unitCircle;
Assert.AreEqual(unitCircle, converted); Assert.Multiple(() =>
Assert.AreEqual(unitCircle.Radius, converted.HorizontalRadius); {
Assert.AreEqual(unitCircle.Radius, converted.VerticalRadius); Assert.That(converted, Is.EqualTo((EllipseF)unitCircle));
Assert.AreEqual(unitCircle.Center, converted.Center); Assert.That(converted.HorizontalRadius, Is.EqualTo(unitCircle.Radius));
Assert.That(converted.VerticalRadius, Is.EqualTo(unitCircle.Radius));
Assert.That(converted.Center, Is.EqualTo(unitCircle.Center));
});
} }
[TestMethod] [Test]
public void op_Implicit_ShouldReturnEquivalentEllipse_GivenEllipse() public void op_Implicit_ShouldReturnEquivalentEllipse_GivenEllipse()
{ {
Ellipse unitEllipse = Ellipse.Unit; Ellipse unitEllipse = Ellipse.Unit;
EllipseF converted = unitEllipse; EllipseF converted = unitEllipse;
Assert.AreEqual(unitEllipse, converted); Assert.Multiple(() =>
Assert.AreEqual(unitEllipse.HorizontalRadius, converted.HorizontalRadius); {
Assert.AreEqual(unitEllipse.VerticalRadius, converted.VerticalRadius); Assert.That(converted, Is.EqualTo((EllipseF)unitEllipse));
Assert.AreEqual(unitEllipse.Center, converted.Center); Assert.That(converted.HorizontalRadius, Is.EqualTo(unitEllipse.HorizontalRadius));
Assert.That(converted.VerticalRadius, Is.EqualTo(unitEllipse.VerticalRadius));
Assert.That(converted.Center, Is.EqualTo((PointF)unitEllipse.Center));
});
} }
[TestMethod] [Test]
public void VerticalRadius_ShouldBe0_GivenEmptyEllipse() 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() 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 System.Drawing;
using Microsoft.VisualStudio.TestTools.UnitTesting; using NUnit.Framework;
using X10D.Drawing; using X10D.Drawing;
namespace X10D.Tests.Drawing; namespace X10D.Tests.Drawing;
[TestClass] [TestFixture]
public class EllipseTests internal class EllipseTests
{ {
[TestMethod] [Test]
public void Area_ShouldBePiRadiusRadius_GivenUnitEllipse() public void Area_ShouldBePiRadiusRadius_GivenUnitEllipse()
{ {
var unitEllipse = Ellipse.Unit; 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() public void ApproximateCircumference_ShouldBe2PiRadius_GivenUnitEllipse()
{ {
var unitEllipse = Ellipse.Unit; 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() public void Constructor_ShouldGiveCorrectEllipse()
{ {
var ellipse = new Ellipse(Point.Empty, new Size(2, 1)); var ellipse = new Ellipse(Point.Empty, new Size(2, 1));
Assert.AreEqual(new Point(0, 0), ellipse.Center); Assert.Multiple(() =>
Assert.AreEqual(new Size(2, 1), ellipse.Radius); {
Assert.That(ellipse.Center, Is.EqualTo(new Point(0, 0)));
Assert.That(ellipse.Radius, Is.EqualTo(new Size(2, 1)));
});
ellipse = new Ellipse(0, 0, 2, 1); ellipse = new Ellipse(0, 0, 2, 1);
Assert.AreEqual(new Point(0, 0), ellipse.Center); Assert.Multiple(() =>
Assert.AreEqual(new Size(2, 1), ellipse.Radius); {
Assert.That(ellipse.Center, Is.EqualTo(new Point(0, 0)));
Assert.That(ellipse.Radius, Is.EqualTo(new Size(2, 1)));
});
} }
[TestMethod] [Test]
public void Equals_ShouldBeTrue_GivenTwoUnitEllipses() public void Equals_ShouldBeTrue_GivenTwoUnitEllipses()
{ {
var unitEllipse1 = Ellipse.Unit; var unitEllipse1 = Ellipse.Unit;
var unitEllipse2 = Ellipse.Unit; var unitEllipse2 = Ellipse.Unit;
Assert.AreEqual(unitEllipse1, unitEllipse2); Assert.Multiple(() =>
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() public void Equals_ShouldBeFalse_GivenDifferentEllipses()
{ {
Assert.AreNotEqual(Ellipse.Unit, Ellipse.Empty); Assert.Multiple(() =>
Assert.IsFalse(Ellipse.Unit == Ellipse.Empty); {
Assert.IsTrue(Ellipse.Unit != Ellipse.Empty); 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() 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() public void GetHashCode_ShouldBeCorrect_GivenEmptyEllipse()
{ {
// this test is pretty pointless, it exists only for code coverage purposes // this test is pretty pointless, it exists only for code coverage purposes
int hashCode = Ellipse.Empty.GetHashCode(); int hashCode = Ellipse.Empty.GetHashCode();
Assert.AreEqual(hashCode, Ellipse.Empty.GetHashCode()); Assert.That(Ellipse.Empty.GetHashCode(), Is.EqualTo(hashCode));
} }
[TestMethod] [Test]
public void GetHashCode_ShouldBeCorrect_GivenUnitEllipse() public void GetHashCode_ShouldBeCorrect_GivenUnitEllipse()
{ {
// this test is pretty pointless, it exists only for code coverage purposes // this test is pretty pointless, it exists only for code coverage purposes
int hashCode = Ellipse.Unit.GetHashCode(); int hashCode = Ellipse.Unit.GetHashCode();
Assert.AreEqual(hashCode, Ellipse.Unit.GetHashCode()); Assert.That(Ellipse.Unit.GetHashCode(), Is.EqualTo(hashCode));
} }
[TestMethod] [Test]
public void HorizontalRadius_ShouldBe0_GivenEmptyEllipse() 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() 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() public void op_Implicit_ShouldReturnEquivalentEllipse_GivenCircle()
{ {
Circle unitCircle = Circle.Unit; Circle unitCircle = Circle.Unit;
Ellipse converted = unitCircle; Ellipse converted = unitCircle;
Assert.AreEqual(unitCircle, converted); Assert.Multiple(() =>
Assert.AreEqual(unitCircle.Radius, converted.HorizontalRadius); {
Assert.AreEqual(unitCircle.Radius, converted.VerticalRadius); Assert.That(converted, Is.EqualTo((Ellipse)unitCircle));
Assert.AreEqual(unitCircle.Center, converted.Center); Assert.That(converted.HorizontalRadius, Is.EqualTo(unitCircle.Radius));
Assert.That(converted.VerticalRadius, Is.EqualTo(unitCircle.Radius));
Assert.That(converted.Center, Is.EqualTo(unitCircle.Center));
});
} }
[TestMethod] [Test]
public void VerticalRadius_ShouldBe0_GivenEmptyEllipse() 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() 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.Drawing;
using System.Numerics; using System.Numerics;
using Microsoft.VisualStudio.TestTools.UnitTesting; using NUnit.Framework;
using X10D.Drawing; using X10D.Drawing;
namespace X10D.Tests.Drawing; namespace X10D.Tests.Drawing;
[TestClass] [TestFixture]
public class Line3DTests internal class Line3DTests
{ {
[TestMethod] [Test]
public void CompareTo_ShouldBeNegativeOne_GivenEmptyAndOne() 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() 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() 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() 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() public void CompareTo_ShouldBeZero_GivenUnitLine()
{ {
var unitLine3D = Line3D.One; var unitLine3D = Line3D.One;
Assert.AreEqual(0, unitLine3D.CompareTo(unitLine3D)); Assert.That(unitLine3D.CompareTo(unitLine3D), Is.Zero);
} }
[TestMethod] [Test]
public void CompareTo_ShouldThrowArgumentException_GivenInvalidType() 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() 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() 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() 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() 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() public void Equals_ShouldBeTrue_GivenTwoUnitLines()
{ {
Line3D first = Line3D.One; Line3D first = Line3D.One;
Line3D second = Line3D.One; Line3D second = Line3D.One;
Assert.AreEqual(first, second); Assert.That(second, Is.EqualTo(first));
Assert.IsTrue(first == second); Assert.That(second == first);
Assert.IsFalse(first != second);
} }
[TestMethod] [Test]
public void Equals_ShouldBeFalse_GivenDifferentLines() public void Equals_ShouldBeFalse_GivenDifferentLines()
{ {
Assert.AreNotEqual(Line3D.One, Line3D.Empty); Assert.That(Line3D.Empty, Is.Not.EqualTo(Line3D.One));
Assert.IsFalse(Line3D.One == Line3D.Empty); Assert.That(Line3D.Empty != Line3D.One);
Assert.IsTrue(Line3D.One != Line3D.Empty);
} }
[TestMethod] [Test]
public void Equals_ShouldBeFalse_GivenDifferentObjects() 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() public void GetHashCode_ShouldBeCorrect_GivenEmptyLine()
{ {
// this test is pretty pointless, it exists only for code coverage purposes // this test is pretty pointless, it exists only for code coverage purposes
int hashCode = Line3D.Empty.GetHashCode(); int hashCode = Line3D.Empty.GetHashCode();
Assert.AreEqual(hashCode, Line3D.Empty.GetHashCode()); Assert.That(Line3D.Empty.GetHashCode(), Is.EqualTo(hashCode));
} }
[TestMethod] [Test]
public void GetHashCode_ShouldBeCorrect_GivenUnitLine() public void GetHashCode_ShouldBeCorrect_GivenUnitLine()
{ {
// this test is pretty pointless, it exists only for code coverage purposes // this test is pretty pointless, it exists only for code coverage purposes
int hashCode = Line3D.One.GetHashCode(); int hashCode = Line3D.One.GetHashCode();
Assert.AreEqual(hashCode, Line3D.One.GetHashCode()); Assert.That(Line3D.One.GetHashCode(), Is.EqualTo(hashCode));
} }
[TestMethod] [Test]
public void op_Explicit_ShouldReturnEquivalentLine_GivenLine() public void op_Explicit_ShouldReturnEquivalentLine_GivenLine()
{ {
Line3D oneLine = new Line3D(Vector3.Zero, Vector3.UnitX + Vector3.UnitY); Line3D oneLine = new Line3D(Vector3.Zero, Vector3.UnitX + Vector3.UnitY);
@ -119,12 +118,15 @@ public class Line3DTests
var expectedStart = new Point((int)oneLine.Start.X, (int)oneLine.Start.Y); var expectedStart = new Point((int)oneLine.Start.X, (int)oneLine.Start.Y);
var expectedEnd = new Point((int)oneLine.End.X, (int)oneLine.End.Y); var expectedEnd = new Point((int)oneLine.End.X, (int)oneLine.End.Y);
Assert.AreEqual(oneLine.Length, converted.Length); Assert.Multiple(() =>
Assert.AreEqual(expectedStart, converted.Start); {
Assert.AreEqual(expectedEnd, converted.End); Assert.That(converted.Length, Is.EqualTo(oneLine.Length));
Assert.That(converted.Start, Is.EqualTo(expectedStart));
Assert.That(converted.End, Is.EqualTo(expectedEnd));
});
} }
[TestMethod] [Test]
public void op_Explicit_ShouldReturnEquivalentLineF_GivenLine() public void op_Explicit_ShouldReturnEquivalentLineF_GivenLine()
{ {
Line3D oneLine = new Line3D(Vector3.Zero, Vector3.UnitX + Vector3.UnitY); Line3D oneLine = new Line3D(Vector3.Zero, Vector3.UnitX + Vector3.UnitY);
@ -133,21 +135,25 @@ public class Line3DTests
var expectedStart = new PointF(oneLine.Start.X, oneLine.Start.Y); var expectedStart = new PointF(oneLine.Start.X, oneLine.Start.Y);
var expectedEnd = new PointF(oneLine.End.X, oneLine.End.Y); var expectedEnd = new PointF(oneLine.End.X, oneLine.End.Y);
Assert.AreEqual(oneLine.Length, converted.Length); Assert.Multiple(() =>
Assert.AreEqual(expectedStart, converted.Start); {
Assert.AreEqual(expectedEnd, converted.End); Assert.That(converted.Length, Is.EqualTo(oneLine.Length));
Assert.That(converted.Start, Is.EqualTo(expectedStart));
Assert.That(converted.End, Is.EqualTo(expectedEnd));
});
} }
[TestMethod] [Test]
public void op_GreaterThan_True_GivenUnitAndEmptyCircle() public void op_GreaterThan_True_GivenUnitAndEmptyCircle()
{ {
Assert.IsTrue(Line3D.One > Line3D.Empty); Assert.That(Line3D.One, Is.GreaterThan(Line3D.Empty));
Assert.IsTrue(Line3D.One >= Line3D.Empty); Assert.That(Line3D.One, Is.GreaterThanOrEqualTo(Line3D.Empty));
Assert.IsFalse(Line3D.One < Line3D.Empty);
Assert.IsFalse(Line3D.One <= Line3D.Empty); Assert.That(Line3D.One > Line3D.Empty);
Assert.That(Line3D.One >= Line3D.Empty);
} }
[TestMethod] [Test]
public void op_Implicit_ShouldReturnEquivalentLine_GivenLine() public void op_Implicit_ShouldReturnEquivalentLine_GivenLine()
{ {
Line oneLine = Line.One; Line oneLine = Line.One;
@ -156,13 +162,16 @@ public class Line3DTests
var expectedStart = new Vector3(oneLine.Start.X, oneLine.Start.Y, 0.0f); var expectedStart = new Vector3(oneLine.Start.X, oneLine.Start.Y, 0.0f);
var expectedEnd = new Vector3(oneLine.End.X, oneLine.End.Y, 0.0f); var expectedEnd = new Vector3(oneLine.End.X, oneLine.End.Y, 0.0f);
Assert.AreEqual(oneLine, converted); Assert.Multiple(() =>
Assert.AreEqual(oneLine.Length, converted.Length); {
Assert.AreEqual(expectedStart, converted.Start); Assert.That(converted, Is.EqualTo((Line3D)oneLine));
Assert.AreEqual(expectedEnd, converted.End); Assert.That(converted.Length, Is.EqualTo(oneLine.Length));
Assert.That(converted.Start, Is.EqualTo(expectedStart));
Assert.That(converted.End, Is.EqualTo(expectedEnd));
});
} }
[TestMethod] [Test]
public void op_Implicit_ShouldReturnEquivalentLine_GivenLineF() public void op_Implicit_ShouldReturnEquivalentLine_GivenLineF()
{ {
LineF oneLine = LineF.One; LineF oneLine = LineF.One;
@ -171,18 +180,22 @@ public class Line3DTests
var expectedStart = new Vector3(oneLine.Start.X, oneLine.Start.Y, 0.0f); var expectedStart = new Vector3(oneLine.Start.X, oneLine.Start.Y, 0.0f);
var expectedEnd = new Vector3(oneLine.End.X, oneLine.End.Y, 0.0f); var expectedEnd = new Vector3(oneLine.End.X, oneLine.End.Y, 0.0f);
Assert.AreEqual(oneLine, converted); Assert.Multiple(() =>
Assert.AreEqual(oneLine.Length, converted.Length); {
Assert.AreEqual(expectedStart, converted.Start); Assert.That(converted, Is.EqualTo((Line3D)oneLine));
Assert.AreEqual(expectedEnd, converted.End); 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() public void op_LessThan_True_GivenEmptyAndUnitCircle()
{ {
Assert.IsTrue(Line3D.Empty < Line3D.One); Assert.That(Line3D.Empty, Is.LessThan(Line3D.One));
Assert.IsTrue(Line3D.Empty <= Line3D.One); Assert.That(Line3D.Empty, Is.LessThanOrEqualTo(Line3D.One));
Assert.IsFalse(Line3D.Empty > Line3D.One); Assert.That(Line3D.Empty < Line3D.One);
Assert.IsFalse(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; using X10D.Drawing;
namespace X10D.Tests.Drawing; namespace X10D.Tests.Drawing;
[TestClass] [TestFixture]
public class LineFTests internal class LineFTests
{ {
[TestMethod] [Test]
public void CompareTo_ShouldBeNegativeOne_GivenEmptyAndOne() 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() 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() 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() 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() public void CompareTo_ShouldBeZero_GivenUnitLine()
{ {
var unitLineF = LineF.One; Assert.That(LineF.One.CompareTo(LineF.One), Is.Zero);
Assert.AreEqual(0, unitLineF.CompareTo(unitLineF));
} }
[TestMethod] [Test]
public void CompareTo_ShouldThrowArgumentException_GivenInvalidType() 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() 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() 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() 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() public void Equals_ShouldBeTrue_GivenTwoUnitLines()
{ {
LineF first = LineF.One; LineF first = LineF.One;
LineF second = LineF.One; LineF second = LineF.One;
Assert.AreEqual(first, second); Assert.Multiple(() =>
Assert.IsTrue(first == second); {
Assert.IsFalse(first != second); 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() public void Equals_ShouldBeFalse_GivenDifferentLines()
{ {
Assert.AreNotEqual(LineF.One, LineF.Empty); Assert.Multiple(() =>
Assert.IsFalse(LineF.One == LineF.Empty); {
Assert.IsTrue(LineF.One != LineF.Empty); 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() 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() public void GetHashCode_ShouldBeCorrect_GivenEmptyLine()
{ {
// this test is pretty pointless, it exists only for code coverage purposes // this test is pretty pointless, it exists only for code coverage purposes
int hashCode = LineF.Empty.GetHashCode(); int hashCode = LineF.Empty.GetHashCode();
Assert.AreEqual(hashCode, LineF.Empty.GetHashCode()); Assert.That(LineF.Empty.GetHashCode(), Is.EqualTo(hashCode));
} }
[TestMethod] [Test]
public void GetHashCode_ShouldBeCorrect_GivenUnitLine() public void GetHashCode_ShouldBeCorrect_GivenUnitLine()
{ {
// this test is pretty pointless, it exists only for code coverage purposes // this test is pretty pointless, it exists only for code coverage purposes
int hashCode = LineF.One.GetHashCode(); int hashCode = LineF.One.GetHashCode();
Assert.AreEqual(hashCode, LineF.One.GetHashCode()); Assert.That(LineF.One.GetHashCode(), Is.EqualTo(hashCode));
} }
[TestMethod] [Test]
public void op_Explicit_ShouldReturnEquivalentLine_GivenLine() public void op_Explicit_ShouldReturnEquivalentLine_GivenLine()
{ {
LineF oneLine = LineF.One; LineF oneLine = LineF.One;
Line converted = (Line)oneLine; Line converted = (Line)oneLine;
Assert.AreEqual(oneLine, converted); Assert.Multiple(() =>
Assert.AreEqual(oneLine.Length, converted.Length); {
Assert.AreEqual(oneLine.Start, converted.Start); Assert.That(converted, Is.EqualTo((Line)oneLine));
Assert.AreEqual(oneLine.End, converted.End); 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() public void op_GreaterThan_True_GivenUnitAndEmptyCircle()
{ {
Assert.IsTrue(LineF.One > LineF.Empty); Assert.That(LineF.One, Is.GreaterThan(LineF.Empty));
Assert.IsTrue(LineF.One >= LineF.Empty); Assert.That(LineF.One, Is.GreaterThanOrEqualTo(LineF.Empty));
Assert.IsFalse(LineF.One < LineF.Empty); Assert.That(LineF.One > LineF.Empty);
Assert.IsFalse(LineF.One <= LineF.Empty); Assert.That(LineF.One >= LineF.Empty);
} }
[TestMethod] [Test]
public void op_Implicit_ShouldReturnEquivalentLine_GivenLine() public void op_Implicit_ShouldReturnEquivalentLine_GivenLine()
{ {
Line oneLine = Line.One; Line oneLine = Line.One;
LineF converted = oneLine; LineF converted = oneLine;
Assert.AreEqual(oneLine, converted); Assert.Multiple(() =>
Assert.AreEqual(oneLine.Length, converted.Length); {
Assert.AreEqual(oneLine.Start, converted.Start); Assert.That(converted, Is.EqualTo((LineF)oneLine));
Assert.AreEqual(oneLine.End, converted.End); 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() public void op_LessThan_True_GivenEmptyAndUnitCircle()
{ {
Assert.IsTrue(LineF.Empty < LineF.One); Assert.That(LineF.Empty, Is.LessThan(LineF.One));
Assert.IsTrue(LineF.Empty <= LineF.One); Assert.That(LineF.Empty, Is.LessThanOrEqualTo(LineF.One));
Assert.IsFalse(LineF.Empty > LineF.One); Assert.That(LineF.Empty < LineF.One);
Assert.IsFalse(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; using X10D.Drawing;
namespace X10D.Tests.Drawing; namespace X10D.Tests.Drawing;
[TestClass] [TestFixture]
public class LineTests internal class LineTests
{ {
[TestMethod] [Test]
public void CompareTo_ShouldBeNegativeOne_GivenEmptyAndOne() 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() 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() 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() 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() public void CompareTo_ShouldBeZero_GivenUnitLine()
{ {
var unitLine = Line.One; var unitLine = Line.One;
Assert.AreEqual(0, unitLine.CompareTo(unitLine)); Assert.That(unitLine.CompareTo(unitLine), Is.Zero);
} }
[TestMethod] [Test]
public void CompareTo_ShouldThrowArgumentException_GivenInvalidType() 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() public void Equals_ShouldBeTrue_GivenTwoUnitLines()
{ {
Line first = Line.One; Line first = Line.One;
Line second = Line.One; Line second = Line.One;
Assert.AreEqual(first, second); Assert.Multiple(() =>
Assert.IsTrue(first == second); {
Assert.IsFalse(first != second); 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() public void Equals_ShouldBeFalse_GivenDifferentLines()
{ {
Assert.AreNotEqual(Line.One, Line.Empty); Assert.Multiple(() =>
Assert.IsFalse(Line.One == Line.Empty); {
Assert.IsTrue(Line.One != Line.Empty); 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() 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() public void GetHashCode_ShouldBeCorrect_GivenEmptyLine()
{ {
// this test is pretty pointless, it exists only for code coverage purposes // this test is pretty pointless, it exists only for code coverage purposes
int hashCode = Line.Empty.GetHashCode(); int hashCode = Line.Empty.GetHashCode();
Assert.AreEqual(hashCode, Line.Empty.GetHashCode()); Assert.That(Line.Empty.GetHashCode(), Is.EqualTo(hashCode));
} }
[TestMethod] [Test]
public void GetHashCode_ShouldBeCorrect_GivenUnitLine() public void GetHashCode_ShouldBeCorrect_GivenUnitLine()
{ {
// this test is pretty pointless, it exists only for code coverage purposes // this test is pretty pointless, it exists only for code coverage purposes
int hashCode = Line.One.GetHashCode(); int hashCode = Line.One.GetHashCode();
Assert.AreEqual(hashCode, Line.One.GetHashCode()); Assert.That(Line.One.GetHashCode(), Is.EqualTo(hashCode));
} }
[TestMethod] [Test]
public void Length_ShouldBe0_GivenEmptyLine() 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() 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() 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() public void op_GreaterThan_True_GivenUnitAndEmptyCircle()
{ {
Assert.IsTrue(Line.One > Line.Empty); Assert.That(Line.One, Is.GreaterThan(Line.Empty));
Assert.IsTrue(Line.One >= Line.Empty); Assert.That(Line.One, Is.GreaterThanOrEqualTo(Line.Empty));
Assert.IsFalse(Line.One < Line.Empty); Assert.That(Line.One > Line.Empty);
Assert.IsFalse(Line.One <= Line.Empty); Assert.That(Line.One >= Line.Empty);
} }
[TestMethod] [Test]
public void op_LessThan_True_GivenEmptyAndUnitCircle() public void op_LessThan_True_GivenEmptyAndUnitCircle()
{ {
Assert.IsTrue(Line.Empty < Line.One); Assert.That(Line.Empty, Is.LessThan(Line.One));
Assert.IsTrue(Line.Empty <= Line.One); Assert.That(Line.Empty, Is.LessThanOrEqualTo(Line.One));
Assert.IsFalse(Line.Empty > Line.One); Assert.That(Line.Empty < Line.One);
Assert.IsFalse(Line.Empty >= Line.One); Assert.That(Line.Empty <= Line.One);
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,37 +1,37 @@
using System.Drawing; using System.Drawing;
using Microsoft.VisualStudio.TestTools.UnitTesting; using NUnit.Framework;
using X10D.Drawing; using X10D.Drawing;
namespace X10D.Tests.Drawing; namespace X10D.Tests.Drawing;
[TestClass] [TestFixture]
public class RandomTests internal class RandomTests
{ {
[TestMethod] [Test]
public void NextColorArgb_ShouldReturn331515e5_GivenSeed1234() public void NextColorArgb_ShouldReturn331515e5_GivenSeed1234()
{ {
var random = new Random(1234); 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() public void NextColorArgb_ShouldThrow_GivenNull()
{ {
Random? random = null; Random random = null!;
Assert.ThrowsException<ArgumentNullException>(() => random!.NextColorArgb()); Assert.Throws<ArgumentNullException>(() => random.NextColorArgb());
} }
[TestMethod] [Test]
public void NextColorRgb_ShouldReturn1515e5_GivenSeed1234() public void NextColorRgb_ShouldReturn1515e5_GivenSeed1234()
{ {
var random = new Random(1234); 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() public void NextColorRgb_ShouldThrow_GivenNull()
{ {
Random? random = null; Random random = null!;
Assert.ThrowsException<ArgumentNullException>(() => random!.NextColorRgb()); Assert.Throws<ArgumentNullException>(() => random.NextColorRgb());
} }
} }

View File

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

View File

@ -1,135 +1,142 @@
using Microsoft.VisualStudio.TestTools.UnitTesting; using NUnit.Framework;
using X10D.Drawing; using X10D.Drawing;
namespace X10D.Tests.Drawing; namespace X10D.Tests.Drawing;
[TestClass] [TestFixture]
public class SphereTests internal class SphereTests
{ {
[TestMethod] [Test]
public void Circumference_ShouldBe2PiRadius_GivenUnitCircle() public void Circumference_ShouldBe2PiRadius_GivenUnitCircle()
{ {
var unitSphere = Sphere.Unit; 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() 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() 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() 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() 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() public void CompareTo_ShouldBeZero_GivenUnitCircle()
{ {
var unitCircle = Sphere.Unit; var unitCircle = Sphere.Unit;
Assert.AreEqual(0, unitCircle.CompareTo(unitCircle)); Assert.That(unitCircle.CompareTo(unitCircle), Is.Zero);
} }
[TestMethod] [Test]
public void CompareTo_ShouldThrowArgumentException_GivenInvalidType() 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() 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() public void Equals_ShouldBeTrue_GivenTwoUnitCircles()
{ {
var unitCircle1 = Sphere.Unit; var unitCircle1 = Sphere.Unit;
var unitCircle2 = Sphere.Unit; var unitCircle2 = Sphere.Unit;
Assert.AreEqual(unitCircle1, unitCircle2);
Assert.IsTrue(unitCircle1 == unitCircle2); Assert.Multiple(() =>
Assert.IsFalse(unitCircle1 != unitCircle2); {
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() 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() public void Equals_ShouldBeFalse_GivenDifferentCircles()
{ {
Assert.AreNotEqual(Sphere.Unit, Sphere.Empty); Assert.That(Sphere.Empty, Is.Not.EqualTo(Sphere.Unit));
Assert.IsFalse(Sphere.Unit == Sphere.Empty); Assert.That(Sphere.Unit, Is.Not.EqualTo(Sphere.Empty));
Assert.IsTrue(Sphere.Unit != Sphere.Empty); Assert.That(Sphere.Empty != Sphere.Unit);
Assert.That(Sphere.Unit != Sphere.Empty);
} }
[TestMethod] [Test]
public void GetHashCode_ShouldBeCorrect_GivenEmptyCircle() public void GetHashCode_ShouldBeCorrect_GivenEmptyCircle()
{ {
// this test is pretty pointless, it exists only for code coverage purposes // this test is pretty pointless, it exists only for code coverage purposes
int hashCode = Sphere.Empty.GetHashCode(); int hashCode = Sphere.Empty.GetHashCode();
Assert.AreEqual(hashCode, Sphere.Empty.GetHashCode()); Assert.That(Sphere.Empty.GetHashCode(), Is.EqualTo(hashCode));
} }
[TestMethod] [Test]
public void GetHashCode_ShouldBeCorrect_GivenUnitCircle() public void GetHashCode_ShouldBeCorrect_GivenUnitCircle()
{ {
// this test is pretty pointless, it exists only for code coverage purposes // this test is pretty pointless, it exists only for code coverage purposes
int hashCode = Sphere.Unit.GetHashCode(); int hashCode = Sphere.Unit.GetHashCode();
Assert.AreEqual(hashCode, Sphere.Unit.GetHashCode()); Assert.That(Sphere.Unit.GetHashCode(), Is.EqualTo(hashCode));
} }
[TestMethod] [Test]
public void op_GreaterThan_True_GivenUnitAndEmptyCircle() public void op_GreaterThan_True_GivenUnitAndEmptyCircle()
{ {
Assert.IsTrue(Sphere.Unit > Sphere.Empty); Assert.That(Sphere.Unit, Is.GreaterThan(Sphere.Empty));
Assert.IsTrue(Sphere.Unit >= Sphere.Empty); Assert.That(Sphere.Unit, Is.GreaterThanOrEqualTo(Sphere.Empty));
Assert.IsFalse(Sphere.Unit < Sphere.Empty); Assert.That(Sphere.Unit > Sphere.Empty);
Assert.IsFalse(Sphere.Unit <= Sphere.Empty); Assert.That(Sphere.Unit >= Sphere.Empty);
} }
[TestMethod] [Test]
public void op_LessThan_True_GivenEmptyAndUnitCircle() public void op_LessThan_True_GivenEmptyAndUnitCircle()
{ {
Assert.IsTrue(Sphere.Empty < Sphere.Unit); Assert.That(Sphere.Empty, Is.LessThan(Sphere.Unit));
Assert.IsTrue(Sphere.Empty <= Sphere.Unit); Assert.That(Sphere.Empty, Is.LessThanOrEqualTo(Sphere.Unit));
Assert.IsFalse(Sphere.Empty > Sphere.Unit); Assert.That(Sphere.Empty < Sphere.Unit);
Assert.IsFalse(Sphere.Empty >= Sphere.Unit); Assert.That(Sphere.Empty <= Sphere.Unit);
} }
[TestMethod] [Test]
public void Radius_ShouldBe0_GivenEmptySphere() 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() 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() public void Volume_ShouldBe4Over3TimesPi_GivenUnitCircle()
{ {
var unitSphere = Sphere.Unit; 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.DependencyInjection;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
using Microsoft.VisualStudio.TestTools.UnitTesting; using NUnit.Framework;
using X10D.Hosting.DependencyInjection; using X10D.Hosting.DependencyInjection;
namespace X10D.Tests.Hosting; namespace X10D.Tests.Hosting;
[TestClass] [TestFixture]
public class ServiceCollectionTests internal class ServiceCollectionTests
{ {
[TestMethod] [Test]
public void AddHostedSingleton_ShouldRegisterServiceAsSingletonAndAsHostedService() public void AddHostedSingleton_ShouldRegisterServiceAsSingletonAndAsHostedService()
{ {
var services = new ServiceCollection(); var services = new ServiceCollection();
@ -19,14 +19,38 @@ public class ServiceCollectionTests
var service = serviceProvider.GetService<TestService>(); var service = serviceProvider.GetService<TestService>();
var hostedService = serviceProvider.GetService<IHostedService>(); var hostedService = serviceProvider.GetService<IHostedService>();
Assert.IsNotNull(service); Assert.Multiple(() =>
Assert.IsNotNull(hostedService); {
Assert.IsInstanceOfType(service, typeof(TestService)); Assert.That(service, Is.Not.Null);
Assert.IsInstanceOfType(hostedService, typeof(TestService)); Assert.That(hostedService, Is.Not.Null);
Assert.AreSame(service, hostedService); 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() public void AddHostedSingleton_ShouldRegisterServiceTypeAsSingletonAndAsHostedService()
{ {
var services = new ServiceCollection(); var services = new ServiceCollection();
@ -37,15 +61,48 @@ public class ServiceCollectionTests
var service = serviceProvider.GetService<TestService>(); var service = serviceProvider.GetService<TestService>();
var hostedService = serviceProvider.GetService<IHostedService>(); var hostedService = serviceProvider.GetService<IHostedService>();
Assert.IsNotNull(service); Assert.Multiple(() =>
Assert.IsNotNull(hostedService); {
Assert.IsInstanceOfType(service, typeof(TestService)); Assert.That(service, Is.Not.Null);
Assert.IsInstanceOfType(hostedService, typeof(TestService)); Assert.That(hostedService, Is.Not.Null);
Assert.AreSame(service, hostedService); 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) public Task StartAsync(CancellationToken cancellationToken)
{ {
return Task.CompletedTask; return Task.CompletedTask;

View File

@ -1,32 +1,32 @@
using Microsoft.VisualStudio.TestTools.UnitTesting; using NUnit.Framework;
using X10D.IO; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
[TestClass] [TestFixture]
public class BooleanTests internal class BooleanTests
{ {
[TestMethod] [Test]
public void GetBytes_ReturnsArrayContaining1() public void GetBytes_ReturnsArrayContaining1()
{ {
const bool value = true; const bool value = true;
CollectionAssert.AreEqual(new byte[] {1}, value.GetBytes()); CollectionAssert.AreEqual(new byte[] {1}, value.GetBytes());
} }
[TestMethod] [Test]
public void TryWriteBytes_ReturnsTrue_FillsSpanContaining1_GivenLargeEnoughSpan() public void TryWriteBytes_ReturnsTrue_FillsSpanContaining1_GivenLargeEnoughSpan()
{ {
const bool value = true; const bool value = true;
Span<byte> buffer = stackalloc byte[1]; Span<byte> buffer = stackalloc byte[1];
Assert.IsTrue(value.TryWriteBytes(buffer)); Assert.That(value.TryWriteBytes(buffer));
CollectionAssert.AreEqual(new byte[] {1}, buffer.ToArray()); CollectionAssert.AreEqual(new byte[] {1}, buffer.ToArray());
} }
[TestMethod] [Test]
public void TryWriteBytes_ReturnsFalse_GivenSmallSpan() public void TryWriteBytes_ReturnsFalse_GivenSmallSpan()
{ {
const bool value = true; const bool value = true;
Span<byte> buffer = stackalloc byte[0]; Span<byte> buffer = stackalloc byte[0];
Assert.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; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
[TestClass] [TestFixture]
public class ByteTests internal class ByteTests
{ {
[TestMethod] [Test]
public void GetBytes_ReturnsArrayContainingItself() public void GetBytes_ReturnsArrayContainingItself()
{ {
const byte value = 0xFF; const byte value = 0xFF;
CollectionAssert.AreEqual(new[] {value}, value.GetBytes()); CollectionAssert.AreEqual(new[] {value}, value.GetBytes());
} }
[TestMethod] [Test]
public void TryWriteBytes_ReturnsTrue_FillsSpanContainingItself_GivenLargeEnoughSpan() public void TryWriteBytes_ReturnsTrue_FillsSpanContainingItself_GivenLargeEnoughSpan()
{ {
const byte value = 0xFF; const byte value = 0xFF;
Span<byte> buffer = stackalloc byte[1]; Span<byte> buffer = stackalloc byte[1];
Assert.IsTrue(value.TryWriteBytes(buffer)); Assert.That(value.TryWriteBytes(buffer));
CollectionAssert.AreEqual(new[] {value}, buffer.ToArray()); CollectionAssert.AreEqual(new[] {value}, buffer.ToArray());
} }
[TestMethod] [Test]
public void TryWriteBytes_ReturnsFalse_GivenSmallSpan() public void TryWriteBytes_ReturnsFalse_GivenSmallSpan()
{ {
const byte value = 0x0F; const byte value = 0x0F;
Span<byte> buffer = stackalloc byte[0]; Span<byte> buffer = stackalloc byte[0];
Assert.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; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
[TestClass] [TestFixture]
public class DirectoryInfoTests internal class DirectoryInfoTests
{ {
[TestMethod] [Test]
public void Clear_ShouldClear_GivenValidDirectory() public void Clear_ShouldClear_GivenValidDirectory()
{ {
string tempDirectoryPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); string tempDirectoryPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
var tempDirectory = new DirectoryInfo(tempDirectoryPath); var tempDirectory = new DirectoryInfo(tempDirectoryPath);
tempDirectory.Create(); tempDirectory.Create();
Assert.IsTrue(tempDirectory.Exists); Assert.That(tempDirectory.Exists);
var file = new FileInfo(Path.Combine(tempDirectory.FullName, "file")); var file = new FileInfo(Path.Combine(tempDirectory.FullName, "file"));
file.Create().Close(); file.Create().Close();
@ -24,34 +24,42 @@ public class DirectoryInfoTests
var childFile = new FileInfo(Path.Combine(childDirectory.FullName, "childFile")); var childFile = new FileInfo(Path.Combine(childDirectory.FullName, "childFile"));
childFile.Create().Close(); childFile.Create().Close();
Assert.AreEqual(1, tempDirectory.GetFiles().Length); Assert.Multiple(() =>
Assert.AreEqual(1, tempDirectory.GetDirectories().Length); {
Assert.That(tempDirectory.GetFiles(), Has.Length.EqualTo(1));
Assert.That(tempDirectory.GetDirectories(), Has.Length.EqualTo(1));
});
tempDirectory.Clear(); tempDirectory.Clear();
Assert.AreEqual(0, tempDirectory.GetFiles().Length);
Assert.AreEqual(0, tempDirectory.GetDirectories().Length); Assert.Multiple(() =>
Assert.IsTrue(tempDirectory.Exists); {
Assert.That(tempDirectory.GetFiles(), Is.Empty);
Assert.That(tempDirectory.GetDirectories(), Is.Empty);
Assert.That(tempDirectory.Exists);
});
tempDirectory.Delete(); tempDirectory.Delete();
} }
[TestMethod] [Test]
public void Clear_ShouldThrowArgumentNullException_GivenNull() public void Clear_ShouldThrowArgumentNullException_GivenNull()
{ {
Assert.ThrowsException<ArgumentNullException>(() => ((DirectoryInfo?)null)!.Clear()); Assert.Throws<ArgumentNullException>(() => ((DirectoryInfo?)null)!.Clear());
} }
[TestMethod] [Test]
public void Clear_ShouldThrowDirectoryNotFoundException_GivenInvalidDirectory() public void Clear_ShouldThrowDirectoryNotFoundException_GivenInvalidDirectory()
{ {
var directory = new DirectoryInfo(@"123:/@12#3"); var directory = new DirectoryInfo(@"123:/@12#3");
Assert.ThrowsException<DirectoryNotFoundException>(() => directory.Clear()); Assert.Throws<DirectoryNotFoundException>(() => directory.Clear());
} }
[TestMethod] [Test]
public void Clear_ShouldThrowDirectoryNotFoundException_GivenNonExistentDirectory() public void Clear_ShouldThrowDirectoryNotFoundException_GivenNonExistentDirectory()
{ {
var directory = new DirectoryInfo(@"/@12#3"); var directory = new DirectoryInfo(@"/@12#3");
Assert.IsFalse(directory.Exists); Assert.That(directory.Exists, Is.False);
Assert.ThrowsException<DirectoryNotFoundException>(() => directory.Clear()); Assert.Throws<DirectoryNotFoundException>(() => directory.Clear());
} }
} }

View File

@ -1,66 +1,66 @@
using Microsoft.VisualStudio.TestTools.UnitTesting; using NUnit.Framework;
using X10D.IO; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
[TestClass] [TestFixture]
public class DoubleTests internal class DoubleTests
{ {
[TestMethod] [Test]
public void GetBytes_ReturnsCorrectValue() public void GetBigEndianBytes_ReturnsCorrectValue()
{ {
const double value = 42.5; const double value = 42.5;
byte[] bytes = BitConverter.IsLittleEndian
? new byte[] {0, 0, 0, 0, 0, 0x40, 0x45, 0x40} var expected = new byte[] { 0x40, 0x45, 0x40, 0, 0, 0, 0, 0 };
: new byte[] {0x40, 0x45, 0x40, 0, 0, 0, 0, 0}; byte[] actual = value.GetBigEndianBytes();
CollectionAssert.AreEqual(bytes, value.GetBytes()); CollectionAssert.AreEqual(expected, actual);
} }
[TestMethod] [Test]
public void GetBytes_ReturnsCorrectValue_WithEndianness() public void GetLittleEndianBytes_ReturnsCorrectValue()
{ {
const double value = 42.5; const double value = 42.5;
byte[] littleEndian = {0, 0, 0, 0, 0, 0x40, 0x45, 0x40};
byte[] bigEndian = {0x40, 0x45, 0x40, 0, 0, 0, 0, 0};
CollectionAssert.AreEqual(littleEndian, value.GetBytes(Endianness.LittleEndian)); var expected = new byte[] { 0, 0, 0, 0, 0, 0x40, 0x45, 0x40 };
CollectionAssert.AreEqual(bigEndian, value.GetBytes(Endianness.BigEndian)); byte[] actual = value.GetLittleEndianBytes();
CollectionAssert.AreEqual(expected, actual);
} }
[TestMethod] [Test]
public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan() public void TryWriteBigEndian_ReturnsTrue_FillsSpanCorrectly()
{ {
const double value = 42.5; const double value = 42.5;
byte[] bytes = BitConverter.IsLittleEndian
? new byte[] {0, 0, 0, 0, 0, 0x40, 0x45, 0x40}
: new byte[] {0x40, 0x45, 0x40, 0, 0, 0, 0, 0};
Span<byte> buffer = stackalloc byte[8]; var expected = new byte[] { 0x40, 0x45, 0x40, 0, 0, 0, 0, 0 };
Assert.IsTrue(value.TryWriteBytes(buffer)); Span<byte> actual = stackalloc byte[8];
CollectionAssert.AreEqual(bytes, buffer.ToArray()); Assert.That(value.TryWriteBigEndian(actual));
CollectionAssert.AreEqual(expected, actual.ToArray());
} }
[TestMethod] [Test]
public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan_WithEndianness() public void TryWriteLittleEndian_ReturnsTrue_FillsSpanCorrectly()
{ {
const double value = 42.5; const double value = 42.5;
byte[] littleEndian = {0, 0, 0, 0, 0, 0x40, 0x45, 0x40};
byte[] bigEndian = {0x40, 0x45, 0x40, 0, 0, 0, 0, 0};
Span<byte> buffer = stackalloc byte[8]; var expected = new byte[] { 0, 0, 0, 0, 0, 0x40, 0x45, 0x40 };
Span<byte> actual = stackalloc byte[8];
Assert.IsTrue(value.TryWriteBytes(buffer, Endianness.LittleEndian)); Assert.That(value.TryWriteLittleEndian(actual));
CollectionAssert.AreEqual(littleEndian, buffer.ToArray()); CollectionAssert.AreEqual(expected, actual.ToArray());
Assert.IsTrue(value.TryWriteBytes(buffer, Endianness.BigEndian));
CollectionAssert.AreEqual(bigEndian, buffer.ToArray());
} }
[TestMethod] [Test]
public void TryWriteBytes_ReturnsFalse_GivenSmallSpan() public void TryWriteBigEndian_ReturnsFalse_GivenSmallSpan()
{ {
const double value = 42.5; const double value = 42.5;
Span<byte> buffer = stackalloc byte[0]; Span<byte> buffer = stackalloc byte[0];
Assert.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 System.Security.Cryptography;
using Microsoft.VisualStudio.TestTools.UnitTesting; using NUnit.Framework;
using X10D.IO; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
[TestClass] [TestFixture]
public class FileInfoTests internal class FileInfoTests
{ {
[TestMethod] [Test]
public void GetHashSha1ShouldBeCorrect() public void GetHashSha1ShouldBeCorrect()
{ {
string fileName = $"temp.{DateTimeOffset.Now.ToUnixTimeSeconds()}.bin"; var fileName = $"temp.{DateTimeOffset.Now.ToUnixTimeSeconds()}.bin";
if (File.Exists(fileName)) if (File.Exists(fileName))
{ {
Assert.Fail("Temporary file already exists"); Assert.Fail("Temporary file already exists");
} }
File.WriteAllText(fileName, "Hello World"); File.WriteAllText(fileName, "Hello World");
Assert.IsTrue(File.Exists(fileName)); Assert.That(File.Exists(fileName));
// SHA-1 // SHA-1
byte[] expectedHash = byte[] expectedHash =
@ -37,17 +37,17 @@ public class FileInfoTests
} }
} }
[TestMethod] [Test]
public void TryWriteHashSha1ShouldBeCorrect() public void TryWriteHashSha1ShouldBeCorrect()
{ {
string fileName = $"temp.{DateTimeOffset.Now.ToUnixTimeSeconds()}.bin"; var fileName = $"temp.{DateTimeOffset.Now.ToUnixTimeSeconds()}.bin";
if (File.Exists(fileName)) if (File.Exists(fileName))
{ {
Assert.Fail("Temporary file already exists"); Assert.Fail("Temporary file already exists");
} }
File.WriteAllText(fileName, "Hello World"); File.WriteAllText(fileName, "Hello World");
Assert.IsTrue(File.Exists(fileName)); Assert.That(File.Exists(fileName));
// SHA-1 // SHA-1
byte[] expectedHash = byte[] expectedHash =
@ -60,7 +60,7 @@ public class FileInfoTests
{ {
Span<byte> hash = stackalloc byte[20]; Span<byte> hash = stackalloc byte[20];
new FileInfo(fileName).TryWriteHash<SHA1>(hash, out int bytesWritten); new FileInfo(fileName).TryWriteHash<SHA1>(hash, out int bytesWritten);
Assert.AreEqual(expectedHash.Length, bytesWritten); Assert.That(bytesWritten, Is.EqualTo(expectedHash.Length));
CollectionAssert.AreEqual(expectedHash, hash.ToArray()); CollectionAssert.AreEqual(expectedHash, hash.ToArray());
} }
finally finally
@ -69,25 +69,25 @@ public class FileInfoTests
} }
} }
[TestMethod] [Test]
public void GetHashNullShouldThrow() public void GetHashNullShouldThrow()
{ {
// any HashAlgorithm will do, but SHA1 is used above. so to remain consistent, we use it here // any HashAlgorithm will do, but SHA1 is used above. so to remain consistent, we use it here
Assert.ThrowsException<ArgumentNullException>(() => ((FileInfo?)null)!.GetHash<SHA1>()); Assert.Throws<ArgumentNullException>(() => _ = ((FileInfo?)null)!.GetHash<SHA1>());
Assert.ThrowsException<ArgumentNullException>(() => ((FileInfo?)null)!.TryWriteHash<SHA1>(Span<byte>.Empty, out _)); Assert.Throws<ArgumentNullException>(() => ((FileInfo?)null)!.TryWriteHash<SHA1>(Span<byte>.Empty, out _));
} }
[TestMethod] [Test]
public void GetHashInvalidFileShouldThrow() public void GetHashInvalidFileShouldThrow()
{ {
string fileName = $"temp.{DateTimeOffset.Now.ToUnixTimeSeconds()}.bin"; var fileName = $"temp.{DateTimeOffset.Now.ToUnixTimeSeconds()}.bin";
if (File.Exists(fileName)) if (File.Exists(fileName))
{ {
Assert.Fail("Temporary file already exists"); Assert.Fail("Temporary file already exists");
} }
// any HashAlgorithm will do, but SHA1 is used above. so to remain consistent, we use it here // any HashAlgorithm will do, but SHA1 is used above. so to remain consistent, we use it here
Assert.ThrowsException<FileNotFoundException>(() => new FileInfo(fileName).GetHash<SHA1>()); Assert.Throws<FileNotFoundException>(() => _ = new FileInfo(fileName).GetHash<SHA1>());
Assert.ThrowsException<FileNotFoundException>(() => new FileInfo(fileName).TryWriteHash<SHA1>(Span<byte>.Empty, out _)); 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; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
[TestClass] [TestFixture]
public class Int16Tests internal class Int16Tests
{ {
[TestMethod] [Test]
public void GetBytes_ReturnsCorrectValue() public void GetLittleEndianBytes_ReturnsCorrectValue()
{ {
const short value = 0x0F; 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] [Test]
public void GetBytes_ReturnsCorrectValue_WithEndianness() public void GetBigEndianBytes_ReturnsCorrectValue()
{ {
const short value = 0x0F; const short value = 0x0F;
byte[] littleEndian = {0x0F, 0};
byte[] bigEndian = {0, 0x0F};
CollectionAssert.AreEqual(littleEndian, value.GetBytes(Endianness.LittleEndian)); byte[] expected = { 0, 0x0F };
CollectionAssert.AreEqual(bigEndian, value.GetBytes(Endianness.BigEndian)); byte[] actual = value.GetBigEndianBytes();
CollectionAssert.AreEqual(expected, actual);
} }
[TestMethod] [Test]
public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan() public void TryWriteLittleEndian_ReturnsTrue_FillsSpanCorrectly()
{ {
const short value = 0x0F; const short value = 0x0F;
byte[] bytes = BitConverter.IsLittleEndian ? new byte[] {0x0F, 0} : new byte[] {0, 0x0F};
Span<byte> buffer = stackalloc byte[2]; byte[] expected = { 0x0F, 0 };
Assert.IsTrue(value.TryWriteBytes(buffer)); Span<byte> actual = stackalloc byte[2];
CollectionAssert.AreEqual(bytes, buffer.ToArray()); Assert.That(value.TryWriteLittleEndian(actual));
CollectionAssert.AreEqual(expected, actual.ToArray());
} }
[TestMethod] [Test]
public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan_WithEndianness() public void TryWriteBigEndian_ReturnsTrue_FillsSpanCorrectly()
{ {
const short value = 0x0F; const short value = 0x0F;
byte[] littleEndian = {0x0F, 0};
byte[] bigEndian = {0, 0x0F};
Span<byte> buffer = stackalloc byte[2]; byte[] expected = { 0, 0x0F };
Span<byte> actual = stackalloc byte[2];
Assert.IsTrue(value.TryWriteBytes(buffer, Endianness.LittleEndian)); Assert.That(value.TryWriteBigEndian(actual));
CollectionAssert.AreEqual(littleEndian, buffer.ToArray()); CollectionAssert.AreEqual(expected, actual.ToArray());
Assert.IsTrue(value.TryWriteBytes(buffer, Endianness.BigEndian));
CollectionAssert.AreEqual(bigEndian, buffer.ToArray());
} }
[TestMethod] [Test]
public void TryWriteBytes_ReturnsFalse_GivenSmallSpan() public void TryWriteLittleEndian_RReturnsFalse_GivenSmallSpan()
{ {
const short value = 0x0F; const short value = 0x0F;
Span<byte> buffer = stackalloc byte[0]; 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; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
[TestClass] [TestFixture]
public class Int32Tests internal class Int32Tests
{ {
[TestMethod] [Test]
public void GetBytes_ReturnsCorrectValue() public void GetBigEndianBytes_ReturnsCorrectValue()
{ {
const int value = 0x0F; const int value = 0x0F;
byte[] bytes = BitConverter.IsLittleEndian ? new byte[] {0x0F, 0, 0, 0} : new byte[] {0, 0, 0, 0x0F};
CollectionAssert.AreEqual(bytes, value.GetBytes()); var expected = new byte[] { 0, 0, 0, 0x0F };
byte[] actual = value.GetBigEndianBytes();
CollectionAssert.AreEqual(expected, actual);
} }
[TestMethod] [Test]
public void GetBytes_ReturnsCorrectValue_WithEndianness() public void GetLittleEndianBytes_ReturnsCorrectValue()
{ {
const int value = 0x0F; const int value = 0x0F;
byte[] littleEndian = {0x0F, 0, 0, 0};
byte[] bigEndian = {0, 0, 0, 0x0F};
CollectionAssert.AreEqual(littleEndian, value.GetBytes(Endianness.LittleEndian)); var expected = new byte[] { 0x0F, 0, 0, 0 };
CollectionAssert.AreEqual(bigEndian, value.GetBytes(Endianness.BigEndian)); byte[] actual = value.GetLittleEndianBytes();
CollectionAssert.AreEqual(expected, actual);
} }
[TestMethod] [Test]
public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan() public void TryWriteBigEndian_ReturnsTrue_FillsSpanCorrectly()
{ {
const int value = 0x0F; 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]; var expected = new byte[] { 0, 0, 0, 0x0F };
Assert.IsTrue(value.TryWriteBytes(buffer)); Span<byte> actual = stackalloc byte[4];
CollectionAssert.AreEqual(bytes, buffer.ToArray()); Assert.That(value.TryWriteBigEndian(actual));
CollectionAssert.AreEqual(expected, actual.ToArray());
} }
[TestMethod] [Test]
public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan_WithEndianness() public void TryWriteLittleEndian_ReturnsTrue_FillsSpanCorrectly()
{ {
const int value = 0x0F; const int value = 0x0F;
byte[] littleEndian = {0x0F, 0, 0, 0};
byte[] bigEndian = {0, 0, 0, 0x0F};
Span<byte> buffer = stackalloc byte[4]; var expected = new byte[] { 0x0F, 0, 0, 0 };
Span<byte> actual = stackalloc byte[4];
Assert.IsTrue(value.TryWriteBytes(buffer, Endianness.LittleEndian)); Assert.That(value.TryWriteLittleEndian(actual));
CollectionAssert.AreEqual(littleEndian, buffer.ToArray()); CollectionAssert.AreEqual(expected, actual.ToArray());
Assert.IsTrue(value.TryWriteBytes(buffer, Endianness.BigEndian));
CollectionAssert.AreEqual(bigEndian, buffer.ToArray());
} }
[TestMethod] [Test]
public void TryWriteBytes_ReturnsFalse_GivenSmallSpan() public void TryWriteBigEndian_ReturnsFalse_GivenSmallSpan()
{ {
const int value = 0x0F; const int value = 0x0F;
Span<byte> buffer = stackalloc byte[0]; 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; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
[TestClass] [TestFixture]
public class Int64Tests internal class Int64Tests
{ {
[TestMethod] [Test]
public void GetBytes_ReturnsCorrectValue() public void GetLittleEndianBytes_ReturnsCorrectValue()
{ {
const long value = 0x0F; const long value = 0x0F;
byte[] bytes = BitConverter.IsLittleEndian
? new byte[] {0x0F, 0, 0, 0, 0, 0, 0, 0} byte[] expected = { 0x0F, 0, 0, 0, 0, 0, 0, 0 };
: new byte[] {0, 0, 0, 0, 0, 0, 0, 0x0F}; byte[] actual = value.GetLittleEndianBytes();
CollectionAssert.AreEqual(bytes, value.GetBytes()); CollectionAssert.AreEqual(expected, actual);
} }
[TestMethod] [Test]
public void GetBytes_ReturnsCorrectValue_WithEndianness() public void GetBigEndianBytes_ReturnsCorrectValue()
{ {
const long value = 0x0F; const long value = 0x0F;
byte[] littleEndian = {0x0F, 0, 0, 0, 0, 0, 0, 0};
byte[] bigEndian = {0, 0, 0, 0, 0, 0, 0, 0x0F};
CollectionAssert.AreEqual(littleEndian, value.GetBytes(Endianness.LittleEndian)); byte[] expected = { 0, 0, 0, 0, 0, 0, 0, 0x0F };
CollectionAssert.AreEqual(bigEndian, value.GetBytes(Endianness.BigEndian)); byte[] actual = value.GetBigEndianBytes();
CollectionAssert.AreEqual(expected, actual);
} }
[TestMethod] [Test]
public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan() public void TryWriteLittleEndian_ReturnsTrue_FillsSpanCorrectly()
{ {
const long value = 0x0F; const long value = 0x0F;
byte[] bytes = BitConverter.IsLittleEndian
? new byte[] {0x0F, 0, 0, 0, 0, 0, 0, 0}
: new byte[] {0, 0, 0, 0, 0, 0, 0, 0x0F};
Span<byte> buffer = stackalloc byte[8]; byte[] expected = { 0x0F, 0, 0, 0, 0, 0, 0, 0 };
Assert.IsTrue(value.TryWriteBytes(buffer)); Span<byte> actual = stackalloc byte[8];
CollectionAssert.AreEqual(bytes, buffer.ToArray()); Assert.That(value.TryWriteLittleEndian(actual));
CollectionAssert.AreEqual(expected, actual.ToArray());
} }
[TestMethod] [Test]
public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan_WithEndianness() public void TryWriteBigEndian_ReturnsTrue_FillsSpanCorrectly()
{ {
const long value = 0x0F; const long value = 0x0F;
byte[] littleEndian = {0x0F, 0, 0, 0, 0, 0, 0, 0};
byte[] bigEndian = {0, 0, 0, 0, 0, 0, 0, 0x0F};
Span<byte> buffer = stackalloc byte[8]; byte[] expected = { 0, 0, 0, 0, 0, 0, 0, 0x0F };
Span<byte> actual = stackalloc byte[8];
Assert.IsTrue(value.TryWriteBytes(buffer, Endianness.LittleEndian)); Assert.That(value.TryWriteBigEndian(actual));
CollectionAssert.AreEqual(littleEndian, buffer.ToArray()); CollectionAssert.AreEqual(expected, actual.ToArray());
Assert.IsTrue(value.TryWriteBytes(buffer, Endianness.BigEndian));
CollectionAssert.AreEqual(bigEndian, buffer.ToArray());
} }
[TestMethod] [Test]
public void TryWriteBytes_ReturnsFalse_GivenSmallSpan() public void TryWriteLittleEndian_RReturnsFalse_GivenSmallSpan()
{ {
const long value = 0x0F; const long value = 0x0F;
Span<byte> buffer = stackalloc byte[0]; 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 System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting; using NUnit.Framework;
using X10D.IO; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
[TestClass] [TestFixture]
public class ListOfByteTests internal class ListOfByteTests
{ {
[TestMethod] [Test]
public void AsString_ShouldReturnBytes_GivenBytes() public void AsString_ShouldReturnBytes_GivenBytes()
{ {
var bytes = new byte[] {0x01, 0x02, 0x03, 0x04, 0x05}; var bytes = new byte[] {0x01, 0x02, 0x03, 0x04, 0x05};
Assert.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() public void AsString_ShouldThrow_GivenNullArray()
{ {
byte[]? bytes = null; byte[]? bytes = null;
Assert.ThrowsException<ArgumentNullException>(() => bytes!.AsString()); Assert.Throws<ArgumentNullException>(() => bytes!.AsString());
} }
[TestMethod] [Test]
public void ToDouble_ShouldReturnDouble_GivenBytes() public void ToDouble_ShouldReturnDouble_GivenBytes()
{ {
var bytes = new byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x7A, 0x40}; var bytes = new byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x7A, 0x40};
@ -31,59 +31,59 @@ public class ListOfByteTests
Array.Reverse(bytes); 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() public void ToDouble_ShouldThrow_GivenNullArray()
{ {
byte[]? bytes = null; byte[] bytes = null!;
Assert.ThrowsException<ArgumentNullException>(() => bytes!.ToDouble()); Assert.Throws<ArgumentNullException>(() => bytes.ToDouble());
} }
[TestMethod] [Test]
public void ToInt16_ShouldReturnInt16_GivenBytes() public void ToInt16_ShouldReturnInt16_GivenBytes()
{ {
var bytes = new byte[] {0xA4, 0x01}; 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() public void ToInt16_ShouldThrow_GivenNullArray()
{ {
byte[]? bytes = null; byte[] bytes = null!;
Assert.ThrowsException<ArgumentNullException>(() => bytes!.ToInt16()); Assert.Throws<ArgumentNullException>(() => bytes.ToInt16());
} }
[TestMethod] [Test]
public void ToInt32_ShouldReturnInt32_GivenBytes() public void ToInt32_ShouldReturnInt32_GivenBytes()
{ {
var bytes = new byte[] {0xA4, 0x01, 0x00, 0x00}; var bytes = new byte[] {0xA4, 0x01, 0x00, 0x00};
Assert.AreEqual(420, bytes.ToInt32()); Assert.That(bytes.ToInt32(), Is.EqualTo(420));
} }
[TestMethod] [Test]
public void ToInt32_ShouldThrow_GivenNullArray() public void ToInt32_ShouldThrow_GivenNullArray()
{ {
byte[]? bytes = null; byte[] bytes = null!;
Assert.ThrowsException<ArgumentNullException>(() => bytes!.ToInt32()); Assert.Throws<ArgumentNullException>(() => bytes.ToInt32());
} }
[TestMethod] [Test]
public void ToInt64_ShouldReturnInt32_GivenBytes() public void ToInt64_ShouldReturnInt32_GivenBytes()
{ {
var bytes = new byte[] {0xA4, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; var bytes = new byte[] {0xA4, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
Assert.AreEqual(420L, bytes.ToInt64()); Assert.That(bytes.ToInt64(), Is.EqualTo(420L));
} }
[TestMethod] [Test]
public void ToInt64_ShouldThrow_GivenNullArray() public void ToInt64_ShouldThrow_GivenNullArray()
{ {
byte[]? bytes = null; byte[]? bytes = null;
Assert.ThrowsException<ArgumentNullException>(() => bytes!.ToInt64()); Assert.Throws<ArgumentNullException>(() => bytes!.ToInt64());
} }
[TestMethod] [Test]
public void ToSingle_ShouldReturnDouble_GivenBytes() public void ToSingle_ShouldReturnDouble_GivenBytes()
{ {
var bytes = new byte[] {0x00, 0x00, 0xD2, 0x43}; var bytes = new byte[] {0x00, 0x00, 0xD2, 0x43};
@ -93,76 +93,76 @@ public class ListOfByteTests
Array.Reverse(bytes); 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() public void ToSingle_ShouldThrow_GivenNullArray()
{ {
byte[]? bytes = null; byte[] bytes = null!;
Assert.ThrowsException<ArgumentNullException>(() => bytes!.ToSingle()); Assert.Throws<ArgumentNullException>(() => bytes.ToSingle());
} }
[TestMethod] [Test]
public void ToString_ShouldReturnHelloWorld_GivenUTF8() public void ToString_ShouldReturnHelloWorld_GivenUTF8()
{ {
var bytes = new byte[] {0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64}; var bytes = new byte[] {0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64};
Assert.AreEqual("Hello World", bytes.ToString(Encoding.UTF8)); Assert.That(bytes.ToString(Encoding.UTF8), Is.EqualTo("Hello World"));
} }
[TestMethod] [Test]
public void ToString_ShouldThrow_GivenNullArray() public void ToString_ShouldThrow_GivenNullArray()
{ {
byte[]? bytes = null; byte[] bytes = null!;
Assert.ThrowsException<ArgumentNullException>(() => bytes!.ToString(Encoding.UTF8)); Assert.Throws<ArgumentNullException>(() => bytes.ToString(Encoding.UTF8));
} }
[TestMethod] [Test]
public void ToString_ShouldThrow_GivenNullEncoding() public void ToString_ShouldThrow_GivenNullEncoding()
{ {
var bytes = new byte[] {0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64}; var bytes = new byte[] {0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64};
Assert.ThrowsException<ArgumentNullException>(() => bytes.ToString(null!)); Assert.Throws<ArgumentNullException>(() => bytes.ToString(null!));
} }
[TestMethod] [Test]
public void ToUInt16_ShouldReturnInt16_GivenBytes() public void ToUInt16_ShouldReturnInt16_GivenBytes()
{ {
var bytes = new byte[] {0xA4, 0x01}; 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() public void ToUInt16_ShouldThrow_GivenNullArray()
{ {
byte[]? bytes = null; byte[] bytes = null!;
Assert.ThrowsException<ArgumentNullException>(() => bytes!.ToUInt16()); Assert.Throws<ArgumentNullException>(() => bytes.ToUInt16());
} }
[TestMethod] [Test]
public void ToUInt32_ShouldReturnInt32_GivenBytes() public void ToUInt32_ShouldReturnInt32_GivenBytes()
{ {
var bytes = new byte[] {0xA4, 0x01, 0x00, 0x00}; var bytes = new byte[] {0xA4, 0x01, 0x00, 0x00};
Assert.AreEqual(420U, bytes.ToUInt32()); Assert.That(bytes.ToUInt32(), Is.EqualTo(420U));
} }
[TestMethod] [Test]
public void ToUInt32_ShouldThrow_GivenNullArray() public void ToUInt32_ShouldThrow_GivenNullArray()
{ {
byte[]? bytes = null; byte[]? bytes = null;
Assert.ThrowsException<ArgumentNullException>(() => bytes!.ToUInt32()); Assert.Throws<ArgumentNullException>(() => bytes!.ToUInt32());
} }
[TestMethod] [Test]
public void ToUInt64_ShouldReturnInt32_GivenBytes() public void ToUInt64_ShouldReturnInt32_GivenBytes()
{ {
var bytes = new byte[] {0xA4, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; var bytes = new byte[] {0xA4, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
Assert.AreEqual(420UL, bytes.ToUInt64()); Assert.That(bytes.ToUInt64(), Is.EqualTo(420UL));
} }
[TestMethod] [Test]
public void ToUInt64_ShouldThrow_GivenNullArray() public void ToUInt64_ShouldThrow_GivenNullArray()
{ {
byte[]? bytes = null; byte[] bytes = null!;
Assert.ThrowsException<ArgumentNullException>(() => bytes!.ToUInt64()); Assert.Throws<ArgumentNullException>(() => bytes.ToUInt64());
} }
} }

View File

@ -1,33 +1,32 @@
using Microsoft.VisualStudio.TestTools.UnitTesting; using NUnit.Framework;
using X10D.IO; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
[TestClass] [TestFixture]
[CLSCompliant(false)] internal class SByteTests
public class SByteTests
{ {
[TestMethod] [Test]
public void GetBytes_ReturnsArrayContainingItself() public void GetBytes_ReturnsArrayContainingItself()
{ {
const sbyte value = 0x0F; const sbyte value = 0x0F;
CollectionAssert.AreEqual(new[] {(byte)value}, value.GetBytes()); CollectionAssert.AreEqual(new[] {(byte)value}, value.GetBytes());
} }
[TestMethod] [Test]
public void TryWriteBytes_ReturnsTrue_FillsSpanContainingItself_GivenLargeEnoughSpan() public void TryWriteBytes_ReturnsTrue_FillsSpanContainingItself_GivenLargeEnoughSpan()
{ {
const sbyte value = 0x0F; const sbyte value = 0x0F;
Span<byte> buffer = stackalloc byte[1]; Span<byte> buffer = stackalloc byte[1];
Assert.IsTrue(value.TryWriteBytes(buffer)); Assert.That(value.TryWriteBytes(buffer));
CollectionAssert.AreEqual(new[] {(byte)value}, buffer.ToArray()); CollectionAssert.AreEqual(new[] {(byte)value}, buffer.ToArray());
} }
[TestMethod] [Test]
public void TryWriteBytes_ReturnsFalse_GivenSmallSpan() public void TryWriteBytes_ReturnsFalse_GivenSmallSpan()
{ {
const sbyte value = 0x0F; const sbyte value = 0x0F;
Span<byte> buffer = stackalloc byte[0]; Span<byte> buffer = stackalloc byte[0];
Assert.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; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
[TestClass] [TestFixture]
public class SingleTests internal class SingleTests
{ {
[TestMethod] [Test]
public void GetBytes_ReturnsCorrectValue() public void GetBigEndianBytes_ReturnsCorrectValue()
{ {
const float value = 42.5f; const float value = 42.5f;
byte[] bytes = BitConverter.IsLittleEndian
? new byte[] {0, 0, 0x2A, 0x42} var expected = new byte[] { 0x42, 0x2A, 0, 0 };
: new byte[] {0x42, 0x2A, 0, 0}; byte[] actual = value.GetBigEndianBytes();
CollectionAssert.AreEqual(bytes, value.GetBytes()); CollectionAssert.AreEqual(expected, actual);
} }
[TestMethod] [Test]
public void GetBytes_ReturnsCorrectValue_WithEndianness() public void GetLittleEndianBytes_ReturnsCorrectValue()
{ {
const float value = 42.5f; const float value = 42.5f;
byte[] littleEndian = {0, 0, 0x2A, 0x42};
byte[] bigEndian = {0x42, 0x2A, 0, 0};
CollectionAssert.AreEqual(littleEndian, value.GetBytes(Endianness.LittleEndian)); var expected = new byte[] { 0, 0, 0x2A, 0x42 };
CollectionAssert.AreEqual(bigEndian, value.GetBytes(Endianness.BigEndian)); byte[] actual = value.GetLittleEndianBytes();
CollectionAssert.AreEqual(expected, actual);
} }
[TestMethod] [Test]
public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan() public void TryWriteBigEndian_ReturnsTrue_FillsSpanCorrectly()
{ {
const float value = 42.5f; const float value = 42.5f;
byte[] bytes = BitConverter.IsLittleEndian
? new byte[] {0, 0, 0x2A, 0x42}
: new byte[] {0x42, 0x2A, 0, 0};
Span<byte> buffer = stackalloc byte[4]; var expected = new byte[] { 0x42, 0x2A, 0, 0 };
Assert.IsTrue(value.TryWriteBytes(buffer)); Span<byte> actual = stackalloc byte[4];
CollectionAssert.AreEqual(bytes, buffer.ToArray()); Assert.That(value.TryWriteBigEndian(actual));
CollectionAssert.AreEqual(expected, actual.ToArray());
} }
[TestMethod] [Test]
public void TryWriteBytes_ReturnsTrue_FillsSpanCorrectly_GivenLargeEnoughSpan_WithEndianness() public void TryWriteLittleEndian_ReturnsTrue_FillsSpanCorrectly()
{ {
const float value = 42.5f; const float value = 42.5f;
byte[] littleEndian = {0, 0, 0x2A, 0x42};
byte[] bigEndian = {0x42, 0x2A, 0, 0};
Span<byte> buffer = stackalloc byte[4]; var expected = new byte[] { 0, 0, 0x2A, 0x42 };
Span<byte> actual = stackalloc byte[4];
Assert.IsTrue(value.TryWriteBytes(buffer, Endianness.LittleEndian)); Assert.That(value.TryWriteLittleEndian(actual));
CollectionAssert.AreEqual(littleEndian, buffer.ToArray()); CollectionAssert.AreEqual(expected, actual.ToArray());
Assert.IsTrue(value.TryWriteBytes(buffer, Endianness.BigEndian));
CollectionAssert.AreEqual(bigEndian, buffer.ToArray());
} }
[TestMethod] [Test]
public void TryWriteBytes_ReturnsFalse_GivenSmallSpan() public void TryWriteBigEndian_ReturnsFalse_GivenSmallSpan()
{ {
const float value = 42.5f; const float value = 42.5f;
Span<byte> buffer = stackalloc byte[0]; Span<byte> buffer = stackalloc byte[0];
Assert.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; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
public partial class StreamTests internal partial class StreamTests
{ {
[TestMethod] [Test]
public void ReadDecimal_ShouldThrowArgumentException_GivenNonReadableStream() public void ReadDecimalBigEndian_ShouldThrowArgumentNullException_GivenNullStream()
{
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()
{ {
Stream stream = null!; Stream stream = null!;
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadDecimal()); Assert.Throws<ArgumentNullException>(() => stream.ReadDecimalBigEndian());
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadDecimal(Endianness.LittleEndian));
Assert.ThrowsException<ArgumentNullException>(() => stream.ReadDecimal(Endianness.BigEndian));
} }
[TestMethod] [Test]
public void ReadDecimal_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() public void ReadDecimalLittleEndian_ShouldThrowArgumentNullException_GivenNullStream()
{ {
// we don't need to enclose this stream in a using declaration, since disposing a Stream stream = null!;
// null stream is meaningless. NullStream.Dispose actually does nothing, anyway. Assert.Throws<ArgumentNullException>(() => stream.ReadDecimalLittleEndian());
// that - coupled with the fact that encapsulating the stream in a using declaration causes the
// analyser to trip up and think the stream is disposed by the time the local is captured in
// assertion lambda - means this line is fine as it is. please do not change.
Stream stream = Stream.Null;
Assert.ThrowsException<ArgumentOutOfRangeException>(() => stream.ReadDecimal((Endianness)(-1)));
} }
[TestMethod] [Test]
public void ReadDecimal_ShouldReadBigEndian_GivenBigEndian() [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void ReadDecimalBigEndian_ShouldThrowArgumentException_GivenNonReadableStream()
{
Stream stream = new DummyStream();
Assert.Throws<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(); using var stream = new MemoryStream();
ReadOnlySpan<byte> bytes = stackalloc byte[] ReadOnlySpan<byte> bytes = stackalloc byte[]
@ -47,14 +48,17 @@ public partial class StreamTests
stream.Position = 0; stream.Position = 0;
const decimal expected = 420.0m; const decimal expected = 420.0m;
decimal actual = stream.ReadDecimal(Endianness.BigEndian); decimal actual = stream.ReadDecimalBigEndian();
Assert.AreEqual(16, stream.Position); Assert.Multiple(() =>
Assert.AreEqual(expected, actual); {
Assert.That(stream.Position, Is.EqualTo(16));
Assert.That(actual, Is.EqualTo(expected));
});
} }
[TestMethod] [Test]
public void ReadDecimal_ShouldWriteLittleEndian_GivenLittleEndian() public void ReadDecimalLittleEndian_ShouldWriteLittleEndian()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
ReadOnlySpan<byte> bytes = stackalloc byte[] ReadOnlySpan<byte> bytes = stackalloc byte[]
@ -65,9 +69,12 @@ public partial class StreamTests
stream.Position = 0; stream.Position = 0;
const decimal expected = 420.0m; const decimal expected = 420.0m;
decimal actual = stream.ReadDecimal(Endianness.LittleEndian); decimal actual = stream.ReadDecimalLittleEndian();
Assert.AreEqual(16, stream.Position); Assert.Multiple(() =>
Assert.AreEqual(expected, actual); {
Assert.That(stream.Position, Is.EqualTo(16));
Assert.That(actual, Is.EqualTo(expected));
});
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,65 +1,67 @@
using System.Diagnostics; using System.Diagnostics;
using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Diagnostics.CodeAnalysis;
using NUnit.Framework;
using X10D.IO; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
public partial class StreamTests internal partial class StreamTests
{ {
[TestMethod] [Test]
public void WriteDecimal_ShouldThrowArgumentException_GivenNonWriteableStream() public void WriteBigEndian_ShouldThrowArgumentNullException_GivenNullStream_AndDecimalArgument()
{
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()
{ {
Stream stream = null!; Stream stream = null!;
Assert.ThrowsException<ArgumentNullException>(() => stream.Write(420.0m, Endianness.LittleEndian)); Assert.Throws<ArgumentNullException>(() => stream.WriteBigEndian(420.0m));
Assert.ThrowsException<ArgumentNullException>(() => stream.Write(420.0m, Endianness.BigEndian));
} }
[TestMethod] [Test]
public void WriteDecimal_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void WriteBigEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndDecimalArgument()
{ {
// we don't need to enclose this stream in a using declaration, since disposing a Stream stream = new DummyStream();
// null stream is meaningless. NullStream.Dispose actually does nothing, anyway. Assert.Throws<ArgumentException>(() => stream.WriteBigEndian(420.0m));
// 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)));
} }
[TestMethod] [Test]
public void WriteDecimal_ShouldWriteBigEndian_GivenBigEndian() 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(); using var stream = new MemoryStream();
stream.Write(420.0m, Endianness.BigEndian); stream.WriteBigEndian(420.0m);
Assert.AreEqual(16, stream.Position); Assert.That(stream.Position, Is.EqualTo(16));
stream.Position = 0; stream.Position = 0;
Span<byte> actual = stackalloc byte[16]; Span<byte> actual = stackalloc byte[16];
ReadOnlySpan<byte> expected = stackalloc byte[] ReadOnlySpan<byte> expected = stackalloc byte[]
{ {
0x00, 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); int read = stream.Read(actual);
Assert.AreEqual(16, read); Assert.That(read, Is.EqualTo(16));
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
} }
[TestMethod] [Test]
public void WriteDecimal_ShouldWriteLittleEndian_GivenLittleEndian() public void WriteLittleEndian_ShouldWriteLittleEndian_GivenDecimalArgument()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
stream.Write(420.0m, Endianness.LittleEndian); stream.WriteLittleEndian(420.0m);
Assert.AreEqual(16, stream.Position); Assert.That(stream.Position, Is.EqualTo(16));
stream.Position = 0; stream.Position = 0;
Span<byte> actual = stackalloc byte[16]; 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}"))); 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()); 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; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
public partial class StreamTests internal partial class StreamTests
{ {
[TestMethod] [Test]
public void WriteDouble_ShouldThrowArgumentException_GivenNonWriteableStream() public void WriteBigEndian_ShouldThrowArgumentNullException_GivenNullStream_AndDoubleArgument()
{
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()
{ {
Stream stream = null!; Stream stream = null!;
Assert.ThrowsException<ArgumentNullException>(() => stream.Write(420.0, Endianness.LittleEndian)); Assert.Throws<ArgumentNullException>(() => stream.WriteBigEndian(420.0));
Assert.ThrowsException<ArgumentNullException>(() => stream.Write(420.0, Endianness.BigEndian));
} }
[TestMethod] [Test]
public void WriteDouble_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void WriteBigEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndDoubleArgument()
{ {
// we don't need to enclose this stream in a using declaration, since disposing a Stream stream = new DummyStream();
// null stream is meaningless. NullStream.Dispose actually does nothing, anyway. Assert.Throws<ArgumentException>(() => stream.WriteBigEndian(420.0));
// 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)));
} }
[TestMethod] [Test]
public void WriteDouble_ShouldWriteBigEndian_GivenBigEndian() 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(); using var stream = new MemoryStream();
stream.Write(420.0, Endianness.BigEndian); stream.WriteBigEndian(420.0);
Assert.AreEqual(8, stream.Position); Assert.That(stream.Position, Is.EqualTo(8));
stream.Position = 0; stream.Position = 0;
Span<byte> actual = stackalloc byte[8]; Span<byte> actual = stackalloc byte[8];
ReadOnlySpan<byte> expected = stackalloc byte[] { 0x40, 0x7A, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00 }; ReadOnlySpan<byte> expected = stackalloc byte[] { 0x40, 0x7A, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00 };
int read = stream.Read(actual); int read = stream.Read(actual);
Assert.AreEqual(8, read); Assert.That(read, Is.EqualTo(8));
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
} }
[TestMethod] [Test]
public void WriteDouble_ShouldWriteLittleEndian_GivenLittleEndian() public void WriteLittleEndian_ShouldWriteLittleEndian_GivenDoubleArgument()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
stream.Write(420.0, Endianness.LittleEndian); stream.WriteLittleEndian(420.0);
Assert.AreEqual(8, stream.Position); Assert.That(stream.Position, Is.EqualTo(8));
stream.Position = 0; stream.Position = 0;
Span<byte> actual = stackalloc byte[8]; Span<byte> actual = stackalloc byte[8];
ReadOnlySpan<byte> expected = stackalloc byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x7A, 0x40 }; ReadOnlySpan<byte> expected = stackalloc byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x7A, 0x40 };
int read = stream.Read(actual); int read = stream.Read(actual);
Assert.AreEqual(8, read); Assert.That(read, Is.EqualTo(8));
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); 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; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
public partial class StreamTests internal partial class StreamTests
{ {
[TestMethod] [Test]
public void WriteInt16_ShouldThrowArgumentException_GivenNonWriteableStream() public void WriteBigEndian_ShouldThrowArgumentNullException_GivenNullStream_AndInt16Argument()
{
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()
{ {
Stream stream = null!; Stream stream = null!;
Assert.ThrowsException<ArgumentNullException>(() => stream.Write((short)420, Endianness.LittleEndian)); Assert.Throws<ArgumentNullException>(() => stream.WriteBigEndian((short)420));
Assert.ThrowsException<ArgumentNullException>(() => stream.Write((short)420, Endianness.BigEndian));
} }
[TestMethod] [Test]
public void WriteInt16_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void WriteBigEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndInt16Argument()
{ {
// we don't need to enclose this stream in a using declaration, since disposing a Stream stream = new DummyStream();
// null stream is meaningless. NullStream.Dispose actually does nothing, anyway. Assert.Throws<ArgumentException>(() => stream.WriteBigEndian((short)420));
// 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)));
} }
[TestMethod] [Test]
public void WriteInt16_ShouldWriteBigEndian_GivenBigEndian() 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(); using var stream = new MemoryStream();
stream.Write((short)420, Endianness.BigEndian); stream.WriteBigEndian((short)420);
Assert.AreEqual(2, stream.Position); Assert.That(stream.Position, Is.EqualTo(2));
stream.Position = 0; stream.Position = 0;
Span<byte> actual = stackalloc byte[2]; Span<byte> actual = stackalloc byte[2];
ReadOnlySpan<byte> expected = stackalloc byte[] { 0x01, 0xA4 }; ReadOnlySpan<byte> expected = stackalloc byte[] { 0x01, 0xA4 };
int read = stream.Read(actual); int read = stream.Read(actual);
Assert.AreEqual(2, read); Assert.That(read, Is.EqualTo(2));
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
} }
[TestMethod] [Test]
public void WriteInt16_ShouldWriteLittleEndian_GivenLittleEndian() public void WriteLittleEndian_ShouldWriteLittleEndian_GivenInt16Argument()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
stream.Write((short)420, Endianness.LittleEndian); stream.WriteLittleEndian((short)420);
Assert.AreEqual(2, stream.Position); Assert.That(stream.Position, Is.EqualTo(2));
stream.Position = 0; stream.Position = 0;
Span<byte> actual = stackalloc byte[2]; Span<byte> actual = stackalloc byte[2];
ReadOnlySpan<byte> expected = stackalloc byte[] { 0xA4, 0x01 }; ReadOnlySpan<byte> expected = stackalloc byte[] { 0xA4, 0x01 };
int read = stream.Read(actual); int read = stream.Read(actual);
Assert.AreEqual(2, read); Assert.That(read, Is.EqualTo(2));
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); 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; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
public partial class StreamTests internal partial class StreamTests
{ {
[TestMethod] [Test]
public void WriteInt32_ShouldThrowArgumentException_GivenNonWriteableStream() public void WriteBigEndian_ShouldThrowArgumentNullException_GivenNullStream_AndInt32Argument()
{
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()
{ {
Stream stream = null!; Stream stream = null!;
Assert.ThrowsException<ArgumentNullException>(() => stream.Write(420, Endianness.LittleEndian)); Assert.Throws<ArgumentNullException>(() => stream.WriteBigEndian(420));
Assert.ThrowsException<ArgumentNullException>(() => stream.Write(420, Endianness.BigEndian));
} }
[TestMethod] [Test]
public void WriteInt32_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void WriteBigEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndInt32Argument()
{ {
// we don't need to enclose this stream in a using declaration, since disposing a Stream stream = new DummyStream();
// null stream is meaningless. NullStream.Dispose actually does nothing, anyway. Assert.Throws<ArgumentException>(() => stream.WriteBigEndian(420));
// 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)));
} }
[TestMethod] [Test]
public void WriteInt32_ShouldWriteBigEndian_GivenBigEndian() 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(); using var stream = new MemoryStream();
stream.Write(420, Endianness.BigEndian); stream.WriteBigEndian(420);
Assert.AreEqual(4, stream.Position); Assert.That(stream.Position, Is.EqualTo(4));
stream.Position = 0; stream.Position = 0;
Span<byte> actual = stackalloc byte[4]; Span<byte> actual = stackalloc byte[4];
ReadOnlySpan<byte> expected = stackalloc byte[] { 0x00, 0x00, 0x01, 0xA4 }; ReadOnlySpan<byte> expected = stackalloc byte[] { 0x00, 0x00, 0x01, 0xA4 };
int read = stream.Read(actual); int read = stream.Read(actual);
Assert.AreEqual(4, read); Assert.That(read, Is.EqualTo(4));
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
} }
[TestMethod] [Test]
public void WriteInt32_ShouldWriteLittleEndian_GivenLittleEndian() public void WriteLittleEndian_ShouldWriteLittleEndian_GivenInt32Argument()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
stream.Write(420, Endianness.LittleEndian); stream.WriteLittleEndian(420);
Assert.AreEqual(4, stream.Position); Assert.That(stream.Position, Is.EqualTo(4));
stream.Position = 0; stream.Position = 0;
Span<byte> actual = stackalloc byte[4]; Span<byte> actual = stackalloc byte[4];
ReadOnlySpan<byte> expected = stackalloc byte[] { 0xA4, 0x01, 0x00, 0x00 }; ReadOnlySpan<byte> expected = stackalloc byte[] { 0xA4, 0x01, 0x00, 0x00 };
int read = stream.Read(actual); int read = stream.Read(actual);
Assert.AreEqual(4, read); Assert.That(read, Is.EqualTo(4));
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); 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; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
public partial class StreamTests internal partial class StreamTests
{ {
[TestMethod] [Test]
public void WriteInt64_ShouldThrowArgumentException_GivenNonWriteableStream() public void WriteBigEndian_ShouldThrowArgumentNullException_GivenNullStream_AndInt64Argument()
{
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()
{ {
Stream stream = null!; Stream stream = null!;
Assert.ThrowsException<ArgumentNullException>(() => stream.Write(420L, Endianness.LittleEndian)); Assert.Throws<ArgumentNullException>(() => stream.WriteBigEndian(420L));
Assert.ThrowsException<ArgumentNullException>(() => stream.Write(420L, Endianness.BigEndian));
} }
[TestMethod] [Test]
public void WriteInt64_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void WriteBigEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndInt64Argument()
{ {
// we don't need to enclose this stream in a using declaration, since disposing a Stream stream = new DummyStream();
// null stream is meaningless. NullStream.Dispose actually does nothing, anyway. Assert.Throws<ArgumentException>(() => stream.WriteBigEndian(420L));
// 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)));
} }
[TestMethod] [Test]
public void WriteInt64_ShouldWriteBigEndian_GivenBigEndian() 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(); using var stream = new MemoryStream();
stream.Write(420L, Endianness.BigEndian); stream.WriteBigEndian(420L);
Assert.AreEqual(8, stream.Position); Assert.That(stream.Position, Is.EqualTo(8));
stream.Position = 0; stream.Position = 0;
Span<byte> actual = stackalloc byte[8]; Span<byte> actual = stackalloc byte[8];
ReadOnlySpan<byte> expected = stackalloc byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xA4 }; ReadOnlySpan<byte> expected = stackalloc byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xA4 };
int read = stream.Read(actual); int read = stream.Read(actual);
Assert.AreEqual(8, read); Assert.That(read, Is.EqualTo(8));
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
} }
[TestMethod] [Test]
public void WriteInt64_ShouldWriteLittleEndian_GivenLittleEndian() public void WriteLittleEndian_ShouldWriteLittleEndian_GivenLittleEndian()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
stream.Write(420L, Endianness.LittleEndian); stream.WriteLittleEndian(420L);
Assert.AreEqual(8, stream.Position); Assert.That(stream.Position, Is.EqualTo(8));
stream.Position = 0; stream.Position = 0;
Span<byte> actual = stackalloc byte[8]; Span<byte> actual = stackalloc byte[8];
ReadOnlySpan<byte> expected = stackalloc byte[] { 0xA4, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; ReadOnlySpan<byte> expected = stackalloc byte[] { 0xA4, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
int read = stream.Read(actual); int read = stream.Read(actual);
Assert.AreEqual(8, read); Assert.That(read, Is.EqualTo(8));
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); 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; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
public partial class StreamTests internal partial class StreamTests
{ {
[TestMethod] [Test]
public void WriteSingle_ShouldThrowArgumentException_GivenNonWriteableStream() public void WriteBigEndian_ShouldThrowArgumentNullException_GivenNullStream_AndSingleArgument()
{
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()
{ {
Stream stream = null!; Stream stream = null!;
Assert.ThrowsException<ArgumentNullException>(() => stream.Write(420.0f, Endianness.LittleEndian)); Assert.Throws<ArgumentNullException>(() => stream.WriteBigEndian(420.0f));
Assert.ThrowsException<ArgumentNullException>(() => stream.Write(420.0f, Endianness.BigEndian));
} }
[TestMethod] [Test]
public void WriteSingle_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void WriteBigEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndSingleArgument()
{ {
// we don't need to enclose this stream in a using declaration, since disposing a Stream stream = new DummyStream();
// null stream is meaningless. NullStream.Dispose actually does nothing, anyway. Assert.Throws<ArgumentException>(() => stream.WriteBigEndian(420.0f));
// 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)));
} }
[TestMethod] [Test]
public void WriteSingle_ShouldWriteBigEndian_GivenBigEndian() 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(); using var stream = new MemoryStream();
stream.Write(420.0f, Endianness.BigEndian); stream.WriteBigEndian(420.0f);
Assert.AreEqual(4, stream.Position); Assert.That(stream.Position, Is.EqualTo(4));
stream.Position = 0; stream.Position = 0;
Span<byte> actual = stackalloc byte[4]; Span<byte> actual = stackalloc byte[4];
ReadOnlySpan<byte> expected = stackalloc byte[] { 0x43, 0xD2, 0x00, 0x00 }; ReadOnlySpan<byte> expected = stackalloc byte[] { 0x43, 0xD2, 0x00, 0x00 };
int read = stream.Read(actual); int read = stream.Read(actual);
Assert.AreEqual(4, read); Assert.That(read, Is.EqualTo(4));
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
} }
[TestMethod] [Test]
public void WriteSingle_ShouldWriteLittleEndian_GivenLittleEndian() public void WriteLittleEndian_ShouldWriteLittleEndian_GivenSingleArgument()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
stream.Write(420.0f, Endianness.LittleEndian); stream.WriteLittleEndian(420.0f);
Assert.AreEqual(4, stream.Position); Assert.That(stream.Position, Is.EqualTo(4));
stream.Position = 0; stream.Position = 0;
Span<byte> actual = stackalloc byte[4]; Span<byte> actual = stackalloc byte[4];
ReadOnlySpan<byte> expected = stackalloc byte[] { 0x00, 0x00, 0xD2, 0x43 }; ReadOnlySpan<byte> expected = stackalloc byte[] { 0x00, 0x00, 0xD2, 0x43 };
int read = stream.Read(actual); int read = stream.Read(actual);
Assert.AreEqual(4, read); Assert.That(read, Is.EqualTo(4));
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); 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; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
public partial class StreamTests internal partial class StreamTests
{ {
[TestMethod] [Test]
[CLSCompliant(false)] public void WriteBigEndian_ShouldThrowArgumentNullException_GivenNullStream_AndUInt16Argument()
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()
{ {
Stream stream = null!; Stream stream = null!;
Assert.ThrowsException<ArgumentNullException>(() => stream.Write((ushort)420, Endianness.LittleEndian)); Assert.Throws<ArgumentNullException>(() => stream.WriteBigEndian((ushort)420));
Assert.ThrowsException<ArgumentNullException>(() => stream.Write((ushort)420, Endianness.BigEndian));
} }
[TestMethod] [Test]
[CLSCompliant(false)] [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void WriteUInt16_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() public void WriteBigEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndUInt16Argument()
{ {
// we don't need to enclose this stream in a using declaration, since disposing a Stream stream = new DummyStream();
// null stream is meaningless. NullStream.Dispose actually does nothing, anyway. Assert.Throws<ArgumentException>(() => stream.WriteBigEndian((ushort)420));
// 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)));
} }
[TestMethod] [Test]
[CLSCompliant(false)] public void WriteLittleEndian_ShouldThrowArgumentNullException_GivenNullStream_AndUInt16Argument()
public void WriteUInt16_ShouldWriteBigEndian_GivenBigEndian() {
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(); using var stream = new MemoryStream();
stream.Write((ushort)420, Endianness.BigEndian); stream.WriteBigEndian((ushort)420);
Assert.AreEqual(2, stream.Position); Assert.That(stream.Position, Is.EqualTo(2));
stream.Position = 0; stream.Position = 0;
Span<byte> actual = stackalloc byte[2]; Span<byte> actual = stackalloc byte[2];
ReadOnlySpan<byte> expected = stackalloc byte[] { 0x01, 0xA4 }; ReadOnlySpan<byte> expected = stackalloc byte[] { 0x01, 0xA4 };
int read = stream.Read(actual); int read = stream.Read(actual);
Assert.AreEqual(2, read); Assert.That(read, Is.EqualTo(2));
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
} }
[TestMethod] [Test]
[CLSCompliant(false)] public void WriteLittleEndian_ShouldWriteLittleEndian_GivenUInt16tleEndian()
public void WriteUInt16_ShouldWriteLittleEndian_GivenLittleEndian()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
stream.Write((ushort)420, Endianness.LittleEndian); stream.WriteLittleEndian((ushort)420);
Assert.AreEqual(2, stream.Position); Assert.That(stream.Position, Is.EqualTo(2));
stream.Position = 0; stream.Position = 0;
Span<byte> actual = stackalloc byte[2]; Span<byte> actual = stackalloc byte[2];
ReadOnlySpan<byte> expected = stackalloc byte[] { 0xA4, 0x01 }; ReadOnlySpan<byte> expected = stackalloc byte[] { 0xA4, 0x01 };
int read = stream.Read(actual); int read = stream.Read(actual);
Assert.AreEqual(2, read); Assert.That(read, Is.EqualTo(2));
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); 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; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
public partial class StreamTests internal partial class StreamTests
{ {
[TestMethod] [Test]
[CLSCompliant(false)] public void WriteBigEndian_ShouldThrowArgumentNullException_GivenNullStream_AndUInt32Argument()
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()
{ {
Stream stream = null!; Stream stream = null!;
Assert.ThrowsException<ArgumentNullException>(() => stream.Write(420U, Endianness.LittleEndian)); Assert.Throws<ArgumentNullException>(() => stream.WriteBigEndian(420U));
Assert.ThrowsException<ArgumentNullException>(() => stream.Write(420U, Endianness.BigEndian));
} }
[TestMethod] [Test]
[CLSCompliant(false)] [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void WriteUInt32_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() public void WriteBigEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndUInt32Argument()
{ {
// we don't need to enclose this stream in a using declaration, since disposing a Stream stream = new DummyStream();
// null stream is meaningless. NullStream.Dispose actually does nothing, anyway. Assert.Throws<ArgumentException>(() => stream.WriteBigEndian(420U));
// 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)));
} }
[TestMethod] [Test]
[CLSCompliant(false)] public void WriteLittleEndian_ShouldThrowArgumentNullException_GivenNullStream_AndUInt32Argument()
public void WriteUInt32_ShouldWriteBigEndian_GivenBigEndian() {
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(); using var stream = new MemoryStream();
stream.Write(420U, Endianness.BigEndian); stream.WriteBigEndian(420U);
Assert.AreEqual(4, stream.Position); Assert.That(stream.Position, Is.EqualTo(4));
stream.Position = 0; stream.Position = 0;
Span<byte> actual = stackalloc byte[4]; Span<byte> actual = stackalloc byte[4];
ReadOnlySpan<byte> expected = stackalloc byte[] { 0x00, 0x00, 0x01, 0xA4 }; ReadOnlySpan<byte> expected = stackalloc byte[] { 0x00, 0x00, 0x01, 0xA4 };
int read = stream.Read(actual); int read = stream.Read(actual);
Assert.AreEqual(4, read); Assert.That(read, Is.EqualTo(4));
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
} }
[TestMethod] [Test]
[CLSCompliant(false)] public void WriteLittleEndian_ShouldWriteLittleEndian_GivenUInt32Argument()
public void WriteUInt32_ShouldWriteLittleEndian_GivenLittleEndian()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
stream.Write(420U, Endianness.LittleEndian); stream.WriteLittleEndian(420U);
Assert.AreEqual(4, stream.Position); Assert.That(stream.Position, Is.EqualTo(4));
stream.Position = 0; stream.Position = 0;
Span<byte> actual = stackalloc byte[4]; Span<byte> actual = stackalloc byte[4];
ReadOnlySpan<byte> expected = stackalloc byte[] { 0xA4, 0x01, 0x00, 0x00 }; ReadOnlySpan<byte> expected = stackalloc byte[] { 0xA4, 0x01, 0x00, 0x00 };
int read = stream.Read(actual); int read = stream.Read(actual);
Assert.AreEqual(4, read); Assert.That(read, Is.EqualTo(4));
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); 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; using X10D.IO;
namespace X10D.Tests.IO; namespace X10D.Tests.IO;
public partial class StreamTests internal partial class StreamTests
{ {
[TestMethod] [Test]
[CLSCompliant(false)] public void WriteBigEndian_ShouldThrowArgumentNullException_GivenNullStream_AndUInt64Argument()
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()
{ {
Stream stream = null!; Stream stream = null!;
Assert.ThrowsException<ArgumentNullException>(() => stream.Write(420UL, Endianness.LittleEndian)); Assert.Throws<ArgumentNullException>(() => stream.WriteBigEndian(420UL));
Assert.ThrowsException<ArgumentNullException>(() => stream.Write(420UL, Endianness.BigEndian));
} }
[TestMethod] [Test]
[CLSCompliant(false)] [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope")]
public void WriteUInt64_ShouldThrowArgumentOutOfRangeException_GivenInvalidEndiannessValue() public void WriteBigEndian_ShouldThrowArgumentException_GivenNonWritableStream_AndUInt64Argument()
{ {
// we don't need to enclose this stream in a using declaration, since disposing a Stream stream = new DummyStream();
// null stream is meaningless. NullStream.Dispose actually does nothing, anyway. Assert.Throws<ArgumentException>(() => stream.WriteBigEndian(420UL));
// 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)));
} }
[TestMethod] [Test]
[CLSCompliant(false)] public void WriteLittleEndian_ShouldThrowArgumentNullException_GivenNullStream_AndUInt64Argument()
public void WriteUInt64_ShouldWriteBigEndian_GivenBigEndian() {
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(); using var stream = new MemoryStream();
stream.Write(420UL, Endianness.BigEndian); stream.WriteBigEndian(420UL);
Assert.AreEqual(8, stream.Position); Assert.That(stream.Position, Is.EqualTo(8));
stream.Position = 0; stream.Position = 0;
Span<byte> actual = stackalloc byte[8]; Span<byte> actual = stackalloc byte[8];
ReadOnlySpan<byte> expected = stackalloc byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xA4 }; ReadOnlySpan<byte> expected = stackalloc byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xA4 };
int read = stream.Read(actual); int read = stream.Read(actual);
Assert.AreEqual(8, read); Assert.That(read, Is.EqualTo(8));
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
} }
[TestMethod] [Test]
[CLSCompliant(false)] public void WriteLittleEndian_ShouldWriteLittleEndian_GivenUInt64Argument()
public void WriteUInt64_ShouldWriteLittleEndian_GivenLittleEndian()
{ {
using var stream = new MemoryStream(); using var stream = new MemoryStream();
stream.Write(420UL, Endianness.LittleEndian); stream.WriteLittleEndian(420UL);
Assert.AreEqual(8, stream.Position); Assert.That(stream.Position, Is.EqualTo(8));
stream.Position = 0; stream.Position = 0;
Span<byte> actual = stackalloc byte[8]; Span<byte> actual = stackalloc byte[8];
ReadOnlySpan<byte> expected = stackalloc byte[] { 0xA4, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; ReadOnlySpan<byte> expected = stackalloc byte[] { 0xA4, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
int read = stream.Read(actual); int read = stream.Read(actual);
Assert.AreEqual(8, read); Assert.That(read, Is.EqualTo(8));
CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray()); CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
} }
} }

View File

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

View File

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

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