From 713a31e136591127bdbc552594898d984e86eb13 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Maxime=20G=C3=A9linas?= Date: Wed, 11 Apr 2018 21:13:13 -0400 Subject: [PATCH 1/5] Implement and test `Guard` class --- .../GuardTests.cs | 47 +++++ .../SolidStack.Core.Guards.Tests.csproj | 25 +++ src/SolidStack.Core.Guards/Guard.cs | 174 ++++++++++++++++++ .../Internal/GuardClauseException.cs | 19 ++ .../SolidStack.Core.Guards.csproj | 11 ++ .../SolidStack.Core.Guards.nuspec | 20 ++ src/SolidStack.sln | 31 ++++ 7 files changed, 327 insertions(+) create mode 100644 src/SolidStack.Core.Guards.Tests/GuardTests.cs create mode 100644 src/SolidStack.Core.Guards.Tests/SolidStack.Core.Guards.Tests.csproj create mode 100644 src/SolidStack.Core.Guards/Guard.cs create mode 100644 src/SolidStack.Core.Guards/Internal/GuardClauseException.cs create mode 100644 src/SolidStack.Core.Guards/SolidStack.Core.Guards.csproj create mode 100644 src/SolidStack.Core.Guards/SolidStack.Core.Guards.nuspec create mode 100644 src/SolidStack.sln diff --git a/src/SolidStack.Core.Guards.Tests/GuardTests.cs b/src/SolidStack.Core.Guards.Tests/GuardTests.cs new file mode 100644 index 0000000..e3fbbf4 --- /dev/null +++ b/src/SolidStack.Core.Guards.Tests/GuardTests.cs @@ -0,0 +1,47 @@ +using System; +using System.Diagnostics.CodeAnalysis; +using FluentAssertions; +using SolidStack.Core.Guards; +using SolidStack.Core.Guards.Internal; +using Xunit; + +namespace SolidStack.Core.Tests.Guards +{ + public class GuardTests + { + [Fact] + public void Requires_WithMatchedPredicate_DoesntThrows() + { + Action act = () => Guard.Requires(() => true, "message"); + + act.Should().NotThrow(); + } + + [Fact] + public void Requires_WithUnmatchedPredicate_Throws() + { + Action act = () => Guard.Requires(() => false, "message"); + + act.Should().Throw(); + } + + [Fact] + public void RequiresNonNull_WithNonNull_DoesntThrows() + { + const string nonNull = ""; + Action act = () => Guard.RequiresNonNull(nonNull, "message"); + + act.Should().NotThrow(); + } + + [Fact] + [SuppressMessage("ReSharper", "ExpressionIsAlwaysNull")] + public void RequiresNonNull_WithNull_Throws() + { + string @null = null; + Action act = () => Guard.RequiresNonNull(@null, "message"); + + act.Should().Throw(); + } + } +} \ No newline at end of file diff --git a/src/SolidStack.Core.Guards.Tests/SolidStack.Core.Guards.Tests.csproj b/src/SolidStack.Core.Guards.Tests/SolidStack.Core.Guards.Tests.csproj new file mode 100644 index 0000000..5f47815 --- /dev/null +++ b/src/SolidStack.Core.Guards.Tests/SolidStack.Core.Guards.Tests.csproj @@ -0,0 +1,25 @@ + + + + netcoreapp2.0 + + false + + + + + + + + + + + + + + + + + + + diff --git a/src/SolidStack.Core.Guards/Guard.cs b/src/SolidStack.Core.Guards/Guard.cs new file mode 100644 index 0000000..179c169 --- /dev/null +++ b/src/SolidStack.Core.Guards/Guard.cs @@ -0,0 +1,174 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using SolidStack.Core.Guards.Internal; + +namespace SolidStack.Core.Guards +{ + /// + /// + /// Provides guard clauses that allow you to write pre-conditions and post-conditions for your methods in a + /// readable way. + /// + /// + /// + /// + /// + public static class Guard + { + /// + /// Checks for a method post-condition; if the condition is false, displays an error message. + /// + /// + /// The check will be performed in trigger mode only to avoid affecting performance. + /// + /// The condition to validate. + /// The error message to display. + [Conditional("DEBUG")] + public static void Ensures(Func predicate, string message) => + Debug.Assert(predicate(), message); + + /// + /// Checks for a method post-condition against all items in a sequence; if any condition is false, displays an error + /// message. + /// + /// + /// The check will be performed in "release" mode only to avoid affecting performance. + /// + /// The type of the sequence items. + /// The sequence to check. + /// The condition to validate. + /// The error message to display. + [Conditional("DEBUG")] + public static void EnsuresAll( + IEnumerable sequence, + Func predicate, string message) + { + foreach (var item in sequence) + Requires(() => predicate(item), message); + } + + /// + /// Checks for a method post-condition against all items in a sequence; if all conditions are false, displays an error + /// message. + /// + /// + /// The check will be performed in "release" mode only to avoid affecting performance. + /// + /// The type of the sequence items. + /// The sequence to check. + /// The condition to validate. + /// The error message to display. + [Conditional("DEBUG")] + public static void EnsuresAny( + IEnumerable sequence, + Func predicate, string message) => + Ensures(() => sequence.Any(predicate), message); + + /// + /// Checks if a value is null as a method post-condition; if the value is null, displays an error message. + /// + /// + /// The check will be performed in "release" mode only to avoid affecting performance. + /// + /// The type of the value to check. + /// The value to check. + /// The error message to display. + [Conditional("DEBUG")] + public static void EnsuresNonNull(T value, string message) => + Ensures(() => value != null, message); + + /// + /// Checks if a sequence contains null items as a method post-condition; if any item is null, displays an error + /// message. + /// + /// + /// The check will be performed in "release" mode only to avoid affecting performance. + /// + /// The type of the sequence items. + /// The sequence to check. + /// The error message to display. + [Conditional("DEBUG")] + public static void EnsuresNoNullIn(IEnumerable sequence, string message) => + EnsuresAll(sequence, item => item != null, message); + + /// + /// Checks for a method pre-condition; if the condition is false, displays an error message. + /// + /// + /// The check will be performed in trigger mode only to avoid affecting performance. + /// + /// The condition to validate. + /// The error message to display. + /// + public static void Requires(Func predicate, string message) + { + if (predicate()) + return; + + Debug.Fail(message); + throw new GuardClauseException(message); + } + + /// + /// Checks for a method pre-condition against all items in a sequence; if any condition is false, displays an error + /// message. + /// + /// + /// The check will be performed in "release" mode only to avoid affecting performance. + /// + /// The type of the sequence items. + /// The sequence to check. + /// The condition to validate. + /// The error message to display. + [Conditional("DEBUG")] + public static void RequiresAll( + IEnumerable sequence, + Func predicate, string message) + { + foreach (var item in sequence) + Requires(() => predicate(item), message); + } + + /// + /// Checks for a method pre-condition against all items in a sequence; if all conditions are false, displays an error + /// message. + /// + /// + /// The check will be performed in "release" mode only to avoid affecting performance. + /// + /// The type of the sequence items. + /// The sequence to check. + /// The condition to validate. + /// The error message to display. + [Conditional("DEBUG")] + public static void RequiresAny( + IEnumerable sequence, + Func predicate, string message) => + Requires(() => sequence.Any(predicate), message); + + /// + /// Checks if a value is null as a method post-condition; if the value is null, displays an error message. + /// + /// The type of the value to check. + /// The value to check. + /// The variable name of the value to check. + public static void RequiresNonNull(T value, string variableName) => + Requires(() => value != null, $"Receiving null {variableName}."); + + /// + /// Checks if a sequence contains null items as a method pre-condition; if any item is null, displays an error message. + /// + /// + /// The check will be performed in "release" mode only to avoid affecting performance. + /// + /// The type of the sequence items. + /// The sequence to check. + /// The variable of the sequence to check. + [Conditional("DEBUG")] + public static void RequiresNoNullIn(IEnumerable sequence, string variableName) => + RequiresAll(sequence, item => item != null, $"Receiving {variableName} containing one or more null items."); + } +} \ No newline at end of file diff --git a/src/SolidStack.Core.Guards/Internal/GuardClauseException.cs b/src/SolidStack.Core.Guards/Internal/GuardClauseException.cs new file mode 100644 index 0000000..791a04a --- /dev/null +++ b/src/SolidStack.Core.Guards/Internal/GuardClauseException.cs @@ -0,0 +1,19 @@ +using System; + +namespace SolidStack.Core.Guards.Internal +{ + /// + /// + /// The exception that is thrown when the guard clause (i.e. pre-condition / post-condition) of a method isn't respected. + /// + /// + /// That kind of exception should never be catch. + /// + public class GuardClauseException : Exception + { + public GuardClauseException(string message) : + base(message) + { + } + } +} \ No newline at end of file diff --git a/src/SolidStack.Core.Guards/SolidStack.Core.Guards.csproj b/src/SolidStack.Core.Guards/SolidStack.Core.Guards.csproj new file mode 100644 index 0000000..35ac886 --- /dev/null +++ b/src/SolidStack.Core.Guards/SolidStack.Core.Guards.csproj @@ -0,0 +1,11 @@ + + + + netstandard2.0 + + + + + + + diff --git a/src/SolidStack.Core.Guards/SolidStack.Core.Guards.nuspec b/src/SolidStack.Core.Guards/SolidStack.Core.Guards.nuspec new file mode 100644 index 0000000..25690cf --- /dev/null +++ b/src/SolidStack.Core.Guards/SolidStack.Core.Guards.nuspec @@ -0,0 +1,20 @@ + + + + SolidStack.Core.Guards + $version$ + SolidStack.Core.Guards is an extremely simple, unambiguous and lightweight guard clause library. + $authors$ + SolidStack + $projectUrl$ + $licenseUrl$ + $iconUrl$ + $requireLicenseAcceptance$ + + $copyright$ + SolidStack Core Guard Clause + + + + + \ No newline at end of file diff --git a/src/SolidStack.sln b/src/SolidStack.sln new file mode 100644 index 0000000..284ed4f --- /dev/null +++ b/src/SolidStack.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27130.2024 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SolidStack.Core.Guards", "SolidStack.Core.Guards\SolidStack.Core.Guards.csproj", "{0C7E071B-021D-48F3-9306-A10B38A034D8}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SolidStack.Core.Guards.Tests", "SolidStack.Core.Guards.Tests\SolidStack.Core.Guards.Tests.csproj", "{3F4308F7-20C6-4E5E-BB94-8681BEEF3E3A}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {0C7E071B-021D-48F3-9306-A10B38A034D8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0C7E071B-021D-48F3-9306-A10B38A034D8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0C7E071B-021D-48F3-9306-A10B38A034D8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0C7E071B-021D-48F3-9306-A10B38A034D8}.Release|Any CPU.Build.0 = Release|Any CPU + {3F4308F7-20C6-4E5E-BB94-8681BEEF3E3A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3F4308F7-20C6-4E5E-BB94-8681BEEF3E3A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3F4308F7-20C6-4E5E-BB94-8681BEEF3E3A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3F4308F7-20C6-4E5E-BB94-8681BEEF3E3A}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {A31C7CBE-244A-4FA0-9D34-B202D205602E} + EndGlobalSection +EndGlobal From b3fce4c4f19886ed3e70cb4737855bd0491c31b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Maxime=20G=C3=A9linas?= Date: Wed, 11 Apr 2018 21:52:34 -0400 Subject: [PATCH 2/5] Fix `.travis.yml` --- .travis.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.travis.yml b/.travis.yml index 475e410..fa2d10d 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,7 @@ language: csharp mono: none -dotnet: 2.0.0 +dotnet: $DOTNET_VERSION script: - dotnet restore ./src - - dotnet build ./**/*.csproj --configuration Release - - dotnet test ./**/*Tests*.csproj \ No newline at end of file + - dotnet build ./src/SolidStack.Core.Guards/SolidStack.Core.Guards.csproj --configuration $CONFIGURATION + - dotnet test ./src/SolidStack.Core.Guards/SolidStack.Core.Guards.csproj --configuration $CONFIGURATION \ No newline at end of file From 6ecb580bf0d5677f27ef6ef1ac30ebf07ad8f67e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Maxime=20G=C3=A9linas?= Date: Wed, 11 Apr 2018 22:08:29 -0400 Subject: [PATCH 3/5] Fix `.travis.yml` and update `README.md` --- .travis.yml | 2 +- README.md | 106 +++++++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 106 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index fa2d10d..fc50dc5 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,6 @@ language: csharp mono: none -dotnet: $DOTNET_VERSION +dotnet: 2.0.0 script: - dotnet restore ./src - dotnet build ./src/SolidStack.Core.Guards/SolidStack.Core.Guards.csproj --configuration $CONFIGURATION diff --git a/README.md b/README.md index 924046e..321f988 100644 --- a/README.md +++ b/README.md @@ -1 +1,105 @@ -solidstack +

SolidStack

+ +
+ +**Quick links**: +[Docs][docs-url], +[Changelog][changelog-url], +[Nuget][nuget-packages-url] + +[![Build status][build-status-badge]][build-url] +[![GitHub release][github-release-badge]][license-url] +[![MIT license][license-badge]][license-url] + +
+ +# What is SolidStack? + +SolidStack is a .NET framework consisting of several well-divided NuGet packages that allow you to focus on business logic by providing an implementation of very general design patterns useful in every kind of applications such as the [*Option Pattern*][option-pattern-url], the [*Builder Pattern*][builder-pattern-url], the [*Repository Pattern*][repository-pattern-url], the [*Unit of Work Pattern*][unit-of-work-pattern-url] and so more. In short, if you're tired of duplicated and unreadable code, this framework if for you! + +## Available NuGet packages + +### SolidStack.Core + +The `SolidStack.Core` namespace is the central point of all SolidStack packages, providing very generic concepts that are useful in any type of program, such as object construction, object equality, code flow and more. + +Package | Description +------- | ----------- +[SolidStack.Core.Guards][solidstack.core.guards-page] | `SolidStack.Guards` is an extremely simple, unambiguous and lightweight [guard clause][guard-clauses-url] library. +SolidStack.Core.Flow (in progress...) | `SolidStack.Core.Flow` focuses on encapsulating the branching logic of your code so you can write a linear and much more readable code flow without having to deal with exceptions, null checks and unnecessary conditions. +SolidStack.Core.Equality (coming soon...) | `SolidStack.Core.Equality` is primarily useful when you have to tweak the equality of an object to implement the [*Value Object Pattern*][value-object-pattern-url]. All you have to do is use one of the provided abstract classes and the complex equality logic will be done for you. +SolidStack.Core.Construction (coming soon...) | `SolidStack.Core.Construction`'s only responsibility is to help you construct objects. You can use the [*Builder Pattern*][builder-pattern-url] provided implementation to build complex objects in a fluent way. + +### SolidStack.Domain (coming soon...) + +The `SolidStack.Domain` namespace make it easier when it's time to implement business logic by providing a strong basic implementation of the [domain-driven design][ddd-url] philosophy. + +### SolidStack.Infrastructure (coming soon...) + +The `SolidStack.Infrastructure` namespace provides a general implementation of many features that are not releated to business logic like memory deallocation, time, encryption, serialization and so on. + +### SolidStack.Persistence (coming soon...) + +The `SolidStack.Testing` namespace abstracts how the data is stored so that you can simply switch the way your application stores your data to almost everything such as a SQL database, a NoSQL database, local files, in memory and many more without affecting the rest of your application. + +### SolidStack.Testing (coming soon...) + +The `SolidStack.Testing` namespace provide classes to help you build highly reusable and readable tests so you can simply write tests on a given interface once and then validate each concrete type of that interface with those same tests. + +# How do I get started? + +Check out our [wiki][docs-url] to explore the documentation provided for the packages you want. There is documentation on each package available! + +# Where can I get it? + +First, [install NuGet][nuget-install-url]. Then, install the required NuGet packages avalaible on [nuget.org][nuget-idmobiles-url] using the package manager console: + +``` +PM> Install-Package +``` + +# I have an issue... + +First, you can check if your issue has already been tracked [here][issues-url]. + +Otherwise, you can check if it's already fixed by pulling the [develop branch][develop-branch-url], building the solution and then using the generated DLL files direcly in your project. + +If you still hit a problem, please document it and post it [here][new-issue-url]. + +# How can I contribute? + +Contributors are greatly appreciated, just follow the following steps: + +1. **Fork** the repository +2. **Clone** the project to your own machine +3. **Commit** changes to your own branch +4. **Push** your work back up to your fork +5. **Create a pull request** containing a description and your work and what is the motivation behind it +6. **Submit your pull request** so that we can review your changes + +# License + +SolidStack is Copyright © 2018 SoftFrame under the [MIT license][license-url]. + + +[builder-pattern-url]: http://www.codinghelmet.com/?path=howto/advances-in-applying-the-builder-design-pattern +[build-status-badge]: https://img.shields.io/travis/softframe/solidstack.svg?style=flat-square +[build-url]: https://idmobiles.visualstudio.com/solidstack/_build/index?definitionId=10 +[changelog-url]: https://github.com/idmobiles/solidstack/releases +[develop-branch-url]: https://github.com/idmobiles/solidstack/tree/develop +[docs-url]: https://github.com/idmobiles/solidstack/wiki +[ddd-url]: https://en.wikipedia.org/wiki/Domain-driven_design +[github-release-badge]: https://img.shields.io/github/release/idmobiles/solidstack.svg?style=flat-square +[issues-url]: https://github.com/idmobiles/solidstack/issues +[github-release-url]: https://github.com/idmobiles/solidstack/releases +[guard-clauses-url]: https://medium.com/softframe/what-are-guard-clauses-and-how-to-use-them-350c8f1b6fd2 +[license-badge]: https://img.shields.io/badge/license-MIT-orange.svg?style=flat-square +[license-url]: https://github.com/idmobiles/solidstack/blob/master/LICENSE +[new-issue-url]: https://github.com/idmobiles/solidstack/issues/new +[nuget-packages-url]: https://www.nuget.org/profiles/softframe +[nuget-install-url]: http://docs.nuget.org/docs/start-here/installing-nuget +[option-pattern-url]: http://www.codinghelmet.com/?path=howto/understanding-the-option-maybe-functional-type +[repository-pattern-url]: https://martinfowler.com/eaaCatalog/repository.html +[solidstack.core.guards-page]: https://www.nuget.org/packages/SolidStack.Core +[unit-of-work-pattern-url]: https://martinfowler.com/eaaCatalog/unitOfWork.html +[value-object-pattern-url]: https://martinfowler.com/bliki/ValueObject.html \ No newline at end of file From 6ee11e3a521087079eb5ba597ed61af31d546144 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Maxime=20G=C3=A9linas?= Date: Thu, 12 Apr 2018 21:11:15 -0400 Subject: [PATCH 4/5] Update `README.md` --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 321f988..aeb6b22 100644 --- a/README.md +++ b/README.md @@ -25,14 +25,14 @@ The `SolidStack.Core` namespace is the central point of all SolidStack packages, Package | Description ------- | ----------- -[SolidStack.Core.Guards][solidstack.core.guards-page] | `SolidStack.Guards` is an extremely simple, unambiguous and lightweight [guard clause][guard-clauses-url] library. +[SolidStack.Core.Guards][solidstack.core.guards-page] | `SolidStack.Core.Guards` is an extremely simple, unambiguous and lightweight [*guard clause*][guard-clauses-url] library. SolidStack.Core.Flow (in progress...) | `SolidStack.Core.Flow` focuses on encapsulating the branching logic of your code so you can write a linear and much more readable code flow without having to deal with exceptions, null checks and unnecessary conditions. SolidStack.Core.Equality (coming soon...) | `SolidStack.Core.Equality` is primarily useful when you have to tweak the equality of an object to implement the [*Value Object Pattern*][value-object-pattern-url]. All you have to do is use one of the provided abstract classes and the complex equality logic will be done for you. SolidStack.Core.Construction (coming soon...) | `SolidStack.Core.Construction`'s only responsibility is to help you construct objects. You can use the [*Builder Pattern*][builder-pattern-url] provided implementation to build complex objects in a fluent way. ### SolidStack.Domain (coming soon...) -The `SolidStack.Domain` namespace make it easier when it's time to implement business logic by providing a strong basic implementation of the [domain-driven design][ddd-url] philosophy. +The `SolidStack.Domain` namespace make it easier when it's time to implement business logic by providing a strong basic implementation of the [*domain-driven design*][ddd-url] philosophy. ### SolidStack.Infrastructure (coming soon...) From 0804b3d472f5dd49aea0c9d31707092acf7a98c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Maxime=20G=C3=A9linas?= Date: Thu, 12 Apr 2018 21:12:32 -0400 Subject: [PATCH 5/5] Remove `Debug.Assert` usage and cover all tests --- .travis.yml | 4 +- .../GuardTests.cs | 162 +++++++++++++++++- .../SolidStack.Core.Guards.Tests.csproj | 8 +- src/SolidStack.Core.Guards/Guard.cs | 34 ++-- .../DebugOnlyFactAttribute.cs | 11 ++ .../DebugOnlyTheoryAttribute.cs | 11 ++ .../Internal/FactSkipper.cs | 17 ++ .../SolidStack.Testing.Xunit.csproj | 11 ++ src/SolidStack.sln | 8 +- 9 files changed, 233 insertions(+), 33 deletions(-) create mode 100644 src/SolidStack.Testing.Xunit/DebugOnlyFactAttribute.cs create mode 100644 src/SolidStack.Testing.Xunit/DebugOnlyTheoryAttribute.cs create mode 100644 src/SolidStack.Testing.Xunit/Internal/FactSkipper.cs create mode 100644 src/SolidStack.Testing.Xunit/SolidStack.Testing.Xunit.csproj diff --git a/.travis.yml b/.travis.yml index fc50dc5..e89574e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,6 +2,4 @@ language: csharp mono: none dotnet: 2.0.0 script: - - dotnet restore ./src - - dotnet build ./src/SolidStack.Core.Guards/SolidStack.Core.Guards.csproj --configuration $CONFIGURATION - - dotnet test ./src/SolidStack.Core.Guards/SolidStack.Core.Guards.csproj --configuration $CONFIGURATION \ No newline at end of file + - dotnet test ./src/SolidStack.Core.Guards.Tests/SolidStack.Core.Guards.Tests.csproj \ No newline at end of file diff --git a/src/SolidStack.Core.Guards.Tests/GuardTests.cs b/src/SolidStack.Core.Guards.Tests/GuardTests.cs index e3fbbf4..0d21547 100644 --- a/src/SolidStack.Core.Guards.Tests/GuardTests.cs +++ b/src/SolidStack.Core.Guards.Tests/GuardTests.cs @@ -1,18 +1,111 @@ using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using FluentAssertions; -using SolidStack.Core.Guards; using SolidStack.Core.Guards.Internal; +using SolidStack.Testing.Xunit; using Xunit; -namespace SolidStack.Core.Tests.Guards +namespace SolidStack.Core.Guards.Tests { public class GuardTests { + [Fact] + public void Ensures_WithMatchedPredicate_DoesntThrows() + { + Action act = () => Guard.Ensures(() => true, "error"); + + act.Should().NotThrow(); + } + + [DebugOnlyFact] + public void Ensures_WithUnmatchedPredicateInDebug_Throws() + { + Action act = () => Guard.Ensures(() => false, "error"); + + act.Should().Throw(); + } + + [Theory] + [InlineData(new[] { 0, 4, 6, 10 })] + public void EnsuresAll_WithMatchedPredicates_DoesntThrows(IEnumerable sequence) + { + Action act = () => Guard.EnsuresAll(sequence, n => n >= 0, "error"); + + act.Should().NotThrow(); + } + + [DebugOnlyTheory] + [InlineData(new[] { -4, 0, 6, 10 })] + [InlineData(new[] { -2, -3, -5, -3 })] + public void EnsuresAll_WithUnmatchedPredicatesInDebug_Throws(IEnumerable sequence) + { + Action act = () => Guard.EnsuresAll(sequence, n => n >= 0, "error"); + + act.Should().Throw(); + } + + [Theory] + [InlineData(new[] { 0, 4, 6, 10 })] + [InlineData(new[] { -2, -3, 5, -3 })] + [InlineData(new[] { -2, 0, -7, -5 })] + public void EnsuresAny_WithMatchedPredicates_DoesntThrows(IEnumerable sequence) + { + Action act = () => Guard.EnsuresAny(sequence, n => n >= 0, "error"); + + act.Should().NotThrow(); + } + + [DebugOnlyTheory] + [InlineData(new[] { -2, -3, -5, -3 })] + public void EnsuresAny_WithUnmatchedPredicatesInDebug_Throws(IEnumerable sequence) + { + Action act = () => Guard.EnsuresAny(sequence, n => n >= 0, "error"); + + act.Should().Throw(); + } + + [Fact] + public void EnsuresNonNull_WithNonNull_DoesntThrows() + { + const string nonNull = ""; + Action act = () => Guard.EnsuresNonNull(nonNull, "error"); + + act.Should().NotThrow(); + } + + [DebugOnlyFact] + [SuppressMessage("ReSharper", "ExpressionIsAlwaysNull")] + public void EnsuresNonNull_WithNullInDebug_Throws() + { + string @null = null; + Action act = () => Guard.EnsuresNonNull(@null, "error"); + + act.Should().Throw(); + } + + [Fact] + public void EnsuresNoNullIn_WithNoNull_DoesntThrows() + { + var sequence = new[] { "foo", "bar", "baz" }; + Action act = () => Guard.EnsuresNoNullIn(sequence, "error"); + + act.Should().NotThrow(); + } + + [DebugOnlyFact] + public void EnsuresNoNullIn_WithNullsInDebug_Throws() + { + var sequence = new[] { "foo", null, "baz" }; + Action act = () => Guard.EnsuresNoNullIn(sequence, "error"); + + act.Should().Throw(); + } + [Fact] public void Requires_WithMatchedPredicate_DoesntThrows() { - Action act = () => Guard.Requires(() => true, "message"); + Action act = () => Guard.Requires(() => true, "error"); act.Should().NotThrow(); } @@ -20,7 +113,46 @@ public void Requires_WithMatchedPredicate_DoesntThrows() [Fact] public void Requires_WithUnmatchedPredicate_Throws() { - Action act = () => Guard.Requires(() => false, "message"); + Action act = () => Guard.Requires(() => false, "error"); + + act.Should().Throw(); + } + + [Theory] + [InlineData(new[] { 0, 4, 6, 10 })] + public void RequiresAll_WithMatchedPredicates_DoesntThrows(IEnumerable sequence) + { + Action act = () => Guard.RequiresAll(sequence, n => n >= 0, "error"); + + act.Should().NotThrow(); + } + + [DebugOnlyTheory] + [InlineData(new[] { -4, 0, 6, 10 })] + [InlineData(new[] { -2, -3, -5, -3 })] + public void RequiresAll_WithUnmatchedPredicates_Throws(IEnumerable sequence) + { + Action act = () => Guard.RequiresAll(sequence, n => n >= 0, "error"); + + act.Should().Throw(); + } + + [Theory] + [InlineData(new[] { 0, 4, 6, 10 })] + [InlineData(new[] { -2, -3, 5, -3 })] + [InlineData(new[] { -2, 0, -7, -5 })] + public void RequiresAny_WithMatchedPredicates_DoesntThrows(IEnumerable sequence) + { + Action act = () => Guard.RequiresAny(sequence, n => n >= 0, "error"); + + act.Should().NotThrow(); + } + + [DebugOnlyTheory] + [InlineData(new[] { -2, -3, -5, -3 })] + public void RequiresAny_WithUnmatchedPredicates_Throws(IEnumerable sequence) + { + Action act = () => Guard.RequiresAny(sequence, n => n >= 0, "error"); act.Should().Throw(); } @@ -29,7 +161,7 @@ public void Requires_WithUnmatchedPredicate_Throws() public void RequiresNonNull_WithNonNull_DoesntThrows() { const string nonNull = ""; - Action act = () => Guard.RequiresNonNull(nonNull, "message"); + Action act = () => Guard.RequiresNonNull(nonNull, "error"); act.Should().NotThrow(); } @@ -39,7 +171,25 @@ public void RequiresNonNull_WithNonNull_DoesntThrows() public void RequiresNonNull_WithNull_Throws() { string @null = null; - Action act = () => Guard.RequiresNonNull(@null, "message"); + Action act = () => Guard.RequiresNonNull(@null, "error"); + + act.Should().Throw(); + } + + [Fact] + public void RequiresNoNullIn_WithNoNull_DoesntThrows() + { + var sequence = new[] { "foo", "bar", "baz" }; + Action act = () => Guard.RequiresNoNullIn(sequence, "error"); + + act.Should().NotThrow(); + } + + [DebugOnlyFact] + public void RequiresNoNullIn_WithNulls_Throws() + { + var sequence = new[] { "foo", null, "baz" }; + Action act = () => Guard.RequiresNoNullIn(sequence, "error"); act.Should().Throw(); } diff --git a/src/SolidStack.Core.Guards.Tests/SolidStack.Core.Guards.Tests.csproj b/src/SolidStack.Core.Guards.Tests/SolidStack.Core.Guards.Tests.csproj index 5f47815..003e166 100644 --- a/src/SolidStack.Core.Guards.Tests/SolidStack.Core.Guards.Tests.csproj +++ b/src/SolidStack.Core.Guards.Tests/SolidStack.Core.Guards.Tests.csproj @@ -8,14 +8,14 @@ - - - - + + + + diff --git a/src/SolidStack.Core.Guards/Guard.cs b/src/SolidStack.Core.Guards/Guard.cs index 179c169..310d811 100644 --- a/src/SolidStack.Core.Guards/Guard.cs +++ b/src/SolidStack.Core.Guards/Guard.cs @@ -28,7 +28,7 @@ public static class Guard /// The error message to display. [Conditional("DEBUG")] public static void Ensures(Func predicate, string message) => - Debug.Assert(predicate(), message); + Assert(predicate, message); /// /// Checks for a method post-condition against all items in a sequence; if any condition is false, displays an error @@ -44,11 +44,8 @@ public static void Ensures(Func predicate, string message) => [Conditional("DEBUG")] public static void EnsuresAll( IEnumerable sequence, - Func predicate, string message) - { - foreach (var item in sequence) - Requires(() => predicate(item), message); - } + Func predicate, string message) => + Assert(() => sequence.All(predicate), message); /// /// Checks for a method post-condition against all items in a sequence; if all conditions are false, displays an error @@ -103,14 +100,8 @@ public static void EnsuresNoNullIn(IEnumerable sequence, string message) = /// The condition to validate. /// The error message to display. /// - public static void Requires(Func predicate, string message) - { - if (predicate()) - return; - - Debug.Fail(message); - throw new GuardClauseException(message); - } + public static void Requires(Func predicate, string message) => + Assert(predicate, message); /// /// Checks for a method pre-condition against all items in a sequence; if any condition is false, displays an error @@ -126,11 +117,8 @@ public static void Requires(Func predicate, string message) [Conditional("DEBUG")] public static void RequiresAll( IEnumerable sequence, - Func predicate, string message) - { - foreach (var item in sequence) - Requires(() => predicate(item), message); - } + Func predicate, string message) => + Assert(() => sequence.All(predicate), message); /// /// Checks for a method pre-condition against all items in a sequence; if all conditions are false, displays an error @@ -170,5 +158,13 @@ public static void RequiresNonNull(T value, string variableName) => [Conditional("DEBUG")] public static void RequiresNoNullIn(IEnumerable sequence, string variableName) => RequiresAll(sequence, item => item != null, $"Receiving {variableName} containing one or more null items."); + + private static void Assert(Func predicate, string message) + { + if (predicate()) + return; + + throw new GuardClauseException(message); + } } } \ No newline at end of file diff --git a/src/SolidStack.Testing.Xunit/DebugOnlyFactAttribute.cs b/src/SolidStack.Testing.Xunit/DebugOnlyFactAttribute.cs new file mode 100644 index 0000000..4d7e55a --- /dev/null +++ b/src/SolidStack.Testing.Xunit/DebugOnlyFactAttribute.cs @@ -0,0 +1,11 @@ +using SolidStack.Testing.Xunit.Internal; +using Xunit; + +namespace SolidStack.Testing.Xunit +{ + public class DebugOnlyFactAttribute : FactAttribute + { + public DebugOnlyFactAttribute() => + FactSkipper.SkipInRelease(this); + } +} diff --git a/src/SolidStack.Testing.Xunit/DebugOnlyTheoryAttribute.cs b/src/SolidStack.Testing.Xunit/DebugOnlyTheoryAttribute.cs new file mode 100644 index 0000000..f571495 --- /dev/null +++ b/src/SolidStack.Testing.Xunit/DebugOnlyTheoryAttribute.cs @@ -0,0 +1,11 @@ +using SolidStack.Testing.Xunit.Internal; +using Xunit; + +namespace SolidStack.Testing.Xunit +{ + public class DebugOnlyTheoryAttribute : TheoryAttribute + { + public DebugOnlyTheoryAttribute() => + FactSkipper.SkipInRelease(this); + } +} diff --git a/src/SolidStack.Testing.Xunit/Internal/FactSkipper.cs b/src/SolidStack.Testing.Xunit/Internal/FactSkipper.cs new file mode 100644 index 0000000..858f6ea --- /dev/null +++ b/src/SolidStack.Testing.Xunit/Internal/FactSkipper.cs @@ -0,0 +1,17 @@ +using Xunit; + +namespace SolidStack.Testing.Xunit.Internal +{ + internal static class FactSkipper + { + public static void SkipInRelease(FactAttribute fact) => + SkipInRelease(fact, "Only running in debug mode."); + + public static void SkipInRelease(FactAttribute fact, string message) + { + #if !DEBUG + fact.Skip = message; + #endif + } + } +} diff --git a/src/SolidStack.Testing.Xunit/SolidStack.Testing.Xunit.csproj b/src/SolidStack.Testing.Xunit/SolidStack.Testing.Xunit.csproj new file mode 100644 index 0000000..c9d7e58 --- /dev/null +++ b/src/SolidStack.Testing.Xunit/SolidStack.Testing.Xunit.csproj @@ -0,0 +1,11 @@ + + + + netstandard2.0 + + + + + + + diff --git a/src/SolidStack.sln b/src/SolidStack.sln index 284ed4f..ca323ae 100644 --- a/src/SolidStack.sln +++ b/src/SolidStack.sln @@ -5,7 +5,9 @@ VisualStudioVersion = 15.0.27130.2024 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SolidStack.Core.Guards", "SolidStack.Core.Guards\SolidStack.Core.Guards.csproj", "{0C7E071B-021D-48F3-9306-A10B38A034D8}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SolidStack.Core.Guards.Tests", "SolidStack.Core.Guards.Tests\SolidStack.Core.Guards.Tests.csproj", "{3F4308F7-20C6-4E5E-BB94-8681BEEF3E3A}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SolidStack.Core.Guards.Tests", "SolidStack.Core.Guards.Tests\SolidStack.Core.Guards.Tests.csproj", "{3F4308F7-20C6-4E5E-BB94-8681BEEF3E3A}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SolidStack.Testing.Xunit", "SolidStack.Testing.Xunit\SolidStack.Testing.Xunit.csproj", "{5AE73D94-930C-4AA3-AA1D-704B9B28FB5C}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -21,6 +23,10 @@ Global {3F4308F7-20C6-4E5E-BB94-8681BEEF3E3A}.Debug|Any CPU.Build.0 = Debug|Any CPU {3F4308F7-20C6-4E5E-BB94-8681BEEF3E3A}.Release|Any CPU.ActiveCfg = Release|Any CPU {3F4308F7-20C6-4E5E-BB94-8681BEEF3E3A}.Release|Any CPU.Build.0 = Release|Any CPU + {5AE73D94-930C-4AA3-AA1D-704B9B28FB5C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5AE73D94-930C-4AA3-AA1D-704B9B28FB5C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5AE73D94-930C-4AA3-AA1D-704B9B28FB5C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5AE73D94-930C-4AA3-AA1D-704B9B28FB5C}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE