diff --git a/sample/ConsoleApp/CustomError/ApplicationError.cs b/sample/ConsoleApp/CustomError/ApplicationError.cs index 42ba3c3..509f7e3 100644 --- a/sample/ConsoleApp/CustomError/ApplicationError.cs +++ b/sample/ConsoleApp/CustomError/ApplicationError.cs @@ -2,40 +2,40 @@ namespace Sample.CustomError; -public abstract class ApplicationError: LogicError +public abstract class ApplicationError : LogicError { - - public int ErrorCode { get; } - - protected ApplicationError(string message, int errorCode) - : base(message) - { - ErrorCode = errorCode; - } + + public int ErrorCode { get; } + + protected ApplicationError(string message, int errorCode) + : base(message) + { + ErrorCode = errorCode; + } } public class NotFoundError : ApplicationError { - - public string ResourceName { get; } - public string ResourceId { get; } - public NotFoundError(string message, int errorCode, string resourceName, string resourceId) - : base(message, errorCode) - { - ResourceName = resourceName; - ResourceId = resourceId; - } + + public string ResourceName { get; } + public string ResourceId { get; } + public NotFoundError(string message, int errorCode, string resourceName, string resourceId) + : base(message, errorCode) + { + ResourceName = resourceName; + ResourceId = resourceId; + } } public class InvalidOperationError : ApplicationError { - - public string OperationName { get; } - public string Reason { get; } - public InvalidOperationError(string message, int errorCode, string operationName, string reason) - : base(message, errorCode) - { - OperationName = operationName; - Reason = reason; - } + + public string OperationName { get; } + public string Reason { get; } + public InvalidOperationError(string message, int errorCode, string operationName, string reason) + : base(message, errorCode) + { + OperationName = operationName; + Reason = reason; + } } \ No newline at end of file diff --git a/sample/ConsoleApp/Models/BookExtensions.cs b/sample/ConsoleApp/Models/BookExtensions.cs index 829c14d..2b24a1a 100644 --- a/sample/ConsoleApp/Models/BookExtensions.cs +++ b/sample/ConsoleApp/Models/BookExtensions.cs @@ -2,9 +2,9 @@ namespace Sample.Models; public static class BookExtensions { - public static string GetPrintableTitle(this Book book) - => book - .Author - .Map(author => $"{book.Title} by {author.GetFullName()}") - .GetValue(() => book.Title); + public static string GetPrintableTitle(this Book book) + => book + .Author + .Map(author => $"{book.Title} by {author.GetFullName()}") + .GetValue(() => book.Title); } \ No newline at end of file diff --git a/sample/ConsoleApp/Models/PersonExtensions.cs b/sample/ConsoleApp/Models/PersonExtensions.cs index d7ab22c..74006f9 100644 --- a/sample/ConsoleApp/Models/PersonExtensions.cs +++ b/sample/ConsoleApp/Models/PersonExtensions.cs @@ -2,9 +2,9 @@ namespace Sample.Models; public static class PersonExtensions { - public static string GetFullName(this Person person) - => person - .Surname - .Map(surname => $"{person.Name} {surname}") - .GetValue(() => person.Name); + public static string GetFullName(this Person person) + => person + .Surname + .Map(surname => $"{person.Name} {surname}") + .GetValue(() => person.Name); } \ No newline at end of file diff --git a/sample/ConsoleApp/Pipelines/CreateUserPipeline.cs b/sample/ConsoleApp/Pipelines/CreateUserPipeline.cs index b2ca306..9b8f388 100644 --- a/sample/ConsoleApp/Pipelines/CreateUserPipeline.cs +++ b/sample/ConsoleApp/Pipelines/CreateUserPipeline.cs @@ -4,48 +4,48 @@ namespace Sample.Pipelines; public static class CreateUserPipeline { - private const string DEMO_USER = "username@sample.com"; - // Models - private record Username(string Value); - private record User(Username Username, string FirstName, string LastName); - public static void Run(string? username = null!) - { - username ??= DEMO_USER; - Console.WriteLine($"Creating user '{username}'"); - var outcome = CreateUsername(username) - .Ensure(u => LookupUser(u).IsNone, new LogicError("User already exists")) - .Map(u => new User(u, "FirstName", "LastName")) - .Bind(CreateUser) - .ExecuteIfSuccess(NotifyCreation) - .Match(u => "User created.", e => $"The following error occurred: {e.Message}"); - - // In a real example the final Match would return a specific model, for example, an IActionResult - // or an IResult (Http) in case of AspNet Web Api. - - Console.WriteLine(outcome); - } + private const string DEMO_USER = "username@sample.com"; + // Models + private record Username(string Value); + private record User(Username Username, string FirstName, string LastName); + public static void Run(string? username = null!) + { + username ??= DEMO_USER; + Console.WriteLine($"Creating user '{username}'"); + var outcome = CreateUsername(username) + .Ensure(u => LookupUser(u).IsNone, new LogicError("User already exists")) + .Map(u => new User(u, "FirstName", "LastName")) + .Bind(CreateUser) + .ExecuteIfSuccess(NotifyCreation) + .Match(u => "User created.", e => $"The following error occurred: {e.Message}"); - private static Result CreateUsername(string username) - { - if (!username.Contains('@')) - return Result.Failure("Username must contain at least one '@'"); - return Result.Success(new Username(username)); - } + // In a real example the final Match would return a specific model, for example, an IActionResult + // or an IResult (Http) in case of AspNet Web Api. - private static Maybe LookupUser(Username username) - { - if (username.Value == DEMO_USER) - return new User(username, "FirstName", "LastName"); - return Maybe.None(); - } + Console.WriteLine(outcome); + } - private static Result CreateUser(User user) - { - if (false) return Result.Failure("Error creating user"); - return new(user); - } - private static void NotifyCreation(User user) - { - Console.WriteLine(" >>> User has been notified!"); - } + private static Result CreateUsername(string username) + { + if (!username.Contains('@')) + return Result.Failure("Username must contain at least one '@'"); + return Result.Success(new Username(username)); + } + + private static Maybe LookupUser(Username username) + { + if (username.Value == DEMO_USER) + return new User(username, "FirstName", "LastName"); + return Maybe.None(); + } + + private static Result CreateUser(User user) + { + if (false) return Result.Failure("Error creating user"); + return new(user); + } + private static void NotifyCreation(User user) + { + Console.WriteLine(" >>> User has been notified!"); + } } \ No newline at end of file diff --git a/sample/ConsoleApp/Pipelines/GamblingPipeline.cs b/sample/ConsoleApp/Pipelines/GamblingPipeline.cs index a428825..efd5331 100644 --- a/sample/ConsoleApp/Pipelines/GamblingPipeline.cs +++ b/sample/ConsoleApp/Pipelines/GamblingPipeline.cs @@ -8,65 +8,65 @@ namespace Sample.Pipelines; /// public static class GamblingPipeline { - public enum Colors - { - Red = 0, Black = 1 - } - public record Amount(int Value); + public enum Colors + { + Red = 0, Black = 1 + } + public record Amount(int Value); - public static void Run(int initialAmount, int numberOfAttempts) - { - Task> FourBetsInARow() => Result.Success(new Amount(initialAmount)) - .Bind(a => Bet(a, (Colors)Random.Shared.Next(2))) - .Bind(a => Bet(a, (Colors)Random.Shared.Next(2))) - .Bind(a => Bet(a, (Colors)Random.Shared.Next(2))) - .Bind(a => Bet(a, (Colors)Random.Shared.Next(2))); - - Console.WriteLine($"You're attempting to win 4 red/black bets in a row in {numberOfAttempts} attempts."); + public static void Run(int initialAmount, int numberOfAttempts) + { + Task> FourBetsInARow() => Result.Success(new Amount(initialAmount)) + .Bind(a => Bet(a, (Colors)Random.Shared.Next(2))) + .Bind(a => Bet(a, (Colors)Random.Shared.Next(2))) + .Bind(a => Bet(a, (Colors)Random.Shared.Next(2))) + .Bind(a => Bet(a, (Colors)Random.Shared.Next(2))); - var attemptsTasks = new List>>(); - for (var i = 0; i < numberOfAttempts; i++) - { - attemptsTasks.Add(FourBetsInARow()); - } + Console.WriteLine($"You're attempting to win 4 red/black bets in a row in {numberOfAttempts} attempts."); - Task.WaitAll(attemptsTasks.ToArray()); + var attemptsTasks = new List>>(); + for (var i = 0; i < numberOfAttempts; i++) + { + attemptsTasks.Add(FourBetsInARow()); + } - var attempts = attemptsTasks.Select(task => task.Result); + Task.WaitAll(attemptsTasks.ToArray()); - var messages = attempts.MatchEach( - win => $"You won {win.Value}", - $"You lost {initialAmount}"); - - foreach (var message in messages) - { - Console.WriteLine(message); - } + var attempts = attemptsTasks.Select(task => task.Result); - var totalWin = ( - from a in attempts.SelectValues() - select a.Value).Sum(); + var messages = attempts.MatchEach( + win => $"You won {win.Value}", + $"You lost {initialAmount}"); - Console.WriteLine($"You spent: {initialAmount * numberOfAttempts}"); - Console.WriteLine($"You 'won': {totalWin}"); - } + foreach (var message in messages) + { + Console.WriteLine(message); + } - private static async Task> Bet(Amount amount, Colors color) - { - var winColor = (Colors) Random.Shared.Next(2); + var totalWin = ( + from a in attempts.SelectValues() + select a.Value).Sum(); - await Task.Delay(Random.Shared.Next(1000)); - - if (winColor == color) - { - Console.WriteLine(" you won :)"); - return Result.Success(new Amount(amount.Value * 2)); - } - else - { - Console.WriteLine(" you lost :("); - return new LogicError("You lost"); - } - } + Console.WriteLine($"You spent: {initialAmount * numberOfAttempts}"); + Console.WriteLine($"You 'won': {totalWin}"); + } + + private static async Task> Bet(Amount amount, Colors color) + { + var winColor = (Colors)Random.Shared.Next(2); + + await Task.Delay(Random.Shared.Next(1000)); + + if (winColor == color) + { + Console.WriteLine(" you won :)"); + return Result.Success(new Amount(amount.Value * 2)); + } + else + { + Console.WriteLine(" you lost :("); + return new LogicError("You lost"); + } + } } \ No newline at end of file diff --git a/sample/ConsoleApp/Samples/Books.cs b/sample/ConsoleApp/Samples/Books.cs index d13cf9a..e710116 100644 --- a/sample/ConsoleApp/Samples/Books.cs +++ b/sample/ConsoleApp/Samples/Books.cs @@ -9,74 +9,74 @@ namespace Sample.Samples; public static class Books { - public static void Example() - { - var bourbaki = new Person("Bourbaki", null); - var euler = new Person("Leonhard", "Euler"); - var erdos = new Person("Pál", "Erdős"); + public static void Example() + { + var bourbaki = new Person("Bourbaki", null); + var euler = new Person("Leonhard", "Euler"); + var erdos = new Person("Pál", "Erdős"); - var algebra = new Book("Algebra", bourbaki); - var elementsOfAlgebra = new Book("Elements of Algebra", euler); - var mathematicalTables = new Book("Mathematical Tables", null); + var algebra = new Book("Algebra", bourbaki); + var elementsOfAlgebra = new Book("Elements of Algebra", euler); + var mathematicalTables = new Book("Mathematical Tables", null); - Console.WriteLine(bourbaki.GetFullName()); - Console.WriteLine(erdos.GetFullName()); - Console.WriteLine(elementsOfAlgebra.GetPrintableTitle()); - Console.WriteLine(mathematicalTables.GetPrintableTitle()); + Console.WriteLine(bourbaki.GetFullName()); + Console.WriteLine(erdos.GetFullName()); + Console.WriteLine(elementsOfAlgebra.GetPrintableTitle()); + Console.WriteLine(mathematicalTables.GetPrintableTitle()); - IEnumerable none = - from b in bourbaki.Surname - from e in euler.Surname - select $"{b} {e}"; + IEnumerable none = + from b in bourbaki.Surname + from e in euler.Surname + select $"{b} {e}"; - Debug.Assert(!none.Any()); + Debug.Assert(!none.Any()); - IEnumerable superMather = - from b in erdos.Surname - from e in euler.Surname - select $"{b} {e}"; + IEnumerable superMather = + from b in erdos.Surname + from e in euler.Surname + select $"{b} {e}"; - Debug.Assert(superMather.Count() == 1); + Debug.Assert(superMather.Count() == 1); - Console.WriteLine($"Super Mathematician: {superMather.First()}"); + Console.WriteLine($"Super Mathematician: {superMather.First()}"); - // Processing a list of Maybe<>s - var books = new List> { algebra, elementsOfAlgebra, mathematicalTables, Maybe.None() }; + // Processing a list of Maybe<>s + var books = new List> { algebra, elementsOfAlgebra, mathematicalTables, Maybe.None() }; - var validBooks = books.SelectValues(); // Retrieve values of Maybes that hold some value, None are discarded + var validBooks = books.SelectValues(); // Retrieve values of Maybes that hold some value, None are discarded - Console.WriteLine("=== VALID BOOKS"); - foreach (var b in validBooks) - { - Console.WriteLine(b); - } + Console.WriteLine("=== VALID BOOKS"); + foreach (var b in validBooks) + { + Console.WriteLine(b); + } - var validAuthors = books - .BindEach(x => x.Author) - .WhereNot(a => a.Name.StartsWith("Xulu")) - .WhereNot(a => a.Surname.Satisfy(x => x.StartsWith("Fugu"))) - .SelectValues(); + var validAuthors = books + .BindEach(x => x.Author) + .WhereNot(a => a.Name.StartsWith("Xulu")) + .WhereNot(a => a.Surname.Satisfy(x => x.StartsWith("Fugu"))) + .SelectValues(); - var bookDescriptions = books.MapEach(b => $"Title: {b.Title}, Author: {b.Author.Map( // Include the Author - a => $"{a.Name}{a.Surname.Map( - s => $" {s}") // Append the surname - .GetValue("")}") // or nothing - .GetValue("Unknown")}") // Unknown author - .SelectValues(); + var bookDescriptions = books.MapEach(b => $"Title: {b.Title}, Author: {b.Author.Map( // Include the Author + a => $"{a.Name}{a.Surname.Map( + s => $" {s}") // Append the surname + .GetValue("")}") // or nothing + .GetValue("Unknown")}") // Unknown author + .SelectValues(); - Console.WriteLine("=== VALID AUTHORS"); - foreach (var a in validAuthors) - { - Console.WriteLine(a); - } + Console.WriteLine("=== VALID AUTHORS"); + foreach (var a in validAuthors) + { + Console.WriteLine(a); + } - Console.WriteLine("=== BOOK DESCRIPTIONS"); - foreach (var _ in bookDescriptions) - { - Console.WriteLine(_); - } - } + Console.WriteLine("=== BOOK DESCRIPTIONS"); + foreach (var _ in bookDescriptions) + { + Console.WriteLine(_); + } + } } \ No newline at end of file diff --git a/sample/FluentValidationSample/ApplicationError.cs b/sample/FluentValidationSample/ApplicationError.cs index 9400f40..cf8d80f 100644 --- a/sample/FluentValidationSample/ApplicationError.cs +++ b/sample/FluentValidationSample/ApplicationError.cs @@ -2,10 +2,10 @@ namespace FluentValidationSample; -public class ApplicationError: LogicError +public class ApplicationError : LogicError { - public ApplicationError(string message) - : base(message) - { - } + public ApplicationError(string message) + : base(message) + { + } } \ No newline at end of file diff --git a/sample/FluentValidationSample/ProductName.cs b/sample/FluentValidationSample/ProductName.cs index 3e8c91f..977ceb8 100644 --- a/sample/FluentValidationSample/ProductName.cs +++ b/sample/FluentValidationSample/ProductName.cs @@ -5,29 +5,29 @@ namespace FluentValidationSample; public class ProductName { - public class Validator: AbstractValidator - { - public const int NameMaxLength = 10; - public Validator() - { - RuleFor(x => x.Name).NotEmpty().MaximumLength(NameMaxLength); - } - } - - public string Name { get; } - private ProductName(string name) - { - Name = name; - } + public class Validator : AbstractValidator + { + public const int NameMaxLength = 10; + public Validator() + { + RuleFor(x => x.Name).NotEmpty().MaximumLength(NameMaxLength); + } + } - public static Result Create(string name) - { - var instance = new ProductName(name); - var validationResult = new Validator().Validate(instance); - - if (!validationResult.IsValid) return - new ValidationError(typeof(ProductName), validationResult.Errors); + public string Name { get; } + private ProductName(string name) + { + Name = name; + } - return instance; - } + public static Result Create(string name) + { + var instance = new ProductName(name); + var validationResult = new Validator().Validate(instance); + + if (!validationResult.IsValid) return + new ValidationError(typeof(ProductName), validationResult.Errors); + + return instance; + } } \ No newline at end of file diff --git a/sample/FluentValidationSample/Program.cs b/sample/FluentValidationSample/Program.cs index d7dec5d..b064211 100644 --- a/sample/FluentValidationSample/Program.cs +++ b/sample/FluentValidationSample/Program.cs @@ -17,10 +17,10 @@ switch (error) { - case ValidationError validationError: - foreach (var f in validationError.Failures) - { - Console.WriteLine($"Property [{f.PropertyName}] failed with message: {f.ErrorMessage}"); - } - break; + case ValidationError validationError: + foreach (var f in validationError.Failures) + { + Console.WriteLine($"Property [{f.PropertyName}] failed with message: {f.ErrorMessage}"); + } + break; } \ No newline at end of file diff --git a/sample/FluentValidationSample/ValidationError.cs b/sample/FluentValidationSample/ValidationError.cs index bb0b8eb..148b67d 100644 --- a/sample/FluentValidationSample/ValidationError.cs +++ b/sample/FluentValidationSample/ValidationError.cs @@ -7,36 +7,36 @@ namespace FluentValidationSample; /// public class ValidationError : ApplicationError { - private readonly List _failures = new(); - - /// - /// Returns a list of s. - /// - public IReadOnlyList Failures => _failures; - - /// - /// The type of the object that failed validation. - /// - public Type ObjectType { get; } - - /// - /// Initializes a new instance of the class. - /// - public ValidationError( - string message, - Type type, - IEnumerable failures) - : base(message) - { - ObjectType = type; - _failures.AddRange(failures); - } - - /// - public ValidationError( - Type type, - IEnumerable failures) - : this($"Error validating {type.Name}", type, failures) - { - } + private readonly List _failures = new(); + + /// + /// Returns a list of s. + /// + public IReadOnlyList Failures => _failures; + + /// + /// The type of the object that failed validation. + /// + public Type ObjectType { get; } + + /// + /// Initializes a new instance of the class. + /// + public ValidationError( + string message, + Type type, + IEnumerable failures) + : base(message) + { + ObjectType = type; + _failures.AddRange(failures); + } + + /// + public ValidationError( + Type type, + IEnumerable failures) + : this($"Error validating {type.Name}", type, failures) + { + } } \ No newline at end of file diff --git a/sample/WebApplication/DomainError.cs b/sample/WebApplication/DomainError.cs index fea60a9..7766483 100644 --- a/sample/WebApplication/DomainError.cs +++ b/sample/WebApplication/DomainError.cs @@ -1,21 +1,21 @@ // ReSharper disable UnusedAutoPropertyAccessor.Global namespace SampleWebApplication; -public class DomainError: LogicError +public class DomainError : LogicError { - public enum ErrorSeverity - { - Low, - Medium, - High - } - - public int Code { get; } - public ErrorSeverity Severity { get; } - public DomainError(string message, int code, ErrorSeverity severity = ErrorSeverity.Low) - : base(message) - { - Code = code; - Severity = severity; - } + public enum ErrorSeverity + { + Low, + Medium, + High + } + + public int Code { get; } + public ErrorSeverity Severity { get; } + public DomainError(string message, int code, ErrorSeverity severity = ErrorSeverity.Low) + : base(message) + { + Code = code; + Severity = severity; + } } \ No newline at end of file diff --git a/sample/WebApplication/MaybeExtensions.cs b/sample/WebApplication/MaybeExtensions.cs index 26a37b2..eb191af 100644 --- a/sample/WebApplication/MaybeExtensions.cs +++ b/sample/WebApplication/MaybeExtensions.cs @@ -4,6 +4,6 @@ namespace SampleWebApplication; public static class MaybeExtensions { - public static IResult ToResult(this Maybe maybe) where T : class - => maybe.Map(Results.Ok).GetValue(Results.NotFound()); + public static IResult ToResult(this Maybe maybe) where T : class + => maybe.Map(Results.Ok).GetValue(Results.NotFound()); } \ No newline at end of file diff --git a/sample/WebApplication/ResultExtensions.cs b/sample/WebApplication/ResultExtensions.cs index 6150be5..5ec707a 100644 --- a/sample/WebApplication/ResultExtensions.cs +++ b/sample/WebApplication/ResultExtensions.cs @@ -2,7 +2,7 @@ namespace SampleWebApplication; public static class ResultExtensions { - /* + /* public static IResult ToResult(this Result result) where TError : Error => result.Match(); diff --git a/src/Monads/Error/AggregateError.cs b/src/Monads/Error/AggregateError.cs index 23114e1..5b5d2d0 100644 --- a/src/Monads/Error/AggregateError.cs +++ b/src/Monads/Error/AggregateError.cs @@ -7,47 +7,47 @@ namespace Bogoware.Monads; /// public class AggregateError : Error { - private const string ERROR_MESSAGE = "Multiple errors occurred"; - private readonly List _innerErrors; - - /// - /// The errors that were aggregated. - /// - public IEnumerable Errors => _innerErrors; - - /// - /// Initializes a new instance of the class. - /// - /// The error message - /// The inner errors - public AggregateError(string message, IEnumerable innerErrors) - { - if (message is null) throw new ArgumentNullException(nameof(message)); - if (innerErrors is null) throw new ArgumentNullException(nameof(innerErrors)); - Message = message; - _innerErrors = [..innerErrors]; - } - - public AggregateError(string message, Error first, Error second, params Error[] others) - : this(message, ConcatenateErrors(first, second, others)) - { - } - - public AggregateError(IEnumerable innerErrors) - : this(ERROR_MESSAGE, innerErrors) - { - } - - public AggregateError(Error first, Error second, params Error[] others) - : this(ConcatenateErrors(first, second, others)) - { - } - - public override string Message { get; } - - private static IEnumerable ConcatenateErrors(Error first, Error second, IEnumerable others) - { - var errors = new List { first, second }; - return errors.Concat(others); - } + private const string ERROR_MESSAGE = "Multiple errors occurred"; + private readonly List _innerErrors; + + /// + /// The errors that were aggregated. + /// + public IEnumerable Errors => _innerErrors; + + /// + /// Initializes a new instance of the class. + /// + /// The error message + /// The inner errors + public AggregateError(string message, IEnumerable innerErrors) + { + if (message is null) throw new ArgumentNullException(nameof(message)); + if (innerErrors is null) throw new ArgumentNullException(nameof(innerErrors)); + Message = message; + _innerErrors = [..innerErrors]; + } + + public AggregateError(string message, Error first, Error second, params Error[] others) + : this(message, ConcatenateErrors(first, second, others)) + { + } + + public AggregateError(IEnumerable innerErrors) + : this(ERROR_MESSAGE, innerErrors) + { + } + + public AggregateError(Error first, Error second, params Error[] others) + : this(ConcatenateErrors(first, second, others)) + { + } + + public override string Message { get; } + + private static IEnumerable ConcatenateErrors(Error first, Error second, IEnumerable others) + { + var errors = new List { first, second }; + return errors.Concat(others); + } } \ No newline at end of file diff --git a/src/Monads/Error/Error.cs b/src/Monads/Error/Error.cs index 36d6254..d165862 100644 --- a/src/Monads/Error/Error.cs +++ b/src/Monads/Error/Error.cs @@ -5,8 +5,8 @@ namespace Bogoware.Monads; /// public abstract class Error { - /// - /// The error message. - /// - public abstract string Message { get; } + /// + /// The error message. + /// + public abstract string Message { get; } } \ No newline at end of file diff --git a/src/Monads/Error/LogicError.cs b/src/Monads/Error/LogicError.cs index 5299b88..40b1a97 100644 --- a/src/Monads/Error/LogicError.cs +++ b/src/Monads/Error/LogicError.cs @@ -32,35 +32,35 @@ namespace Bogoware.Monads; /// } /// } /// -public class LogicError: Error, IEquatable +public class LogicError : Error, IEquatable { - public override string Message { get; } - public LogicError(string message) - { - if (message is null) throw new ArgumentNullException(nameof(message)); - Message = message; - } + public override string Message { get; } + public LogicError(string message) + { + if (message is null) throw new ArgumentNullException(nameof(message)); + Message = message; + } - public bool Equals(LogicError? other) - { - if (ReferenceEquals(null, other)) return false; - if (ReferenceEquals(this, other)) return true; - return Message == other.Message; - } + public bool Equals(LogicError? other) + { + if (ReferenceEquals(null, other)) return false; + if (ReferenceEquals(this, other)) return true; + return Message == other.Message; + } - public override bool Equals(object? obj) => Equals(obj as LogicError); + public override bool Equals(object? obj) => Equals(obj as LogicError); - public override int GetHashCode() => Message.GetHashCode(); + public override int GetHashCode() => Message.GetHashCode(); - public static bool operator ==(LogicError? left, LogicError? right) => Equals(left, right); + public static bool operator ==(LogicError? left, LogicError? right) => Equals(left, right); - public static bool operator !=(LogicError? left, LogicError? right) => !Equals(left, right); - public void Deconstruct(out string message) - { - message = Message; - } + public static bool operator !=(LogicError? left, LogicError? right) => !Equals(left, right); + public void Deconstruct(out string message) + { + message = Message; + } - public override string ToString() => $"""LogicError: "{Message}"."""; - - public static implicit operator LogicError(string message) => new(message); + public override string ToString() => $"""LogicError: "{Message}"."""; + + public static implicit operator LogicError(string message) => new(message); } \ No newline at end of file diff --git a/src/Monads/Error/RuntimeError.cs b/src/Monads/Error/RuntimeError.cs index a1a041c..cb72fb6 100644 --- a/src/Monads/Error/RuntimeError.cs +++ b/src/Monads/Error/RuntimeError.cs @@ -7,12 +7,12 @@ namespace Bogoware.Monads; /// public sealed class RuntimeError : Error { - public Exception Exception { get; } - public RuntimeError(Exception exception) - { - if (exception is null) throw new ArgumentNullException(nameof(exception)); - Exception = exception; - } + public Exception Exception { get; } + public RuntimeError(Exception exception) + { + if (exception is null) throw new ArgumentNullException(nameof(exception)); + Exception = exception; + } - public override string Message => Exception.Message; + public override string Message => Exception.Message; } \ No newline at end of file diff --git a/src/Monads/Exceptions/MaybeNoneException.cs b/src/Monads/Exceptions/MaybeNoneException.cs index 7ee62d3..181ac3d 100644 --- a/src/Monads/Exceptions/MaybeNoneException.cs +++ b/src/Monads/Exceptions/MaybeNoneException.cs @@ -6,12 +6,12 @@ namespace Bogoware.Monads; /// public class MaybeNoneException : ArgumentNullException { - private const string ERROR_MESSAGE = "The Maybe is None"; - public MaybeNoneException():base(ERROR_MESSAGE) - { - } - public MaybeNoneException(Exception inner) - : base(ERROR_MESSAGE, inner) - { - } + private const string ERROR_MESSAGE = "The Maybe is None"; + public MaybeNoneException() : base(ERROR_MESSAGE) + { + } + public MaybeNoneException(Exception inner) + : base(ERROR_MESSAGE, inner) + { + } } \ No newline at end of file diff --git a/src/Monads/Exceptions/ResultFailedException.cs b/src/Monads/Exceptions/ResultFailedException.cs index 0ff93f3..ff1224f 100644 --- a/src/Monads/Exceptions/ResultFailedException.cs +++ b/src/Monads/Exceptions/ResultFailedException.cs @@ -7,13 +7,13 @@ namespace Bogoware.Monads; /// public class ResultFailedException : ResultInvalidOperationException { - private const string ERROR_MESSAGE = "Result is failed: "; - /// - /// The error of the that failed. - /// - public Error Error { get; } - public ResultFailedException(Error error):base($"{ERROR_MESSAGE}'{error.Message}'") - { - Error = error; - } + private const string ERROR_MESSAGE = "Result is failed: "; + /// + /// The error of the that failed. + /// + public Error Error { get; } + public ResultFailedException(Error error) : base($"{ERROR_MESSAGE}'{error.Message}'") + { + Error = error; + } } \ No newline at end of file diff --git a/src/Monads/Exceptions/ResultInvalidOperationException.cs b/src/Monads/Exceptions/ResultInvalidOperationException.cs index ed70fb1..388c863 100644 --- a/src/Monads/Exceptions/ResultInvalidOperationException.cs +++ b/src/Monads/Exceptions/ResultInvalidOperationException.cs @@ -5,8 +5,8 @@ namespace Bogoware.Monads; /// public class ResultInvalidOperationException : InvalidOperationException { - protected ResultInvalidOperationException(string message) - : base(message) - { - } + protected ResultInvalidOperationException(string message) + : base(message) + { + } } \ No newline at end of file diff --git a/src/Monads/Exceptions/ResultSuccessException.cs b/src/Monads/Exceptions/ResultSuccessException.cs index 928bded..6890ecb 100644 --- a/src/Monads/Exceptions/ResultSuccessException.cs +++ b/src/Monads/Exceptions/ResultSuccessException.cs @@ -6,9 +6,9 @@ namespace Bogoware.Monads; /// public class ResultSuccessException : ResultInvalidOperationException { - private const string ERROR_MESSAGE = "Result is successful"; - public ResultSuccessException():base(ERROR_MESSAGE) - { - - } + private const string ERROR_MESSAGE = "Result is successful"; + public ResultSuccessException() : base(ERROR_MESSAGE) + { + + } } \ No newline at end of file diff --git a/src/Monads/Maybe/IMaybe.cs b/src/Monads/Maybe/IMaybe.cs index 0e063ae..b9973bc 100644 --- a/src/Monads/Maybe/IMaybe.cs +++ b/src/Monads/Maybe/IMaybe.cs @@ -6,8 +6,8 @@ namespace Bogoware.Monads; /// public interface IMaybe { - bool IsSome { get; } - bool IsNone { get; } + bool IsSome { get; } + bool IsNone { get; } } public interface IMaybe : IMaybe diff --git a/src/Monads/Maybe/Maybe.cs b/src/Monads/Maybe/Maybe.cs index b5df216..cef0d7c 100644 --- a/src/Monads/Maybe/Maybe.cs +++ b/src/Monads/Maybe/Maybe.cs @@ -9,35 +9,35 @@ namespace Bogoware.Monads; public static class Maybe { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Maybe From(T? value) => new(value); - - //[MethodImpl(MethodImplOptions.AggressiveInlining)] - //public static Maybe From(T? value) where T : struct => new(value); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Maybe From(Maybe maybe) => new(maybe); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Maybe Some(T value) - { - if (value is null) throw new ArgumentNullException(nameof(value)); - return new(value); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Maybe Some(Maybe maybe) - { - if (maybe.IsNone) throw new MaybeNoneException(); - - return new(maybe); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Maybe None() => Maybe.None; - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Maybe None() => Maybe.None; + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Maybe From(T? value) => new(value); + + //[MethodImpl(MethodImplOptions.AggressiveInlining)] + //public static Maybe From(T? value) where T : struct => new(value); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Maybe From(Maybe maybe) => new(maybe); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Maybe Some(T value) + { + if (value is null) throw new ArgumentNullException(nameof(value)); + return new(value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Maybe Some(Maybe maybe) + { + if (maybe.IsNone) throw new MaybeNoneException(); + + return new(maybe); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Maybe None() => Maybe.None; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Maybe None() => Maybe.None; } @@ -46,168 +46,168 @@ public static Maybe Some(Maybe maybe) /// public readonly struct Maybe : IMaybe, IEquatable>, IEnumerable { - private readonly TValue? _value = default; - /// - /// Is true if the maybe is some, otherwise false. - /// - public bool IsSome => _value is not null; - /// - /// Is true if the maybe is none, otherwise false. - /// - public bool IsNone => _value is null; - /// - /// Returns the singleton instance of representing the none state. - /// - public static readonly Maybe None = default; - - /// - /// Initializes a new instance of the . - /// - public Maybe(TValue? value) - { - if (value is not null) - { - _value = value; - } - } - - /// - /// Initializes a new instance of the . - /// - public Maybe(Maybe maybe) => _value = maybe._value; - - /// - /// Returns the value if the maybe is some, otherwise throws an exception. - /// - /// - /// - public TValue GetValueOrThrow() => _value ?? throw new MaybeNoneException(); - - /// - /// Map the value to a new one. - /// - public Maybe Map(Func map) where TNewValue : class - => _value is not null ? new Maybe(map(_value)) : Maybe.None; - - /// - public async Task> Map(Func> map) where TNewValue : class - => _value is not null ? new(await map(_value)) : Maybe.None; - - /// - /// Bind the maybe and, possibly, to a new one. - /// - public Maybe Bind(Func> map) where TNewValue : class - => _value is not null ? map(_value) : Maybe.None; - - /// - public Task> Bind(Func>> map) where TNewValue : class - => _value is not null ? map(_value) : Task.FromResult(Maybe.None); - - /// - /// Maps a new value for both state of a - /// - public TResult Match(Func mapValue, TResult none) - => _value is not null ? mapValue(_value) : none; - - /// - public TResult Match(Func mapValue, Func none) - => _value is not null ? mapValue(_value) : none(); - - /// - public Task Match(Func> mapValue, TResult none) - => _value is not null ? mapValue(_value) : Task.FromResult(none); - - /// - public Task Match(Func> mapValue, Func none) - => _value is not null ? mapValue(_value) : Task.FromResult(none()); - - /// - public Task Match(Func> mapValue, Func> none) - => _value is not null ? mapValue(_value) : none(); - - /// - public Task Match(Func mapValue, Func> none) - => _value is not null ? Task.FromResult(mapValue(_value)) : none(); - - /// - /// Execute the action if the is Some. - /// - public Maybe ExecuteIfSome(Action action) - { - if (_value is not null) action(_value); - return this; - } - - /// - public async Task> ExecuteIfSome(Func action) - { - if (_value is not null) await action(_value); - return this; - } - - /// - /// Retrieve the value if present or return the defaultValue if missing. - /// - public TValue GetValue(TValue defaultValue) - { - if (defaultValue is null) throw new ArgumentNullException(nameof(defaultValue)); - - return _value ?? defaultValue; - } - - /// - public TValue GetValue(Func defaultValue) - { - if (defaultValue is null) throw new ArgumentNullException(nameof(defaultValue)); - - return _value ?? defaultValue(); - } - - /// - public async Task GetValue(Func> defaultValue) - { - if (defaultValue is null) throw new ArgumentNullException(nameof(defaultValue)); - return _value ?? await defaultValue(); - } - - /// - /// Downcast to TNew if possible, otherwise returns a - /// that is actually None case. - /// - /// - /// - public Maybe OfType() where TNewValue : class => - typeof(TValue).IsAssignableFrom(typeof(TNewValue)) - ? new Maybe(_value as TNewValue) - : Maybe.None; - - IEnumerator IEnumerable.GetEnumerator() - { - if (_value is not null) yield return _value; - } - - IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable)this).GetEnumerator(); - - public override bool Equals(object? obj) - { - if (obj is Maybe other) return Equals(other); - return false; - } - - public bool Equals(Maybe other) - { - if (_value is not null) return _value?.Equals(other._value) ?? false; - return other._value is null; - } - - public override int GetHashCode() => _value?.GetHashCode() ?? 0; - - public static bool operator ==(Maybe left, Maybe right) => left.Equals(right); - - public static bool operator !=(Maybe left, Maybe right) => !left.Equals(right); - - public override string ToString() => - _value is null ? $"None<{typeof(TValue).GetFriendlyTypeName()}>()" : $"Some({_value})"; - - public static implicit operator Maybe(TValue? value) => new(value); + private readonly TValue? _value = default; + /// + /// Is true if the maybe is some, otherwise false. + /// + public bool IsSome => _value is not null; + /// + /// Is true if the maybe is none, otherwise false. + /// + public bool IsNone => _value is null; + /// + /// Returns the singleton instance of representing the none state. + /// + public static readonly Maybe None = default; + + /// + /// Initializes a new instance of the . + /// + public Maybe(TValue? value) + { + if (value is not null) + { + _value = value; + } + } + + /// + /// Initializes a new instance of the . + /// + public Maybe(Maybe maybe) => _value = maybe._value; + + /// + /// Returns the value if the maybe is some, otherwise throws an exception. + /// + /// + /// + public TValue GetValueOrThrow() => _value ?? throw new MaybeNoneException(); + + /// + /// Map the value to a new one. + /// + public Maybe Map(Func map) where TNewValue : class + => _value is not null ? new Maybe(map(_value)) : Maybe.None; + + /// + public async Task> Map(Func> map) where TNewValue : class + => _value is not null ? new(await map(_value)) : Maybe.None; + + /// + /// Bind the maybe and, possibly, to a new one. + /// + public Maybe Bind(Func> map) where TNewValue : class + => _value is not null ? map(_value) : Maybe.None; + + /// + public Task> Bind(Func>> map) where TNewValue : class + => _value is not null ? map(_value) : Task.FromResult(Maybe.None); + + /// + /// Maps a new value for both state of a + /// + public TResult Match(Func mapValue, TResult none) + => _value is not null ? mapValue(_value) : none; + + /// + public TResult Match(Func mapValue, Func none) + => _value is not null ? mapValue(_value) : none(); + + /// + public Task Match(Func> mapValue, TResult none) + => _value is not null ? mapValue(_value) : Task.FromResult(none); + + /// + public Task Match(Func> mapValue, Func none) + => _value is not null ? mapValue(_value) : Task.FromResult(none()); + + /// + public Task Match(Func> mapValue, Func> none) + => _value is not null ? mapValue(_value) : none(); + + /// + public Task Match(Func mapValue, Func> none) + => _value is not null ? Task.FromResult(mapValue(_value)) : none(); + + /// + /// Execute the action if the is Some. + /// + public Maybe ExecuteIfSome(Action action) + { + if (_value is not null) action(_value); + return this; + } + + /// + public async Task> ExecuteIfSome(Func action) + { + if (_value is not null) await action(_value); + return this; + } + + /// + /// Retrieve the value if present or return the defaultValue if missing. + /// + public TValue GetValue(TValue defaultValue) + { + if (defaultValue is null) throw new ArgumentNullException(nameof(defaultValue)); + + return _value ?? defaultValue; + } + + /// + public TValue GetValue(Func defaultValue) + { + if (defaultValue is null) throw new ArgumentNullException(nameof(defaultValue)); + + return _value ?? defaultValue(); + } + + /// + public async Task GetValue(Func> defaultValue) + { + if (defaultValue is null) throw new ArgumentNullException(nameof(defaultValue)); + return _value ?? await defaultValue(); + } + + /// + /// Downcast to TNew if possible, otherwise returns a + /// that is actually None case. + /// + /// + /// + public Maybe OfType() where TNewValue : class => + typeof(TValue).IsAssignableFrom(typeof(TNewValue)) + ? new Maybe(_value as TNewValue) + : Maybe.None; + + IEnumerator IEnumerable.GetEnumerator() + { + if (_value is not null) yield return _value; + } + + IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable)this).GetEnumerator(); + + public override bool Equals(object? obj) + { + if (obj is Maybe other) return Equals(other); + return false; + } + + public bool Equals(Maybe other) + { + if (_value is not null) return _value?.Equals(other._value) ?? false; + return other._value is null; + } + + public override int GetHashCode() => _value?.GetHashCode() ?? 0; + + public static bool operator ==(Maybe left, Maybe right) => left.Equals(right); + + public static bool operator !=(Maybe left, Maybe right) => !left.Equals(right); + + public override string ToString() => + _value is null ? $"None<{typeof(TValue).GetFriendlyTypeName()}>()" : $"Some({_value})"; + + public static implicit operator Maybe(TValue? value) => new(value); } \ No newline at end of file diff --git a/src/Monads/Maybe/MaybeAsyncExtensions.cs b/src/Monads/Maybe/MaybeAsyncExtensions.cs index 873cd5f..442cc74 100644 --- a/src/Monads/Maybe/MaybeAsyncExtensions.cs +++ b/src/Monads/Maybe/MaybeAsyncExtensions.cs @@ -6,204 +6,204 @@ namespace Bogoware.Monads; public static class MaybeAsyncExtensions { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> Map( - this Task> maybeTask, Func map) - where TNewValue : class - where TValue : class - => (await maybeTask).Map(map); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> Map( - this Task> maybeTask, Func map) - where TNewValue : class - where TValue : class - => (await maybeTask).Map(map); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> Map( - this Task> maybeTask, Func> map) - where TNewValue : class - where TValue : class - => await (await maybeTask).Map(map); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> Map( - this Task> maybeTask, Func> map) - where TNewValue : class - where TValue : class - => await (await maybeTask).Map(map); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> WithDefault( - this Task> maybeTask, - TValue value) where TValue : class - => (await maybeTask).WithDefault(value); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> WithDefault( - this Task> maybeTask, - Func value) where TValue : class - => (await maybeTask).WithDefault(value); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> WithDefault( - this Task> maybeTask, - Func> value) where TValue : class - => await (await maybeTask).WithDefault(value); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> Bind( - this Task> maybeTask, Func> map) - where TNewValue : class - where TValue : class - => (await maybeTask).Bind(map); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> Bind( - this Task> maybeTask, Func> map) - where TNewValue : class - where TValue : class - => (await maybeTask).Bind(map); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> Bind( - this Task> maybeTask, Func>> map) - where TNewValue : class - where TValue : class - => await (await maybeTask).Bind(map); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> Bind( - this Task> maybeTask, Func>> map) - where TNewValue : class - where TValue : class - => await (await maybeTask).Bind(map); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task Match( - this Task> maybeTask, - TResult newValue, - TResult none) where TValue : class - => (await maybeTask).Match(newValue, none); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task Match( - this Task> maybeTask, - Func value, - TResult none) where TValue : class - => (await maybeTask).Match(value, none); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task Match( - this Task> maybeTask, - Func value, - Func none) where TValue : class - => (await maybeTask).Match(value, none); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task Match( - this Task> maybeTask, - Func> value, - Func none) where TValue : class - => await (await maybeTask).Match(value, none); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task Match( - this Task> maybeTask, - Func value, - Func> none) where TValue : class - => await (await maybeTask).Match(value, none); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task Match( - this Task> maybeTask, - Func> mapValue, TResult none) where TValue : class - => await (await maybeTask).Match(mapValue, none); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task Match( - this Task> maybeTask, - Func> value, - Func> none) where TValue : class - => await (await maybeTask).Match(value, none); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> ExecuteIfSome( - this Task> maybeTask, - Action action) where TValue : class - => (await maybeTask).ExecuteIfSome(action); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> ExecuteIfSome( - this Task> maybeTask, - Action action) where TValue : class - => (await maybeTask).ExecuteIfSome(action); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> ExecuteIfSome( - this Task> maybeTask, - Func action) where TValue : class - => await (await maybeTask).ExecuteIfSome(action); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> ExecuteIfSome( - this Task> maybeTask, - Func action) where TValue : class - => await (await maybeTask).ExecuteIfSome(action); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> ExecuteIfNone( - this Task> maybeTask, - Action action) where TValue : class - => (await maybeTask).ExecuteIfNone(action); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> ExecuteIfNone( - this Task> maybeTask, - Func action) where TValue : class - => await (await maybeTask).ExecuteIfNone(action); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> Execute( - this Task> maybeTask, - Action> action) where TValue : class - => (await maybeTask).Execute(action); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> Execute( - this Task> maybeTask, - Func, Task> action) where TValue : class - => await (await maybeTask).Execute(action); - - /// - /// Evaluate the predicate applied to the value if present. - /// Return false in case of None. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Task Satisfy(this Task> maybe, Func predicate) - where TValue : class - => maybe.Match(predicate, false); - - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Task Satisfy(this Task> maybe, Func> predicate) - where TValue : class - => maybe.Match(predicate, false); - - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> ToResult(this Task> maybeTask, Func errorFunc) where TValue : class - { - var maybe = await maybeTask; - return maybe.ToResult(errorFunc); - } - - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> ToResult(this Task> maybeTask, Func> errorFunc) where TValue : class - { - var maybe = await maybeTask; - return await maybe.ToResult(errorFunc); - } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> Map( + this Task> maybeTask, Func map) + where TNewValue : class + where TValue : class + => (await maybeTask).Map(map); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> Map( + this Task> maybeTask, Func map) + where TNewValue : class + where TValue : class + => (await maybeTask).Map(map); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> Map( + this Task> maybeTask, Func> map) + where TNewValue : class + where TValue : class + => await (await maybeTask).Map(map); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> Map( + this Task> maybeTask, Func> map) + where TNewValue : class + where TValue : class + => await (await maybeTask).Map(map); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> WithDefault( + this Task> maybeTask, + TValue value) where TValue : class + => (await maybeTask).WithDefault(value); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> WithDefault( + this Task> maybeTask, + Func value) where TValue : class + => (await maybeTask).WithDefault(value); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> WithDefault( + this Task> maybeTask, + Func> value) where TValue : class + => await (await maybeTask).WithDefault(value); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> Bind( + this Task> maybeTask, Func> map) + where TNewValue : class + where TValue : class + => (await maybeTask).Bind(map); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> Bind( + this Task> maybeTask, Func> map) + where TNewValue : class + where TValue : class + => (await maybeTask).Bind(map); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> Bind( + this Task> maybeTask, Func>> map) + where TNewValue : class + where TValue : class + => await (await maybeTask).Bind(map); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> Bind( + this Task> maybeTask, Func>> map) + where TNewValue : class + where TValue : class + => await (await maybeTask).Bind(map); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task Match( + this Task> maybeTask, + TResult newValue, + TResult none) where TValue : class + => (await maybeTask).Match(newValue, none); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task Match( + this Task> maybeTask, + Func value, + TResult none) where TValue : class + => (await maybeTask).Match(value, none); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task Match( + this Task> maybeTask, + Func value, + Func none) where TValue : class + => (await maybeTask).Match(value, none); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task Match( + this Task> maybeTask, + Func> value, + Func none) where TValue : class + => await (await maybeTask).Match(value, none); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task Match( + this Task> maybeTask, + Func value, + Func> none) where TValue : class + => await (await maybeTask).Match(value, none); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task Match( + this Task> maybeTask, + Func> mapValue, TResult none) where TValue : class + => await (await maybeTask).Match(mapValue, none); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task Match( + this Task> maybeTask, + Func> value, + Func> none) where TValue : class + => await (await maybeTask).Match(value, none); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> ExecuteIfSome( + this Task> maybeTask, + Action action) where TValue : class + => (await maybeTask).ExecuteIfSome(action); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> ExecuteIfSome( + this Task> maybeTask, + Action action) where TValue : class + => (await maybeTask).ExecuteIfSome(action); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> ExecuteIfSome( + this Task> maybeTask, + Func action) where TValue : class + => await (await maybeTask).ExecuteIfSome(action); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> ExecuteIfSome( + this Task> maybeTask, + Func action) where TValue : class + => await (await maybeTask).ExecuteIfSome(action); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> ExecuteIfNone( + this Task> maybeTask, + Action action) where TValue : class + => (await maybeTask).ExecuteIfNone(action); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> ExecuteIfNone( + this Task> maybeTask, + Func action) where TValue : class + => await (await maybeTask).ExecuteIfNone(action); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> Execute( + this Task> maybeTask, + Action> action) where TValue : class + => (await maybeTask).Execute(action); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> Execute( + this Task> maybeTask, + Func, Task> action) where TValue : class + => await (await maybeTask).Execute(action); + + /// + /// Evaluate the predicate applied to the value if present. + /// Return false in case of None. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Task Satisfy(this Task> maybe, Func predicate) + where TValue : class + => maybe.Match(predicate, false); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Task Satisfy(this Task> maybe, Func> predicate) + where TValue : class + => maybe.Match(predicate, false); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> ToResult(this Task> maybeTask, Func errorFunc) where TValue : class + { + var maybe = await maybeTask; + return maybe.ToResult(errorFunc); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> ToResult(this Task> maybeTask, Func> errorFunc) where TValue : class + { + var maybe = await maybeTask; + return await maybe.ToResult(errorFunc); + } } \ No newline at end of file diff --git a/src/Monads/Maybe/MaybeEnumerableExtensions.cs b/src/Monads/Maybe/MaybeEnumerableExtensions.cs index 392f559..8f91c5f 100644 --- a/src/Monads/Maybe/MaybeEnumerableExtensions.cs +++ b/src/Monads/Maybe/MaybeEnumerableExtensions.cs @@ -6,110 +6,110 @@ namespace Bogoware.Monads; public static class MaybeEnumerableExtensions { - /// - /// Determines if all s of a sequence are Somes. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool AllSome(this IEnumerable maybes) - => maybes.All(m => m.IsSome); - - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool AllSome(this IEnumerable> maybes) where TValue : class - => maybes.All(m => m.IsSome); - - /// - /// Determines if all s of a sequence are Nones. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool AllNone(this IEnumerable maybes) - => maybes.All(m => m.IsNone); - - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool AllNone(this IEnumerable> maybes) where TValue : class - => maybes.All(m => m.IsNone); - - /// - /// Determines if any of a sequence is Some. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool AnySome(this IEnumerable maybes) - => maybes.Any(m => m.IsSome); - - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool AnySome(this IEnumerable> maybes) where TValue : class - => maybes.Any(m => m.IsSome); - - /// - /// Determines if any of a sequence is None. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool AnyNone(this IEnumerable maybes) - => maybes.Any(m => m.IsNone); - - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool AnyNone(this IEnumerable> maybes) where TValue : class => maybes.Any(m => m.IsNone); - - /// - /// Extract values from s. - /// Nones are discarded. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static IEnumerable SelectValues(this IEnumerable> maybes) - where TValue : class - => maybes.SelectMany(m => m); - - /// - /// Bind values via the functor. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static IEnumerable> BindEach( - this IEnumerable> maybes, Func> functor) - where TValue : class - where TNewValue : class - => maybes.Select(m => m.Bind(functor)); - - /// - /// Maps values via the functor. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static IEnumerable> MapEach( - this IEnumerable> maybes, Func functor) - where TValue : class - where TNewValue : class - => maybes.Select(m => m.Map(functor)); - - /// - /// Matches maybes via the two functors. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static IEnumerable MatchEach( - this IEnumerable> maybes, - Func mapSuccesses, - TResult none) - where TValue : class - => maybes.Select(maybe => maybe.Match(mapSuccesses, none)); - - /// - /// Filters Somes via the predicate. - /// Nones are discarded. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static IEnumerable> Where( - this IEnumerable> maybes, Func predicate) - where TValue : class - => maybes.SelectValues().Where(predicate).Select(Maybe.Some); - - /// - /// Filters Somes via negated predicate. - /// Nones are discarded. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static IEnumerable> WhereNot( - this IEnumerable> maybes, Func predicate) - where TValue : class - => maybes.SelectValues().Where(v => !predicate(v)).Select(Maybe.Some); + /// + /// Determines if all s of a sequence are Somes. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool AllSome(this IEnumerable maybes) + => maybes.All(m => m.IsSome); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool AllSome(this IEnumerable> maybes) where TValue : class + => maybes.All(m => m.IsSome); + + /// + /// Determines if all s of a sequence are Nones. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool AllNone(this IEnumerable maybes) + => maybes.All(m => m.IsNone); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool AllNone(this IEnumerable> maybes) where TValue : class + => maybes.All(m => m.IsNone); + + /// + /// Determines if any of a sequence is Some. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool AnySome(this IEnumerable maybes) + => maybes.Any(m => m.IsSome); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool AnySome(this IEnumerable> maybes) where TValue : class + => maybes.Any(m => m.IsSome); + + /// + /// Determines if any of a sequence is None. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool AnyNone(this IEnumerable maybes) + => maybes.Any(m => m.IsNone); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool AnyNone(this IEnumerable> maybes) where TValue : class => maybes.Any(m => m.IsNone); + + /// + /// Extract values from s. + /// Nones are discarded. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static IEnumerable SelectValues(this IEnumerable> maybes) + where TValue : class + => maybes.SelectMany(m => m); + + /// + /// Bind values via the functor. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static IEnumerable> BindEach( + this IEnumerable> maybes, Func> functor) + where TValue : class + where TNewValue : class + => maybes.Select(m => m.Bind(functor)); + + /// + /// Maps values via the functor. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static IEnumerable> MapEach( + this IEnumerable> maybes, Func functor) + where TValue : class + where TNewValue : class + => maybes.Select(m => m.Map(functor)); + + /// + /// Matches maybes via the two functors. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static IEnumerable MatchEach( + this IEnumerable> maybes, + Func mapSuccesses, + TResult none) + where TValue : class + => maybes.Select(maybe => maybe.Match(mapSuccesses, none)); + + /// + /// Filters Somes via the predicate. + /// Nones are discarded. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static IEnumerable> Where( + this IEnumerable> maybes, Func predicate) + where TValue : class + => maybes.SelectValues().Where(predicate).Select(Maybe.Some); + + /// + /// Filters Somes via negated predicate. + /// Nones are discarded. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static IEnumerable> WhereNot( + this IEnumerable> maybes, Func predicate) + where TValue : class + => maybes.SelectValues().Where(v => !predicate(v)).Select(Maybe.Some); } \ No newline at end of file diff --git a/src/Monads/Maybe/MaybeExtensions.cs b/src/Monads/Maybe/MaybeExtensions.cs index d0bb213..a7edda8 100644 --- a/src/Monads/Maybe/MaybeExtensions.cs +++ b/src/Monads/Maybe/MaybeExtensions.cs @@ -8,216 +8,216 @@ namespace Bogoware.Monads; public static class MaybeExtensions { - /// - /// Map the value to a new one. - /// - public static Maybe Map(this Maybe maybe, TNewValue? value) - where TNewValue : class where TValue : class - => maybe.IsSome ? new(value) : Maybe.None; - - /// - public static Maybe Map(this Maybe maybe, Func map) - where TNewValue : class where TValue : class - => maybe.IsSome ? new(map()) : Maybe.None; - - /// - public static async Task> Map( - this Maybe maybe, Func> map) - where TNewValue : class where TValue : class - => maybe.IsSome ? new(await map()) : Maybe.None; - - /// - /// Bind the maybe and, possibly, to a new one. - /// - public static Maybe Bind(this Maybe maybe, Func> map) - where TNewValue : class where TValue : class - => maybe.IsSome ? map() : Maybe.None; - - /// - public static Task> Bind( - this Maybe maybe, Func>> map) - where TNewValue : class where TValue : class - => maybe.IsSome ? map() : Task.FromResult(Maybe.None); - - /// - /// Maps a new value for both state of a - /// - public static TResult Match(this Maybe maybe, TResult resultOnValue, TResult resultOnNone) - where TValue : class - => maybe.IsSome ? resultOnValue : resultOnNone; - - /// - public static TResult Match( - this Maybe maybe, Func resultOnValue, TResult resultOnNone) - where TValue : class - => maybe.IsSome ? resultOnValue() : resultOnNone; - - /// - public static TResult Match( - this Maybe maybe, TResult resultOnValue, Func resultOnNone) - where TValue : class - => maybe.IsSome ? resultOnValue : resultOnNone(); - - /// - public static TResult Match( - this Maybe maybe, Func resultOnValue, Func resultOnNone) - where TValue : class - => maybe.IsSome ? resultOnValue() : resultOnNone(); - - /// - public static Task Match( - this Maybe maybe, Func> resultOnValue, TResult resultOnNone) - where TValue : class - => maybe.IsSome ? resultOnValue() : Task.FromResult(resultOnNone); - - /// - public static Task Match( - this Maybe maybe, TResult resultOnValue, Func> resultOnNone) - where TValue : class - => maybe.IsSome ? Task.FromResult(resultOnValue) : resultOnNone(); - - /// - public static Task Match( - this Maybe maybe, Func> resultOnValue, Func> resultOnNone) - where TValue : class - => maybe.IsSome ? resultOnValue() : resultOnNone(); - - /// - /// Returns a with Some(first) in case of non empty list. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Maybe ToMaybe(this IEnumerable? values) where TValue : class - => values is not null && values.Any() - ? Maybe.Some(values.First()) - : Maybe.None(); - - /// - /// Returns the original Some if predicate is satisfied, None otherwise. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Maybe Where(this TValue? obj, Func predicate) where TValue : class - => obj is not null && predicate(obj) - ? Maybe.Some(obj) - : Maybe.None(); - - /// - /// Returns the original Some if predicate is not satisfied, None otherwise. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Maybe WhereNot(this TValue? obj, Func predicate) where TValue : class - => obj is not null && !predicate(obj) - ? Maybe.Some(obj) - : Maybe.None(); - - /// - /// Evaluate the predicate applied to the value if present. - /// Return false in case of None. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool Satisfy(this Maybe maybe, Func predicate) where TValue : class - => maybe.Match(predicate, false); - - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task Satisfy(this Maybe maybe, Func> predicate) - where TValue : class - => await maybe.Match(predicate, false); - - /// - /// Execute the action. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ref readonly Maybe Execute(in this Maybe maybe, Action> action) - where TValue : class - { - action(maybe); - return ref maybe; - } - - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> Execute(this Maybe maybe, Func, Task> action) - where TValue : class - { - await action(maybe); - return maybe; - } - - /// - /// Execute the action if the is Some. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ref readonly Maybe ExecuteIfSome(in this Maybe maybe, Action action) - where TValue : class - { - if (maybe.IsSome) action(); - return ref maybe; - } - - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> ExecuteIfSome(this Maybe maybe, Func action) - where TNewValue : class - { - if (maybe.IsSome) await action(); - return maybe; - } - - /// - /// Execute the action if the is None. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ref readonly Maybe ExecuteIfNone(in this Maybe maybe, Action action) - where TNewValue : class - { - if (maybe.IsNone) action(); - return ref maybe; - } - - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> ExecuteIfNone(this Maybe maybe, Func action) - where TNewValue : class - { - if (maybe.IsNone) await action(); - return maybe; - } - - /// Map a default value if the current is None. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Maybe WithDefault(this Maybe maybe, TNewValue value) - where TNewValue : class - => maybe.IsSome ? maybe : new(value); - - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Maybe WithDefault(this Maybe maybe, Func value) - where TNewValue : class - => maybe.IsSome ? maybe : new(value()); - - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> WithDefault( - this Maybe maybe, Func> value) where TNewValue : class - => maybe.IsSome ? maybe : new(await value()); - - /// - /// Convert a to a with a default error in case of None. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Result ToResult(this Maybe maybe, Func errorFunc) - where TValue : class - => maybe.Match( - value => Result.Success(value), - () => Result.Failure(errorFunc()) - ); - - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Task> ToResult(this Maybe maybe, Func> errorFunc) - where TValue : class - => maybe.Match( - value => Result.Success(value), - async () => Result.Failure(await errorFunc()) - ); + /// + /// Map the value to a new one. + /// + public static Maybe Map(this Maybe maybe, TNewValue? value) + where TNewValue : class where TValue : class + => maybe.IsSome ? new(value) : Maybe.None; + + /// + public static Maybe Map(this Maybe maybe, Func map) + where TNewValue : class where TValue : class + => maybe.IsSome ? new(map()) : Maybe.None; + + /// + public static async Task> Map( + this Maybe maybe, Func> map) + where TNewValue : class where TValue : class + => maybe.IsSome ? new(await map()) : Maybe.None; + + /// + /// Bind the maybe and, possibly, to a new one. + /// + public static Maybe Bind(this Maybe maybe, Func> map) + where TNewValue : class where TValue : class + => maybe.IsSome ? map() : Maybe.None; + + /// + public static Task> Bind( + this Maybe maybe, Func>> map) + where TNewValue : class where TValue : class + => maybe.IsSome ? map() : Task.FromResult(Maybe.None); + + /// + /// Maps a new value for both state of a + /// + public static TResult Match(this Maybe maybe, TResult resultOnValue, TResult resultOnNone) + where TValue : class + => maybe.IsSome ? resultOnValue : resultOnNone; + + /// + public static TResult Match( + this Maybe maybe, Func resultOnValue, TResult resultOnNone) + where TValue : class + => maybe.IsSome ? resultOnValue() : resultOnNone; + + /// + public static TResult Match( + this Maybe maybe, TResult resultOnValue, Func resultOnNone) + where TValue : class + => maybe.IsSome ? resultOnValue : resultOnNone(); + + /// + public static TResult Match( + this Maybe maybe, Func resultOnValue, Func resultOnNone) + where TValue : class + => maybe.IsSome ? resultOnValue() : resultOnNone(); + + /// + public static Task Match( + this Maybe maybe, Func> resultOnValue, TResult resultOnNone) + where TValue : class + => maybe.IsSome ? resultOnValue() : Task.FromResult(resultOnNone); + + /// + public static Task Match( + this Maybe maybe, TResult resultOnValue, Func> resultOnNone) + where TValue : class + => maybe.IsSome ? Task.FromResult(resultOnValue) : resultOnNone(); + + /// + public static Task Match( + this Maybe maybe, Func> resultOnValue, Func> resultOnNone) + where TValue : class + => maybe.IsSome ? resultOnValue() : resultOnNone(); + + /// + /// Returns a with Some(first) in case of non empty list. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Maybe ToMaybe(this IEnumerable? values) where TValue : class + => values is not null && values.Any() + ? Maybe.Some(values.First()) + : Maybe.None(); + + /// + /// Returns the original Some if predicate is satisfied, None otherwise. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Maybe Where(this TValue? obj, Func predicate) where TValue : class + => obj is not null && predicate(obj) + ? Maybe.Some(obj) + : Maybe.None(); + + /// + /// Returns the original Some if predicate is not satisfied, None otherwise. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Maybe WhereNot(this TValue? obj, Func predicate) where TValue : class + => obj is not null && !predicate(obj) + ? Maybe.Some(obj) + : Maybe.None(); + + /// + /// Evaluate the predicate applied to the value if present. + /// Return false in case of None. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool Satisfy(this Maybe maybe, Func predicate) where TValue : class + => maybe.Match(predicate, false); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task Satisfy(this Maybe maybe, Func> predicate) + where TValue : class + => await maybe.Match(predicate, false); + + /// + /// Execute the action. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ref readonly Maybe Execute(in this Maybe maybe, Action> action) + where TValue : class + { + action(maybe); + return ref maybe; + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> Execute(this Maybe maybe, Func, Task> action) + where TValue : class + { + await action(maybe); + return maybe; + } + + /// + /// Execute the action if the is Some. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ref readonly Maybe ExecuteIfSome(in this Maybe maybe, Action action) + where TValue : class + { + if (maybe.IsSome) action(); + return ref maybe; + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> ExecuteIfSome(this Maybe maybe, Func action) + where TNewValue : class + { + if (maybe.IsSome) await action(); + return maybe; + } + + /// + /// Execute the action if the is None. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ref readonly Maybe ExecuteIfNone(in this Maybe maybe, Action action) + where TNewValue : class + { + if (maybe.IsNone) action(); + return ref maybe; + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> ExecuteIfNone(this Maybe maybe, Func action) + where TNewValue : class + { + if (maybe.IsNone) await action(); + return maybe; + } + + /// Map a default value if the current is None. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Maybe WithDefault(this Maybe maybe, TNewValue value) + where TNewValue : class + => maybe.IsSome ? maybe : new(value); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Maybe WithDefault(this Maybe maybe, Func value) + where TNewValue : class + => maybe.IsSome ? maybe : new(value()); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> WithDefault( + this Maybe maybe, Func> value) where TNewValue : class + => maybe.IsSome ? maybe : new(await value()); + + /// + /// Convert a to a with a default error in case of None. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Result ToResult(this Maybe maybe, Func errorFunc) + where TValue : class + => maybe.Match( + value => Result.Success(value), + () => Result.Failure(errorFunc()) + ); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Task> ToResult(this Maybe maybe, Func> errorFunc) + where TValue : class + => maybe.Match( + value => Result.Success(value), + async () => Result.Failure(await errorFunc()) + ); } \ No newline at end of file diff --git a/src/Monads/Result/IResult.cs b/src/Monads/Result/IResult.cs index dabcc70..6ba94b9 100644 --- a/src/Monads/Result/IResult.cs +++ b/src/Monads/Result/IResult.cs @@ -5,12 +5,12 @@ namespace Bogoware.Monads; public interface IResult { - bool IsSuccess { get; } - bool IsFailure { get; } - public Error GetErrorOrThrow(); + bool IsSuccess { get; } + bool IsFailure { get; } + public Error GetErrorOrThrow(); } public interface IResult : IResult { - //public TValue GetValueOrThrow(); + //public TValue GetValueOrThrow(); } \ No newline at end of file diff --git a/src/Monads/Result/Result.cs b/src/Monads/Result/Result.cs index e469edc..6d5da62 100644 --- a/src/Monads/Result/Result.cs +++ b/src/Monads/Result/Result.cs @@ -322,7 +322,7 @@ public Result RecoverWith(TValue newValue) => IsSuccess ? this : newValue; public Result RecoverWith(Func functor) - => IsSuccess ? this: functor(); + => IsSuccess ? this : functor(); public Result RecoverWith(Func functor) => IsSuccess ? this : functor(Error!); diff --git a/src/Monads/Result/ResultBindAsyncExtensions.cs b/src/Monads/Result/ResultBindAsyncExtensions.cs index 9472d73..c35256d 100644 --- a/src/Monads/Result/ResultBindAsyncExtensions.cs +++ b/src/Monads/Result/ResultBindAsyncExtensions.cs @@ -6,28 +6,28 @@ namespace Bogoware.Monads; public static class ResultBindAsyncExtensions { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> Bind( - this Task> result, Result newValue) - => (await result).Bind(newValue); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> Bind( + this Task> result, Result newValue) + => (await result).Bind(newValue); - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> Bind( - this Task> result, Func> functor) - => (await result).Bind(functor); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> Bind( + this Task> result, Func> functor) + => (await result).Bind(functor); - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task>Bind( - this Task> result, Func>> functor) - => await (await result).Bind(functor); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> Bind( + this Task> result, Func>> functor) + => await (await result).Bind(functor); - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task>Bind( - this Task> result, Func> functor) - => (await result).Bind(functor); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> Bind( + this Task> result, Func> functor) + => (await result).Bind(functor); - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task>Bind( - this Task> result, Func>> functor) - => await (await result).Bind(functor); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> Bind( + this Task> result, Func>> functor) + => await (await result).Bind(functor); } \ No newline at end of file diff --git a/src/Monads/Result/ResultCollection.cs b/src/Monads/Result/ResultCollection.cs index 9e85e40..3a88115 100644 --- a/src/Monads/Result/ResultCollection.cs +++ b/src/Monads/Result/ResultCollection.cs @@ -5,30 +5,30 @@ namespace Bogoware.Monads; /// internal class ResultCollection { - public bool IsSuccess { get; } - public bool IsFailure => !IsSuccess; - public Error GetErrorOrThrow() => _error ?? throw new ResultSuccessException(); + public bool IsSuccess { get; } + public bool IsFailure => !IsSuccess; + public Error GetErrorOrThrow() => _error ?? throw new ResultSuccessException(); - private readonly List> _results; - private readonly AggregateError? _error; + private readonly List> _results; + private readonly AggregateError? _error; - internal ResultCollection(IEnumerable> results) - { - _results = [..results]; - IsSuccess = _results.Count == 0 - || _results.All(r => r.IsSuccess); - - if (IsSuccess) return; - - var errors = _results.Where(r => r.IsFailure).Select(r => r.GetErrorOrThrow()); - _error = new (errors); - } + internal ResultCollection(IEnumerable> results) + { + _results = [.. results]; + IsSuccess = _results.Count == 0 + || _results.All(r => r.IsSuccess); - internal Result> ToResult() - { - if (IsFailure) return Result.Failure>(_error!); - if (_results.Count == 0) return Result.Success(Enumerable.Empty()); - var values = _results.Select(r => r.Value); - return Result.Success(values); - } + if (IsSuccess) return; + + var errors = _results.Where(r => r.IsFailure).Select(r => r.GetErrorOrThrow()); + _error = new(errors); + } + + internal Result> ToResult() + { + if (IsFailure) return Result.Failure>(_error!); + if (_results.Count == 0) return Result.Success(Enumerable.Empty()); + var values = _results.Select(r => r.Value); + return Result.Success(values); + } } \ No newline at end of file diff --git a/src/Monads/Result/ResultEnsureExtensions.cs b/src/Monads/Result/ResultEnsureExtensions.cs index 572f4d1..60bf4f0 100644 --- a/src/Monads/Result/ResultEnsureExtensions.cs +++ b/src/Monads/Result/ResultEnsureExtensions.cs @@ -5,65 +5,65 @@ namespace Bogoware.Monads; public static class ResultEnsureExtensions { - #region Functional Closure Extensions + #region Functional Closure Extensions - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Result Ensure( - this Result result, Func predicate, Func error) - where TError : Error - => result.Ensure(predicate, error()); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Result Ensure( + this Result result, Func predicate, Func error) + where TError : Error + => result.Ensure(predicate, error()); - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> Ensure( - this Result result, Func predicate, Func> error) - where TError : Error - => result.Ensure(predicate, await error()); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> Ensure( + this Result result, Func predicate, Func> error) + where TError : Error + => result.Ensure(predicate, await error()); - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Task> Ensure( - this Result result, Func> predicate, Func error) - where TError : Error - => result.Ensure(predicate, error()); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Task> Ensure( + this Result result, Func> predicate, Func error) + where TError : Error + => result.Ensure(predicate, error()); - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> Ensure( - this Result result, Func> predicate, Func> error) - where TError : Error - => await result.Ensure(predicate, await error()); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> Ensure( + this Result result, Func> predicate, Func> error) + where TError : Error + => await result.Ensure(predicate, await error()); - #endregion Functional Closure Extensions + #endregion Functional Closure Extensions - #region Left Async Extensions + #region Left Async Extensions - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> Ensure( - this Task> result, Func predicate, Error error) - => (await result).Ensure(predicate, error); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> Ensure( + this Task> result, Func predicate, Error error) + => (await result).Ensure(predicate, error); - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> RecoverWith( - this Task> result, Func> predicate, Error error) - => await (await result).Ensure(predicate, error); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> RecoverWith( + this Task> result, Func> predicate, Error error) + => await (await result).Ensure(predicate, error); - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> Ensure( - this Task> result, Func predicate, Func error) - => (await result).Ensure(predicate, error()); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> Ensure( + this Task> result, Func predicate, Func error) + => (await result).Ensure(predicate, error()); - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> Ensure( - this Task> result, Func predicate, Func> error) - => (await result).Ensure(predicate, await error()); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> Ensure( + this Task> result, Func predicate, Func> error) + => (await result).Ensure(predicate, await error()); - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> Ensure( - this Task> result, Func> predicate, Func error) - => await (await result).Ensure(predicate, error()); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> Ensure( + this Task> result, Func> predicate, Func error) + => await (await result).Ensure(predicate, error()); - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> Ensure( - this Task> result, Func> predicate, Func> error) - => await (await result).Ensure(predicate, await error()); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> Ensure( + this Task> result, Func> predicate, Func> error) + => await (await result).Ensure(predicate, await error()); - #endregion Left Async Extensions + #endregion Left Async Extensions } \ No newline at end of file diff --git a/src/Monads/Result/ResultEnumerableExtensions.Filters.cs b/src/Monads/Result/ResultEnumerableExtensions.Filters.cs index bfdee8f..2c1b629 100644 --- a/src/Monads/Result/ResultEnumerableExtensions.Filters.cs +++ b/src/Monads/Result/ResultEnumerableExtensions.Filters.cs @@ -5,26 +5,26 @@ namespace Bogoware.Monads; public static partial class ResultEnumerableExtensions { - /// - /// Filters Successes via the predicate. - /// Failures are discarded. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static IEnumerable> Where( - this IEnumerable> successes, Func predicate) - => successes.SelectValues() - .Where(predicate) - .Select(v => new Result(v)); + /// + /// Filters Successes via the predicate. + /// Failures are discarded. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static IEnumerable> Where( + this IEnumerable> successes, Func predicate) + => successes.SelectValues() + .Where(predicate) + .Select(v => new Result(v)); + + /// + /// Filters Successes via negated predicate. + /// Failures are discarded. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static IEnumerable> WhereNot( + this IEnumerable> successes, Func predicate) + => successes.SelectValues() + .Where(v => !predicate(v)) + .Select(v => new Result(v)); - /// - /// Filters Successes via negated predicate. - /// Failures are discarded. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static IEnumerable> WhereNot( - this IEnumerable> successes, Func predicate) - => successes.SelectValues() - .Where(v => !predicate(v)) - .Select(v => new Result(v)); - } \ No newline at end of file diff --git a/src/Monads/Result/ResultEnumerableExtensions.Predicates.cs b/src/Monads/Result/ResultEnumerableExtensions.Predicates.cs index 3384cb4..e4aa6fc 100644 --- a/src/Monads/Result/ResultEnumerableExtensions.Predicates.cs +++ b/src/Monads/Result/ResultEnumerableExtensions.Predicates.cs @@ -6,52 +6,51 @@ namespace Bogoware.Monads; public static partial class ResultEnumerableExtensions { - /// - /// Determines if all s of a sequence are Successs. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool AllSuccess(this IEnumerable successes) - => successes.All(r => r.IsSuccess); - - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool AllSuccess(this IEnumerable> successes) - => successes.All(v => v.IsSuccess); - - /// - /// Determines if all s of a sequence are Failures. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool AllFailure(this IEnumerable successes) - => successes.All(r => r.IsFailure); - - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool AllFailure(this IEnumerable> successes) - => successes.All(v => v.IsFailure); - - /// - /// Determines if any of a sequence is Success. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool AnySuccess(this IEnumerable successes) - => successes.Any(r => r.IsSuccess); - - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool AnySuccess(this IEnumerable> successes) - => successes.Any(v => v.IsSuccess); - - /// - /// Determines if any of a sequence is Failure. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool AnyFailure(this IEnumerable successes) - => successes.Any(r => r.IsFailure); - - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool AnyFailure(this IEnumerable> successes) - => successes.Any(v => v.IsFailure); - + /// + /// Determines if all s of a sequence are Successs. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool AllSuccess(this IEnumerable successes) + => successes.All(r => r.IsSuccess); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool AllSuccess(this IEnumerable> successes) + => successes.All(v => v.IsSuccess); + + /// + /// Determines if all s of a sequence are Failures. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool AllFailure(this IEnumerable successes) + => successes.All(r => r.IsFailure); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool AllFailure(this IEnumerable> successes) + => successes.All(v => v.IsFailure); + + /// + /// Determines if any of a sequence is Success. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool AnySuccess(this IEnumerable successes) + => successes.Any(r => r.IsSuccess); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool AnySuccess(this IEnumerable> successes) + => successes.Any(v => v.IsSuccess); + + /// + /// Determines if any of a sequence is Failure. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool AnyFailure(this IEnumerable successes) + => successes.Any(r => r.IsFailure); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool AnyFailure(this IEnumerable> successes) + => successes.Any(v => v.IsFailure); } \ No newline at end of file diff --git a/src/Monads/Result/ResultEnumerableExtensions.SelectValues.cs b/src/Monads/Result/ResultEnumerableExtensions.SelectValues.cs index 957e201..fca2811 100644 --- a/src/Monads/Result/ResultEnumerableExtensions.SelectValues.cs +++ b/src/Monads/Result/ResultEnumerableExtensions.SelectValues.cs @@ -5,57 +5,57 @@ namespace Bogoware.Monads; public static partial class ResultEnumerableExtensions { - /// - /// Extract values from s. - /// Failures are discarded. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static IEnumerable SelectValues(this IEnumerable> successes) - => successes.SelectMany(v => v); - - /// - /// Maps values via the functor. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static IEnumerable> MapEach( - this IEnumerable> results, Func functor) - => results.Select(result => result.Map(functor)); - - /// - /// Bind values via the functor. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static IEnumerable> BindEach( - this IEnumerable> results, Func> functor) - => results.Select(result => result.Bind(functor)); - - /// - /// Matches results. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static IEnumerable MatchEach( - this IEnumerable> results, - Func mapSuccesses, - Func mapFailures) - => results.Select(result => result.Match(mapSuccesses, mapFailures)); - - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static IEnumerable MatchEach( - this IEnumerable> results, - Func mapSuccesses, - TResult failure) - => results.Select(result => result.Match(mapSuccesses, failure)); - - /// - /// Aggregates an enumeration of Result into a Result of an enumeration. - /// If all s are Success then return a Success . - /// otherwise return a Failure with an . - /// - /// - /// - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Result> AggregateResults(this IEnumerable> results) - => new ResultCollection(results).ToResult(); + /// + /// Extract values from s. + /// Failures are discarded. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static IEnumerable SelectValues(this IEnumerable> successes) + => successes.SelectMany(v => v); + + /// + /// Maps values via the functor. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static IEnumerable> MapEach( + this IEnumerable> results, Func functor) + => results.Select(result => result.Map(functor)); + + /// + /// Bind values via the functor. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static IEnumerable> BindEach( + this IEnumerable> results, Func> functor) + => results.Select(result => result.Bind(functor)); + + /// + /// Matches results. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static IEnumerable MatchEach( + this IEnumerable> results, + Func mapSuccesses, + Func mapFailures) + => results.Select(result => result.Match(mapSuccesses, mapFailures)); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static IEnumerable MatchEach( + this IEnumerable> results, + Func mapSuccesses, + TResult failure) + => results.Select(result => result.Match(mapSuccesses, failure)); + + /// + /// Aggregates an enumeration of Result into a Result of an enumeration. + /// If all s are Success then return a Success . + /// otherwise return a Failure with an . + /// + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Result> AggregateResults(this IEnumerable> results) + => new ResultCollection(results).ToResult(); } \ No newline at end of file diff --git a/src/Monads/Result/ResultExecuteExtensions.cs b/src/Monads/Result/ResultExecuteExtensions.cs index 8d57150..b587d95 100644 --- a/src/Monads/Result/ResultExecuteExtensions.cs +++ b/src/Monads/Result/ResultExecuteExtensions.cs @@ -8,142 +8,142 @@ namespace Bogoware.Monads; public static class ResultExecuteExtensions { - #region Functional Closure Extensions - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Result ExecuteIfSuccess( - this Result result, Action action) - { - if (result.IsSuccess) action(); - return result; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> ExecuteIfSuccess( - this Result result, Func action) - { - if (result.IsSuccess) await action(); - return result; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Result ExecuteIfFailure( - this Result result, Action action) - { - if (result.IsFailure) action(); - return result; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> ExecuteIfFailure( - this Result result, Func action) - { - if (result.IsFailure) await action(); - return result; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Result Execute(this Result result, Action action) - { - action(); - return result; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> Execute( - this Result result, Func action) - { - await action(); - return result; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Result Execute( - this Result result, Action> action) - { - action(result); - return result; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> Execute( - this Result result, Func, Task> action) - { - await action(result); - return result; - } - - #endregion Functional Closure Extensions - - #region Left Async Extensions - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> ExecuteIfSuccess( - this Task> result, Action action) - => (await result).ExecuteIfSuccess(action); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> ExecuteIfSuccess( - this Task> result, Func action) - => await (await result).ExecuteIfSuccess(action); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> ExecuteIfSuccess( - this Task> result, Action action) - => (await result).ExecuteIfSuccess(action); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> ExecuteIfSuccess( - this Task> result, Func action) - => await (await result).ExecuteIfSuccess(action); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> ExecuteIfFailure( - this Task> result, Action action) - => (await result).ExecuteIfFailure(action); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> ExecuteIfFailure( - this Task> result, Func action) - => await (await result).ExecuteIfFailure(action); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> ExecuteIfFailure( - this Task> result, Action action) - => (await result).ExecuteIfFailure(action); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> ExecuteIfFailure( - this Task> result, Func action) - => await (await result).ExecuteIfFailure(action); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> Execute( - this Task> result, Action action) - => (await result).Execute(action); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> Execute( - this Task> result, Func action) - => await (await result).Execute(action); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> Execute( - this Task> resultTask, Action> action) - { - var result = await resultTask; - action(result); - return result; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> Execute( - this Task> resultTask, Func, Task> action) - { - var result = await resultTask; - await action(result); - return result; - } - - #endregion Left Async Extensions + #region Functional Closure Extensions + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Result ExecuteIfSuccess( + this Result result, Action action) + { + if (result.IsSuccess) action(); + return result; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> ExecuteIfSuccess( + this Result result, Func action) + { + if (result.IsSuccess) await action(); + return result; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Result ExecuteIfFailure( + this Result result, Action action) + { + if (result.IsFailure) action(); + return result; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> ExecuteIfFailure( + this Result result, Func action) + { + if (result.IsFailure) await action(); + return result; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Result Execute(this Result result, Action action) + { + action(); + return result; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> Execute( + this Result result, Func action) + { + await action(); + return result; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Result Execute( + this Result result, Action> action) + { + action(result); + return result; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> Execute( + this Result result, Func, Task> action) + { + await action(result); + return result; + } + + #endregion Functional Closure Extensions + + #region Left Async Extensions + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> ExecuteIfSuccess( + this Task> result, Action action) + => (await result).ExecuteIfSuccess(action); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> ExecuteIfSuccess( + this Task> result, Func action) + => await (await result).ExecuteIfSuccess(action); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> ExecuteIfSuccess( + this Task> result, Action action) + => (await result).ExecuteIfSuccess(action); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> ExecuteIfSuccess( + this Task> result, Func action) + => await (await result).ExecuteIfSuccess(action); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> ExecuteIfFailure( + this Task> result, Action action) + => (await result).ExecuteIfFailure(action); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> ExecuteIfFailure( + this Task> result, Func action) + => await (await result).ExecuteIfFailure(action); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> ExecuteIfFailure( + this Task> result, Action action) + => (await result).ExecuteIfFailure(action); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> ExecuteIfFailure( + this Task> result, Func action) + => await (await result).ExecuteIfFailure(action); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> Execute( + this Task> result, Action action) + => (await result).Execute(action); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> Execute( + this Task> result, Func action) + => await (await result).Execute(action); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> Execute( + this Task> resultTask, Action> action) + { + var result = await resultTask; + action(result); + return result; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> Execute( + this Task> resultTask, Func, Task> action) + { + var result = await resultTask; + await action(result); + return result; + } + + #endregion Left Async Extensions } \ No newline at end of file diff --git a/src/Monads/Result/ResultMapErrorAsyncExtensions.cs b/src/Monads/Result/ResultMapErrorAsyncExtensions.cs index e55a5b9..4f0a849 100644 --- a/src/Monads/Result/ResultMapErrorAsyncExtensions.cs +++ b/src/Monads/Result/ResultMapErrorAsyncExtensions.cs @@ -4,29 +4,29 @@ namespace Bogoware.Monads; public static class ResultMapErrorAsyncExtensions { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> MapError( - this Task> result, Error newError) - => (await result).MapError(newError); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> MapError( + this Task> result, Error newError) + => (await result).MapError(newError); - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> Map( - this Task> result, Func functor) - => (await result).MapError(functor); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> Map( + this Task> result, Func functor) + => (await result).MapError(functor); - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> Map( - this Task> result, Func> functor) - => await (await result).MapError(functor); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> Map( + this Task> result, Func> functor) + => await (await result).MapError(functor); - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> Map( - this Task> result, Func functor) - => (await result).MapError(functor); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> Map( + this Task> result, Func functor) + => (await result).MapError(functor); - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> Map( - this Task> result, - Func> functor) - => await (await result).MapError(functor); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> Map( + this Task> result, + Func> functor) + => await (await result).MapError(functor); } \ No newline at end of file diff --git a/src/Monads/Result/ResultMapExtensions.cs b/src/Monads/Result/ResultMapExtensions.cs index 492e504..e73fe1d 100644 --- a/src/Monads/Result/ResultMapExtensions.cs +++ b/src/Monads/Result/ResultMapExtensions.cs @@ -6,62 +6,62 @@ namespace Bogoware.Monads; public static class ResultMapExtensions { - /* + /* [MethodImpl(MethodImplOptions.AggressiveInlining)] public static async Task> Map( this Task> result, TNewValue newValue) => (await result).Map(newValue); */ - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Result MapToUnit(this Result result) - => result.Map(_ => { }); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> MapToUnit(this Task> result) - => (await result).Map(_ => { }); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Result MapToUnit(this Result result) + => result.Map(_ => { }); - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> Map( - this Task> result, Func functor) - => (await result).Map(functor); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> MapToUnit(this Task> result) + => (await result).Map(_ => { }); - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> Map( - this Task> result, Func> functor) - => await (await result).Map(functor); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> Map( + this Task> result, Func functor) + => (await result).Map(functor); - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> Map( - this Task> result, Func functor) - => (await result).Map(functor); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> Map( + this Task> result, Func> functor) + => await (await result).Map(functor); - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> Map( - this Task> result, - Func> functor) - => await (await result).Map(functor); - - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> Map( - this Task> resultTask, - Action functor) - { - var result = await resultTask; - if (result.IsFailure) return Result.Failure(result.GetErrorOrThrow()); - functor(result.Value!); - return Result.Unit; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> Map( - this Task> resultTask, - Func functor) - { - var result = await resultTask; - if (result.IsFailure) return Result.Failure(result.GetErrorOrThrow()); - await functor(result.Value!); - return Result.Unit; - } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> Map( + this Task> result, Func functor) + => (await result).Map(functor); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> Map( + this Task> result, + Func> functor) + => await (await result).Map(functor); + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> Map( + this Task> resultTask, + Action functor) + { + var result = await resultTask; + if (result.IsFailure) return Result.Failure(result.GetErrorOrThrow()); + functor(result.Value!); + return Result.Unit; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> Map( + this Task> resultTask, + Func functor) + { + var result = await resultTask; + if (result.IsFailure) return Result.Failure(result.GetErrorOrThrow()); + await functor(result.Value!); + return Result.Unit; + } } \ No newline at end of file diff --git a/src/Monads/Result/ResultMatchAsyncExtensions.cs b/src/Monads/Result/ResultMatchAsyncExtensions.cs index 87fe221..be0c80e 100644 --- a/src/Monads/Result/ResultMatchAsyncExtensions.cs +++ b/src/Monads/Result/ResultMatchAsyncExtensions.cs @@ -6,84 +6,84 @@ namespace Bogoware.Monads; public static class ResultMatchAsyncExtensions { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task Match( - this Task> result, Func successful, Func failure) - => (await result).Match(successful, failure); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task Match( - this Task> result, Func> successful, Func failure) - => await (await result).Match(successful, failure); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task Match( - this Task> result, Func successful, Func> failure) - => await (await result).Match(successful, failure); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task Match( - this Task> result, Func> successful, - Func> failure) - => await (await result).Match(successful, failure); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task Match( - this Task> result, TResult successful, TResult failure) - => (await result).Match(successful, failure); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task Match( - this Task> result, Func successful, TResult failure) - => (await result).Match(successful, failure); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task Match( - this Task> result, Func> successful, TResult failure) - => await (await result).Match(successful, failure); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task Match( - this Task> result, TResult successful, Func failure) - => (await result).Match(successful, failure); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task Match( - this Task> result, TResult successful, Func> failure) - => await (await result).Match(successful, failure); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task Match( - this Task> result, Func successful, Func failure) - => (await result).Match(successful, failure); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task Match( - this Task> result, Func successful, TResult failure) - => (await result).Match(successful, failure); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task Match( - this Task> result, Func successful, Func failure) - => (await result).Match(successful, failure); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task Match( - this Task> result, TResult successful, Func> failure) - => await (await result).Match(successful, failure); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task Match( - this Task> result, Func successful, Func> failure) - => await (await result).Match(successful, failure); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task Match( - this Task> result, Func> successful, TResult failure) - => await (await result).Match(successful, failure); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task Match( - this Task> result, Func> successful, Func failure) - => await (await result).Match(successful, failure); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task Match( + this Task> result, Func successful, Func failure) + => (await result).Match(successful, failure); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task Match( + this Task> result, Func> successful, Func failure) + => await (await result).Match(successful, failure); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task Match( + this Task> result, Func successful, Func> failure) + => await (await result).Match(successful, failure); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task Match( + this Task> result, Func> successful, + Func> failure) + => await (await result).Match(successful, failure); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task Match( + this Task> result, TResult successful, TResult failure) + => (await result).Match(successful, failure); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task Match( + this Task> result, Func successful, TResult failure) + => (await result).Match(successful, failure); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task Match( + this Task> result, Func> successful, TResult failure) + => await (await result).Match(successful, failure); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task Match( + this Task> result, TResult successful, Func failure) + => (await result).Match(successful, failure); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task Match( + this Task> result, TResult successful, Func> failure) + => await (await result).Match(successful, failure); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task Match( + this Task> result, Func successful, Func failure) + => (await result).Match(successful, failure); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task Match( + this Task> result, Func successful, TResult failure) + => (await result).Match(successful, failure); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task Match( + this Task> result, Func successful, Func failure) + => (await result).Match(successful, failure); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task Match( + this Task> result, TResult successful, Func> failure) + => await (await result).Match(successful, failure); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task Match( + this Task> result, Func successful, Func> failure) + => await (await result).Match(successful, failure); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task Match( + this Task> result, Func> successful, TResult failure) + => await (await result).Match(successful, failure); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task Match( + this Task> result, Func> successful, Func failure) + => await (await result).Match(successful, failure); } \ No newline at end of file diff --git a/src/Monads/Result/ResultMatchExtensions.cs b/src/Monads/Result/ResultMatchExtensions.cs index 934ddd4..23d0066 100644 --- a/src/Monads/Result/ResultMatchExtensions.cs +++ b/src/Monads/Result/ResultMatchExtensions.cs @@ -5,92 +5,92 @@ namespace Bogoware.Monads; public static class ResultMatchExtensions { - #region Match Functional Closure - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static TResult Match( - this Result result, TResult successful, TResult failure) - => result.IsSuccess ? successful : failure; - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static TResult Match( - this Result result, Func successful, TResult failure) - => result.IsSuccess ? successful() : failure; - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Task Match( - this Result result, Func> successful, TResult failure) - => result.IsSuccess ? successful() : Task.FromResult(failure); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static TResult Match( - this Result result, TResult successful, Func failure) - => result.IsSuccess ? successful : failure(); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Task Match( - this Result result, TResult successful, Func> failure) - => result.IsSuccess ? Task.FromResult(successful) : failure(); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static TResult Match( - this Result result, Func successful, Func failure) - => result.IsSuccess ? successful() : failure(); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static TResult Match( - this Result result, Func successful, TResult failure) - => result.Match(successful, _ => failure); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static TResult Match( - this Result result, Func successful, Func failure) - => result.Match(successful, _ => failure()); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task Match( - this Result result, Func successful, Func> failure) - => await result.Match(successful, _ => failure()); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Task Match( - this Result result, TResult successful, Func> failure) - => result.Match(_ => successful, failure); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Task Match( - this Result result, Func successful, Func> failure) - => result.Match(_ => successful(), failure); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Task Match( - this Result result, Func> successful, TResult failure) - => result.Match(successful, _ => failure); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Task Match( - this Result result, Func> successful, Func failure) - => result.Match(successful, _ => failure()); - #endregion Match Functional Closure - - #region Utils based on Match - /// - /// Retrieve the value if or return the recoverValue if . - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static TValue GetValue(this Result result, TValue recoverValue) - => result.Match(successful => successful, recoverValue); - - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static TValue GetValue( - this Result result, Func recoverValue) - => result.Match(successful => successful, recoverValue); - - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Task GetValue( - this Result result, Func> recoverValue) - => result.Match(successful => successful, recoverValue); - - #endregion Utils based on Match + #region Match Functional Closure + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static TResult Match( + this Result result, TResult successful, TResult failure) + => result.IsSuccess ? successful : failure; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static TResult Match( + this Result result, Func successful, TResult failure) + => result.IsSuccess ? successful() : failure; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Task Match( + this Result result, Func> successful, TResult failure) + => result.IsSuccess ? successful() : Task.FromResult(failure); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static TResult Match( + this Result result, TResult successful, Func failure) + => result.IsSuccess ? successful : failure(); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Task Match( + this Result result, TResult successful, Func> failure) + => result.IsSuccess ? Task.FromResult(successful) : failure(); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static TResult Match( + this Result result, Func successful, Func failure) + => result.IsSuccess ? successful() : failure(); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static TResult Match( + this Result result, Func successful, TResult failure) + => result.Match(successful, _ => failure); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static TResult Match( + this Result result, Func successful, Func failure) + => result.Match(successful, _ => failure()); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task Match( + this Result result, Func successful, Func> failure) + => await result.Match(successful, _ => failure()); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Task Match( + this Result result, TResult successful, Func> failure) + => result.Match(_ => successful, failure); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Task Match( + this Result result, Func successful, Func> failure) + => result.Match(_ => successful(), failure); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Task Match( + this Result result, Func> successful, TResult failure) + => result.Match(successful, _ => failure); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Task Match( + this Result result, Func> successful, Func failure) + => result.Match(successful, _ => failure()); + #endregion Match Functional Closure + + #region Utils based on Match + /// + /// Retrieve the value if or return the recoverValue if . + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static TValue GetValue(this Result result, TValue recoverValue) + => result.Match(successful => successful, recoverValue); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static TValue GetValue( + this Result result, Func recoverValue) + => result.Match(successful => successful, recoverValue); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Task GetValue( + this Result result, Func> recoverValue) + => result.Match(successful => successful, recoverValue); + + #endregion Utils based on Match } \ No newline at end of file diff --git a/src/Monads/Result/ResultRecoverWithExtensions.cs b/src/Monads/Result/ResultRecoverWithExtensions.cs index 0dce917..d1fa294 100644 --- a/src/Monads/Result/ResultRecoverWithExtensions.cs +++ b/src/Monads/Result/ResultRecoverWithExtensions.cs @@ -7,54 +7,54 @@ namespace Bogoware.Monads; public static class ResultRecoverWithExtensions { - #region Functional Closure Extensions - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Result RecoverWith( - this Result result, TValue newValue) - where TError : Error - => result.IsSuccess ? result : new(newValue); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Result RecoverWith( - this Result result, Func functor) - where TError : Error - => result.IsSuccess ? result : new(functor()); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> RecoverWith( - this Result result, Func> functor) - where TError : Error - => result.IsSuccess ? result : new(await functor()); - - #endregion Functional Closure Extensions - - #region Left Async Extensions - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> RecoverWith( - this Task> result, Func functor) - => (await result).RecoverWith(functor); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> RecoverWith( - this Task> result, Func> functor) - => await (await result).RecoverWith(functor); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> RecoverWith( - this Task> result, TValue newValue) - => (await result).RecoverWith(newValue); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> RecoverWith( - this Task> result, Func functor) - => (await result).RecoverWith(functor); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task> RecoverWith( - this Task> result, Func> functor) - => await (await result).RecoverWith(functor); - - #endregion Left Async Extensions + #region Functional Closure Extensions + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Result RecoverWith( + this Result result, TValue newValue) + where TError : Error + => result.IsSuccess ? result : new(newValue); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Result RecoverWith( + this Result result, Func functor) + where TError : Error + => result.IsSuccess ? result : new(functor()); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> RecoverWith( + this Result result, Func> functor) + where TError : Error + => result.IsSuccess ? result : new(await functor()); + + #endregion Functional Closure Extensions + + #region Left Async Extensions + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> RecoverWith( + this Task> result, Func functor) + => (await result).RecoverWith(functor); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> RecoverWith( + this Task> result, Func> functor) + => await (await result).RecoverWith(functor); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> RecoverWith( + this Task> result, TValue newValue) + => (await result).RecoverWith(newValue); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> RecoverWith( + this Task> result, Func functor) + => (await result).RecoverWith(functor); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task> RecoverWith( + this Task> result, Func> functor) + => await (await result).RecoverWith(functor); + + #endregion Left Async Extensions } \ No newline at end of file diff --git a/src/Monads/Result/ResultSatisfyExtensions.cs b/src/Monads/Result/ResultSatisfyExtensions.cs index 5b1cfec..665bd05 100644 --- a/src/Monads/Result/ResultSatisfyExtensions.cs +++ b/src/Monads/Result/ResultSatisfyExtensions.cs @@ -4,38 +4,38 @@ namespace Bogoware.Monads; public static class ResultSatisfyExtensions { - #region Functional Closure - - /// - /// Evaluate the predicate applied to the value if present. - /// Return false in case of None. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool Satisfy(this Result result, Func predicate) - where TValue : class - => result.Match(predicate, false); - - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Task Satisfy( - this Result result, Func> predicate) - where TValue : class - => result.Match(predicate, false); - - #endregion Functional Closure - - #region Left Async Closure - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Task Satisfy(this Task> result, Func predicate) - where TValue : class - => result.Match(predicate, false); - - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Task Satisfy( - this Task> maybe, Func> predicate) - where TValue : class - => maybe.Match(predicate, false); - - #endregion Left Async Closure + #region Functional Closure + + /// + /// Evaluate the predicate applied to the value if present. + /// Return false in case of None. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool Satisfy(this Result result, Func predicate) + where TValue : class + => result.Match(predicate, false); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Task Satisfy( + this Result result, Func> predicate) + where TValue : class + => result.Match(predicate, false); + + #endregion Functional Closure + + #region Left Async Closure + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Task Satisfy(this Task> result, Func predicate) + where TValue : class + => result.Match(predicate, false); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Task Satisfy( + this Task> maybe, Func> predicate) + where TValue : class + => maybe.Match(predicate, false); + + #endregion Left Async Closure } \ No newline at end of file diff --git a/src/Monads/Result/ResultThrowIfFailureExtensions.cs b/src/Monads/Result/ResultThrowIfFailureExtensions.cs index 266926d..8b66a09 100644 --- a/src/Monads/Result/ResultThrowIfFailureExtensions.cs +++ b/src/Monads/Result/ResultThrowIfFailureExtensions.cs @@ -4,20 +4,20 @@ namespace Bogoware.Monads; public static class ResultThrowIfFailureExtensions { - /// - /// Throws a if the is a Failure. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void ThrowIfFailure(this Result result) - { - if (result.IsFailure) throw new ResultFailedException(result.Error!); - } - - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static async Task ThrowIfFailure(this Task> resultTask) - { - var result = await resultTask; - if (result.IsFailure) throw new ResultFailedException(result.Error!); - } + /// + /// Throws a if the is a Failure. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void ThrowIfFailure(this Result result) + { + if (result.IsFailure) throw new ResultFailedException(result.Error!); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task ThrowIfFailure(this Task> resultTask) + { + var result = await resultTask; + if (result.IsFailure) throw new ResultFailedException(result.Error!); + } } \ No newline at end of file diff --git a/src/Monads/Unit.cs b/src/Monads/Unit.cs index 1abaa6b..a50775a 100644 --- a/src/Monads/Unit.cs +++ b/src/Monads/Unit.cs @@ -6,22 +6,22 @@ namespace Bogoware.Monads; /// /// The Unit type is used to represent the absence of a specific value /// -public sealed class Unit: IEquatable +public sealed class Unit : IEquatable { - public static readonly Unit Instance = new(); + public static readonly Unit Instance = new(); - private Unit() - { - } + private Unit() + { + } - public override bool Equals(object? obj) => obj is Unit; - public bool Equals(Unit? other) => other is not null; + public override bool Equals(object? obj) => obj is Unit; + public bool Equals(Unit? other) => other is not null; - public override int GetHashCode() => 0; + public override int GetHashCode() => 0; - public static bool operator ==(Unit? left, Unit? right) => true; + public static bool operator ==(Unit? left, Unit? right) => true; - public static bool operator !=(Unit? left, Unit? right) => false; + public static bool operator !=(Unit? left, Unit? right) => false; - public override string ToString() => nameof(Unit); + public override string ToString() => nameof(Unit); } \ No newline at end of file diff --git a/src/Monads/Utils/TypeHelper.cs b/src/Monads/Utils/TypeHelper.cs index 39b2568..5cdb5c3 100644 --- a/src/Monads/Utils/TypeHelper.cs +++ b/src/Monads/Utils/TypeHelper.cs @@ -3,19 +3,19 @@ namespace Bogoware.Monads; internal static class TypeHelper { - public static string GetFriendlyTypeName(this Type type) - { - if (type is null) throw new ArgumentNullException(nameof(type)); - - if (!type.IsGenericType) return type.Name; - var genericTypes = string.Join(",", - type.GetGenericArguments().Select(t => t.GetFriendlyTypeName()).ToArray()); - return $"{type.Name.Remove(type.Name.IndexOf('`'))}<{genericTypes}>"; + public static string GetFriendlyTypeName(this Type type) + { + if (type is null) throw new ArgumentNullException(nameof(type)); - } + if (!type.IsGenericType) return type.Name; + var genericTypes = string.Join(",", + type.GetGenericArguments().Select(t => t.GetFriendlyTypeName()).ToArray()); + return $"{type.Name.Remove(type.Name.IndexOf('`'))}<{genericTypes}>"; - public static string GetFriendlyTypeName(this object @object) - { - return @object.GetType().GetFriendlyTypeName(); - } + } + + public static string GetFriendlyTypeName(this object @object) + { + return @object.GetType().GetFriendlyTypeName(); + } } \ No newline at end of file diff --git a/test/Monads.UnitTests/Boilerplate/ICallInspector.cs b/test/Monads.UnitTests/Boilerplate/ICallInspector.cs index 3399edd..67f2073 100644 --- a/test/Monads.UnitTests/Boilerplate/ICallInspector.cs +++ b/test/Monads.UnitTests/Boilerplate/ICallInspector.cs @@ -2,14 +2,14 @@ namespace Bogoware.Monads.UnitTests.Boilerplate; public interface ICallInspector { - void MethodVoid(); - void MethodWithValueArg(Value _); - void MethodWithErrorArg(Error _); - void MethodWithMaybeArg(Maybe _); - void MethodWithResultArg(Result _); - Task MethodVoidAsync(); - Task MethodWithValueArgAsync(Value _); - Task MethodWithErrorArgAsync(Error _); - Task MethodWithMaybeArgAsync(Maybe _); - Task MethodWithResultArgAsync(Result _); + void MethodVoid(); + void MethodWithValueArg(Value _); + void MethodWithErrorArg(Error _); + void MethodWithMaybeArg(Maybe _); + void MethodWithResultArg(Result _); + Task MethodVoidAsync(); + Task MethodWithValueArgAsync(Value _); + Task MethodWithErrorArgAsync(Error _); + Task MethodWithMaybeArgAsync(Maybe _); + Task MethodWithResultArgAsync(Result _); } \ No newline at end of file diff --git a/test/Monads.UnitTests/ErrorTests/ErrorTests.cs b/test/Monads.UnitTests/ErrorTests/ErrorTests.cs index 9115ca6..3194f1e 100644 --- a/test/Monads.UnitTests/ErrorTests/ErrorTests.cs +++ b/test/Monads.UnitTests/ErrorTests/ErrorTests.cs @@ -2,43 +2,43 @@ namespace Bogoware.Monads.UnitTests.ErrorTests; public class ErrorTests { - [Fact] - public void CreateRuntimeError() - { - var sut = new RuntimeError(new("Message")); - sut.Exception.Should().NotBeNull(); - sut.Message.Should().Be("Message"); - } + [Fact] + public void CreateRuntimeError() + { + var sut = new RuntimeError(new("Message")); + sut.Exception.Should().NotBeNull(); + sut.Message.Should().Be("Message"); + } - [Fact] - public void CreateLogicError() - { - var sut = new LogicError("Message"); - sut.Message.Should().Be("Message"); - } + [Fact] + public void CreateLogicError() + { + var sut = new LogicError("Message"); + sut.Message.Should().Be("Message"); + } - [Fact] - public void AggregateError_noMessage() - { - var sut = new AggregateError(new LogicError("One"), new LogicError("Two")); - sut.Message.Should().NotBeNullOrEmpty(); - sut.Errors.Should().HaveCount(2); - } - - [Fact] - public void AggregateError_enumerable_coverage() - { - IEnumerable errors = new List { new LogicError("One"), new LogicError("Two") }; - var sut = new AggregateError(errors); - sut.Message.Should().NotBeNullOrEmpty(); - sut.Errors.Should().HaveCount(2); - } - - [Fact] - public void AggregateError_twoErrors_coverage() - { - var sut = new AggregateError("Two logic errors", new LogicError("One"), new LogicError("Two")); - sut.Message.Should().NotBeNullOrEmpty(); - sut.Errors.Should().HaveCount(2); - } + [Fact] + public void AggregateError_noMessage() + { + var sut = new AggregateError(new LogicError("One"), new LogicError("Two")); + sut.Message.Should().NotBeNullOrEmpty(); + sut.Errors.Should().HaveCount(2); + } + + [Fact] + public void AggregateError_enumerable_coverage() + { + IEnumerable errors = new List { new LogicError("One"), new LogicError("Two") }; + var sut = new AggregateError(errors); + sut.Message.Should().NotBeNullOrEmpty(); + sut.Errors.Should().HaveCount(2); + } + + [Fact] + public void AggregateError_twoErrors_coverage() + { + var sut = new AggregateError("Two logic errors", new LogicError("One"), new LogicError("Two")); + sut.Message.Should().NotBeNullOrEmpty(); + sut.Errors.Should().HaveCount(2); + } } \ No newline at end of file diff --git a/test/Monads.UnitTests/ErrorTests/LogicErrorTests.cs b/test/Monads.UnitTests/ErrorTests/LogicErrorTests.cs index 94359e9..e9df275 100644 --- a/test/Monads.UnitTests/ErrorTests/LogicErrorTests.cs +++ b/test/Monads.UnitTests/ErrorTests/LogicErrorTests.cs @@ -2,22 +2,22 @@ namespace Bogoware.Monads.UnitTests.ErrorTests; public class LogicErrorTests { - [Fact] - public void Equality_pattern_success() - { - var error1 = new LogicError("error"); - var error2 = new LogicError("error"); + [Fact] + public void Equality_pattern_success() + { + var error1 = new LogicError("error"); + var error2 = new LogicError("error"); - error1.Equals((object)error2).Should().BeTrue(); - error1.GetHashCode().Should().Be(error2.GetHashCode()); - (error1 == error2).Should().BeTrue(); - (error1 != error2).Should().BeFalse(); - } + error1.Equals((object)error2).Should().BeTrue(); + error1.GetHashCode().Should().Be(error2.GetHashCode()); + (error1 == error2).Should().BeTrue(); + (error1 != error2).Should().BeFalse(); + } - [Fact] - public void Error_ToString() - { - var error = new LogicError("Hello World"); - error.ToString().Should().Be("""LogicError: "Hello World"."""); - } + [Fact] + public void Error_ToString() + { + var error = new LogicError("Hello World"); + error.ToString().Should().Be("""LogicError: "Hello World"."""); + } } \ No newline at end of file diff --git a/test/Monads.UnitTests/MaybeTests/MaybeAsyncTests.cs b/test/Monads.UnitTests/MaybeTests/MaybeAsyncTests.cs index ce4aef5..8a21465 100644 --- a/test/Monads.UnitTests/MaybeTests/MaybeAsyncTests.cs +++ b/test/Monads.UnitTests/MaybeTests/MaybeAsyncTests.cs @@ -9,315 +9,315 @@ namespace Bogoware.Monads.UnitTests.MaybeTests; public class MaybeAsyncTests { - private static AnotherValue Function() => new AnotherValue(0); - private static AnotherValue Function(Value value) => new AnotherValue(value.Val); - private static Maybe BindFunctionSome() => Maybe.Some(new AnotherValue(0)); - private static Maybe BindFunctionSome(Value value) => Maybe.Some(new AnotherValue(value.Val)); - - private static Task AsyncFunction() => Task.FromResult(new AnotherValue(0)); - private static Task AsyncFunction(Value value) => Task.FromResult(new AnotherValue(value.Val)); - private static Task> AsyncBindFunctionSome() => Task.FromResult(Maybe.Some(new AnotherValue(0))); - private static Task> AsyncBindFunctionSome(Value value) => Task.FromResult(Maybe.Some(new AnotherValue(value.Val))); - private static Task> AsyncBindFunctionNone() => Task.FromResult(Maybe.None()); - private static Task> AsyncBindFunctionNone(Value value) => Task.FromResult(Maybe.None()); - - [Fact] - public async Task Async_map_asyncAction_withSome() - { - var sut = Maybe.Some(new Value(0)); - var actual = await sut.Map(() => AsyncFunction()); - actual.IsSome.Should().BeTrue(); - } - - [Fact] - public async Task Async_map_asyncFunction_withSome() - { - var sut = Maybe.Some(new Value(0)); - var actual = await sut.Map(AsyncFunction); - actual.IsSome.Should().BeTrue(); - } - - [Fact] - public async Task Async_map_asyncAction_withNone() - { - var sut = Maybe.None(); - var actual = await sut.Map(() => AsyncFunction()); - actual.IsNone.Should().BeTrue(); - } - - [Fact] - public async Task Async_map_asyncFunction_withNone() - { - var sut = Maybe.None(); - var actual = await sut.Map(AsyncFunction); - actual.IsNone.Should().BeTrue(); - } - - [Fact] - public async Task Async_flatMap_asyncAction_withSome() - { - var sut = Maybe.Some(new Value(0)); - var actual = await sut.Bind(() => AsyncBindFunctionSome()); - actual.IsSome.Should().BeTrue(); - } - - [Fact] - public async Task Async_flatMap_asyncFunction_withSome() - { - var sut = Maybe.Some(new Value(0)); - var actual = await sut.Bind(AsyncBindFunctionSome); - actual.IsSome.Should().BeTrue(); - } - - [Fact] - public async Task Async_flatMap_asyncAction_withNone() - { - var sut = Maybe.None(); - var actual = await sut.Bind(() => AsyncBindFunctionNone()); - actual.IsNone.Should().BeTrue(); - } - - [Fact] - public async Task Async_flatMap_asyncFunction_withNone() - { - var sut = Maybe.None(); - var actual = await sut.Bind(AsyncBindFunctionNone); - actual.IsNone.Should().BeTrue(); - } - - [Fact] - public async Task AsyncExtensions_map_asyncAction_withSome() - { - var sut = Task.FromResult(Maybe.Some(new Value(0))); - var actual = await sut.Map(() => AsyncFunction()); - actual.IsSome.Should().BeTrue(); - } - - [Fact] - public async Task AsyncExtensions_map_asyncFunction_withSome() - { - var sut = Task.FromResult(Maybe.Some(new Value(0))); - var actual = await sut.Map(v => AsyncFunction(v)); - actual.IsSome.Should().BeTrue(); - } - - [Fact] - public async Task AsyncExtensions_map_asyncAction_withNone() - { - var sut = Task.FromResult(Maybe.None()); - var actual = await sut.Map(() => AsyncFunction()); - actual.IsNone.Should().BeTrue(); - } - - [Fact] - public async Task AsyncExtensions_map_asyncFunction_withNone() - { - var sut = Task.FromResult(Maybe.None()); - var actual = await sut.Map(v => AsyncFunction(v)); - actual.IsNone.Should().BeTrue(); - } - - [Fact] - public async Task AsyncExtensions_flatMap_asyncAction_withSome() - { - var sut = Task.FromResult(Maybe.Some(new Value(0))); - var actual = await sut.Bind(() => AsyncBindFunctionSome()); - actual.IsSome.Should().BeTrue(); - } - - [Fact] - public async Task AsyncExtensions_flatMap_asyncFunction_withSome() - { - var sut = Task.FromResult(Maybe.Some(new Value(0))); - var actual = await sut.Bind(v => AsyncBindFunctionSome(v)); - actual.IsSome.Should().BeTrue(); - } - - [Fact] - public async Task AsyncExtensions_map_Action_withSome() - { - var sut = Task.FromResult(Maybe.Some(new Value(0))); - var actual = await sut.Map(() => Function()); - actual.IsSome.Should().BeTrue(); - } - - [Fact] - public async Task AsyncExtensions_map_Function_withSome() - { - var sut = Task.FromResult(Maybe.Some(new Value(0))); - var actual = await sut.Map(v => Function(v)); - actual.IsSome.Should().BeTrue(); - } - - [Fact] - public async Task AsyncExtensions_map_Action_withNone() - { - var sut = Task.FromResult(Maybe.None()); - var actual = await sut.Map(() => Function()); - actual.IsNone.Should().BeTrue(); - } - - [Fact] - public async Task AsyncExtensions_map_Function_withNone() - { - var sut = Task.FromResult(Maybe.None()); - var actual = await sut.Map(v => Function(v)); - actual.IsNone.Should().BeTrue(); - } - - [Fact] - public async Task AsyncExtensions_flatMap_Action_withSome() - { - var sut = Task.FromResult(Maybe.Some(new Value(0))); - var actual = await sut.Bind(() => BindFunctionSome()); - actual.IsSome.Should().BeTrue(); - } - - [Fact] - public async Task AsyncExtensions_flatMap_Function_withSome() - { - var sut = Task.FromResult(Maybe.Some(new Value(0))); - var actual = await sut.Bind(v => BindFunctionSome(v)); - actual.IsSome.Should().BeTrue(); - } - - [Fact] - public async Task Async_wthDefault_value() - { - var sut = Task.FromResult(Maybe.None()); - var actual = await sut.WithDefault(new Value(1)); - actual.IsSome.Should().BeTrue(); - } - - [Fact] - public async Task Async_wthDefault_function() - { - var sut = Task.FromResult(Maybe.None()); - var actual = await sut.WithDefault(() => new(1)); - actual.IsSome.Should().BeTrue(); - } - - [Fact] - public async Task Async_wthDefault_asyncFunction() - { - var sut = Task.FromResult(Maybe.None()); - var actual = await sut.WithDefault(() => Task.FromResult(new(0))); - actual.IsSome.Should().BeTrue(); - } - - [Fact] - public async Task Match_with_values() - { - var sut = Task.FromResult(Maybe.None()); - var actual = await sut.Match(0, 1); - actual.Should().Be(1); - } - [Fact] - public async Task Match_with_func_and_value() - { - var sut = Task.FromResult(Maybe.None()); - var actual = await sut.Match(_ => 0, 1); - actual.Should().Be(1); - } - - [Fact] - public async Task Match_with_funcs() - { - var sut = Task.FromResult(Maybe.None()); - var actual = await sut.Match(_ => 0, () => 1); - actual.Should().Be(1); - } - - [Fact] - public async Task Match_with_asyncLeft() - { - var sut = Task.FromResult(Maybe.None()); - var actual = await sut.Match(_ => Task.FromResult(0), () => 1); - actual.Should().Be(1); - } - [Fact] - public async Task Match_with_asyncRight() - { - var sut = Task.FromResult(Maybe.None()); - var actual = await sut.Match(_ => 0, () => Task.FromResult(1)); - actual.Should().Be(1); - } - - [Fact] - public async Task Match_with_asyncBoth() - { - var sut = Task.FromResult(Maybe.None()); - var actual = await sut.Match(_ => Task.FromResult(0), () => Task.FromResult(1)); - actual.Should().Be(1); - } - - [Fact] - public async Task IfSome_action() - { - var inspector = new Mock(); - var sut = Task.FromResult(Maybe.Some(new Value(0))); - await sut.ExecuteIfSome(inspector.Object.MethodVoid); - inspector.Verify(c => c.MethodVoid()); - } - - [Fact] - public async Task IfSome_action_with_arg() - { - var inspector = new Mock(); - var sut = Task.FromResult(Maybe.Some(new Value(0))); - await sut.ExecuteIfSome(inspector.Object.MethodWithValueArg); - inspector.Verify(c => c.MethodWithValueArg(It.IsAny())); - } - - [Fact] - public async Task IfSome_asyncAction() - { - var inspector = new Mock(); - var sut = Task.FromResult(Maybe.Some(new Value(0))); - await sut.ExecuteIfSome(inspector.Object.MethodVoidAsync); - inspector.Verify(c => c.MethodVoidAsync()); - } - - [Fact] - public async Task IfSome_asyncAction_with_arg() - { - var inspector = new Mock(); - var sut = Task.FromResult(Maybe.Some(new Value(0))); - await sut.ExecuteIfSome(inspector.Object.MethodWithValueArgAsync); - inspector.Verify(c => c.MethodWithValueArgAsync(It.IsAny())); - } - - [Fact] - public async Task IfNone_action() - { - var inspector = new Mock(); - var sut = Task.FromResult(Maybe.None()); - await sut.ExecuteIfNone(inspector.Object.MethodVoid); - inspector.Verify(c => c.MethodVoid()); - } - [Fact] - public async Task IfNone_actionAsync() - { - var inspector = new Mock(); - var sut = Task.FromResult(Maybe.None()); - await sut.ExecuteIfNone(inspector.Object.MethodVoidAsync); - inspector.Verify(c => c.MethodVoidAsync()); - } - - [Fact] - public async Task Tap_action() - { - var inspector = new Mock(); - var sut = Task.FromResult(Maybe.None()); - await sut.Execute(inspector.Object.MethodWithMaybeArg); - inspector.Verify(c => c.MethodWithMaybeArg(It.IsAny>())); - } - [Fact] - public async Task Tap_actionAsync() - { - var inspector = new Mock(); - var sut = Task.FromResult(Maybe.None()); - await sut.Execute(inspector.Object.MethodWithMaybeArgAsync); - inspector.Verify(c => c.MethodWithMaybeArgAsync(It.IsAny>())); - } + private static AnotherValue Function() => new AnotherValue(0); + private static AnotherValue Function(Value value) => new AnotherValue(value.Val); + private static Maybe BindFunctionSome() => Maybe.Some(new AnotherValue(0)); + private static Maybe BindFunctionSome(Value value) => Maybe.Some(new AnotherValue(value.Val)); + + private static Task AsyncFunction() => Task.FromResult(new AnotherValue(0)); + private static Task AsyncFunction(Value value) => Task.FromResult(new AnotherValue(value.Val)); + private static Task> AsyncBindFunctionSome() => Task.FromResult(Maybe.Some(new AnotherValue(0))); + private static Task> AsyncBindFunctionSome(Value value) => Task.FromResult(Maybe.Some(new AnotherValue(value.Val))); + private static Task> AsyncBindFunctionNone() => Task.FromResult(Maybe.None()); + private static Task> AsyncBindFunctionNone(Value value) => Task.FromResult(Maybe.None()); + + [Fact] + public async Task Async_map_asyncAction_withSome() + { + var sut = Maybe.Some(new Value(0)); + var actual = await sut.Map(() => AsyncFunction()); + actual.IsSome.Should().BeTrue(); + } + + [Fact] + public async Task Async_map_asyncFunction_withSome() + { + var sut = Maybe.Some(new Value(0)); + var actual = await sut.Map(AsyncFunction); + actual.IsSome.Should().BeTrue(); + } + + [Fact] + public async Task Async_map_asyncAction_withNone() + { + var sut = Maybe.None(); + var actual = await sut.Map(() => AsyncFunction()); + actual.IsNone.Should().BeTrue(); + } + + [Fact] + public async Task Async_map_asyncFunction_withNone() + { + var sut = Maybe.None(); + var actual = await sut.Map(AsyncFunction); + actual.IsNone.Should().BeTrue(); + } + + [Fact] + public async Task Async_flatMap_asyncAction_withSome() + { + var sut = Maybe.Some(new Value(0)); + var actual = await sut.Bind(() => AsyncBindFunctionSome()); + actual.IsSome.Should().BeTrue(); + } + + [Fact] + public async Task Async_flatMap_asyncFunction_withSome() + { + var sut = Maybe.Some(new Value(0)); + var actual = await sut.Bind(AsyncBindFunctionSome); + actual.IsSome.Should().BeTrue(); + } + + [Fact] + public async Task Async_flatMap_asyncAction_withNone() + { + var sut = Maybe.None(); + var actual = await sut.Bind(() => AsyncBindFunctionNone()); + actual.IsNone.Should().BeTrue(); + } + + [Fact] + public async Task Async_flatMap_asyncFunction_withNone() + { + var sut = Maybe.None(); + var actual = await sut.Bind(AsyncBindFunctionNone); + actual.IsNone.Should().BeTrue(); + } + + [Fact] + public async Task AsyncExtensions_map_asyncAction_withSome() + { + var sut = Task.FromResult(Maybe.Some(new Value(0))); + var actual = await sut.Map(() => AsyncFunction()); + actual.IsSome.Should().BeTrue(); + } + + [Fact] + public async Task AsyncExtensions_map_asyncFunction_withSome() + { + var sut = Task.FromResult(Maybe.Some(new Value(0))); + var actual = await sut.Map(v => AsyncFunction(v)); + actual.IsSome.Should().BeTrue(); + } + + [Fact] + public async Task AsyncExtensions_map_asyncAction_withNone() + { + var sut = Task.FromResult(Maybe.None()); + var actual = await sut.Map(() => AsyncFunction()); + actual.IsNone.Should().BeTrue(); + } + + [Fact] + public async Task AsyncExtensions_map_asyncFunction_withNone() + { + var sut = Task.FromResult(Maybe.None()); + var actual = await sut.Map(v => AsyncFunction(v)); + actual.IsNone.Should().BeTrue(); + } + + [Fact] + public async Task AsyncExtensions_flatMap_asyncAction_withSome() + { + var sut = Task.FromResult(Maybe.Some(new Value(0))); + var actual = await sut.Bind(() => AsyncBindFunctionSome()); + actual.IsSome.Should().BeTrue(); + } + + [Fact] + public async Task AsyncExtensions_flatMap_asyncFunction_withSome() + { + var sut = Task.FromResult(Maybe.Some(new Value(0))); + var actual = await sut.Bind(v => AsyncBindFunctionSome(v)); + actual.IsSome.Should().BeTrue(); + } + + [Fact] + public async Task AsyncExtensions_map_Action_withSome() + { + var sut = Task.FromResult(Maybe.Some(new Value(0))); + var actual = await sut.Map(() => Function()); + actual.IsSome.Should().BeTrue(); + } + + [Fact] + public async Task AsyncExtensions_map_Function_withSome() + { + var sut = Task.FromResult(Maybe.Some(new Value(0))); + var actual = await sut.Map(v => Function(v)); + actual.IsSome.Should().BeTrue(); + } + + [Fact] + public async Task AsyncExtensions_map_Action_withNone() + { + var sut = Task.FromResult(Maybe.None()); + var actual = await sut.Map(() => Function()); + actual.IsNone.Should().BeTrue(); + } + + [Fact] + public async Task AsyncExtensions_map_Function_withNone() + { + var sut = Task.FromResult(Maybe.None()); + var actual = await sut.Map(v => Function(v)); + actual.IsNone.Should().BeTrue(); + } + + [Fact] + public async Task AsyncExtensions_flatMap_Action_withSome() + { + var sut = Task.FromResult(Maybe.Some(new Value(0))); + var actual = await sut.Bind(() => BindFunctionSome()); + actual.IsSome.Should().BeTrue(); + } + + [Fact] + public async Task AsyncExtensions_flatMap_Function_withSome() + { + var sut = Task.FromResult(Maybe.Some(new Value(0))); + var actual = await sut.Bind(v => BindFunctionSome(v)); + actual.IsSome.Should().BeTrue(); + } + + [Fact] + public async Task Async_wthDefault_value() + { + var sut = Task.FromResult(Maybe.None()); + var actual = await sut.WithDefault(new Value(1)); + actual.IsSome.Should().BeTrue(); + } + + [Fact] + public async Task Async_wthDefault_function() + { + var sut = Task.FromResult(Maybe.None()); + var actual = await sut.WithDefault(() => new(1)); + actual.IsSome.Should().BeTrue(); + } + + [Fact] + public async Task Async_wthDefault_asyncFunction() + { + var sut = Task.FromResult(Maybe.None()); + var actual = await sut.WithDefault(() => Task.FromResult(new(0))); + actual.IsSome.Should().BeTrue(); + } + + [Fact] + public async Task Match_with_values() + { + var sut = Task.FromResult(Maybe.None()); + var actual = await sut.Match(0, 1); + actual.Should().Be(1); + } + [Fact] + public async Task Match_with_func_and_value() + { + var sut = Task.FromResult(Maybe.None()); + var actual = await sut.Match(_ => 0, 1); + actual.Should().Be(1); + } + + [Fact] + public async Task Match_with_funcs() + { + var sut = Task.FromResult(Maybe.None()); + var actual = await sut.Match(_ => 0, () => 1); + actual.Should().Be(1); + } + + [Fact] + public async Task Match_with_asyncLeft() + { + var sut = Task.FromResult(Maybe.None()); + var actual = await sut.Match(_ => Task.FromResult(0), () => 1); + actual.Should().Be(1); + } + [Fact] + public async Task Match_with_asyncRight() + { + var sut = Task.FromResult(Maybe.None()); + var actual = await sut.Match(_ => 0, () => Task.FromResult(1)); + actual.Should().Be(1); + } + + [Fact] + public async Task Match_with_asyncBoth() + { + var sut = Task.FromResult(Maybe.None()); + var actual = await sut.Match(_ => Task.FromResult(0), () => Task.FromResult(1)); + actual.Should().Be(1); + } + + [Fact] + public async Task IfSome_action() + { + var inspector = new Mock(); + var sut = Task.FromResult(Maybe.Some(new Value(0))); + await sut.ExecuteIfSome(inspector.Object.MethodVoid); + inspector.Verify(c => c.MethodVoid()); + } + + [Fact] + public async Task IfSome_action_with_arg() + { + var inspector = new Mock(); + var sut = Task.FromResult(Maybe.Some(new Value(0))); + await sut.ExecuteIfSome(inspector.Object.MethodWithValueArg); + inspector.Verify(c => c.MethodWithValueArg(It.IsAny())); + } + + [Fact] + public async Task IfSome_asyncAction() + { + var inspector = new Mock(); + var sut = Task.FromResult(Maybe.Some(new Value(0))); + await sut.ExecuteIfSome(inspector.Object.MethodVoidAsync); + inspector.Verify(c => c.MethodVoidAsync()); + } + + [Fact] + public async Task IfSome_asyncAction_with_arg() + { + var inspector = new Mock(); + var sut = Task.FromResult(Maybe.Some(new Value(0))); + await sut.ExecuteIfSome(inspector.Object.MethodWithValueArgAsync); + inspector.Verify(c => c.MethodWithValueArgAsync(It.IsAny())); + } + + [Fact] + public async Task IfNone_action() + { + var inspector = new Mock(); + var sut = Task.FromResult(Maybe.None()); + await sut.ExecuteIfNone(inspector.Object.MethodVoid); + inspector.Verify(c => c.MethodVoid()); + } + [Fact] + public async Task IfNone_actionAsync() + { + var inspector = new Mock(); + var sut = Task.FromResult(Maybe.None()); + await sut.ExecuteIfNone(inspector.Object.MethodVoidAsync); + inspector.Verify(c => c.MethodVoidAsync()); + } + + [Fact] + public async Task Tap_action() + { + var inspector = new Mock(); + var sut = Task.FromResult(Maybe.None()); + await sut.Execute(inspector.Object.MethodWithMaybeArg); + inspector.Verify(c => c.MethodWithMaybeArg(It.IsAny>())); + } + [Fact] + public async Task Tap_actionAsync() + { + var inspector = new Mock(); + var sut = Task.FromResult(Maybe.None()); + await sut.Execute(inspector.Object.MethodWithMaybeArgAsync); + inspector.Verify(c => c.MethodWithMaybeArgAsync(It.IsAny>())); + } } \ No newline at end of file diff --git a/test/Monads.UnitTests/MaybeTests/MaybeBindTests.cs b/test/Monads.UnitTests/MaybeTests/MaybeBindTests.cs index e86c32d..7f04fbb 100644 --- a/test/Monads.UnitTests/MaybeTests/MaybeBindTests.cs +++ b/test/Monads.UnitTests/MaybeTests/MaybeBindTests.cs @@ -2,57 +2,57 @@ namespace Bogoware.Monads.UnitTests.MaybeTests; public class MaybeBindTests { - [Fact] - public void Some_bindsTo_SomeValue_by_action() - { - var value = Maybe.Some(new Value(0)); - var newValue = value.Bind(() => Maybe.Some(new AnotherValue(0))); - newValue.GetType().Should().Be>(); - newValue.IsSome.Should().BeTrue(); - } - - [Fact] - public void Some_bindsTo_SomeValue_by_function() - { - var value = Maybe.Some(new Value(0)); - var newValue = value.Bind(val => Maybe.Some(new AnotherValue(val.Val + 1))); - newValue.GetType().Should().Be>(); - newValue.IsSome.Should().BeTrue(); - } - - [Fact] - public void Some_bindsTo_None_by_action() - { - var value = Maybe.Some(new Value(0)); - var newValue = value.Bind(Maybe.None); - newValue.GetType().Should().Be>(); - newValue.IsNone.Should().BeTrue(); - } - - [Fact] - public void Some_bindsTo_None_by_function() - { - var value = Maybe.Some(new Value(0)); - var newValue = value.Bind(_ => Maybe.None()); - newValue.GetType().Should().Be>(); - newValue.IsNone.Should().BeTrue(); - } - - [Fact] - public void None_bindsTo_None_by_action() - { - var value = Maybe.None(); - var newValue = value.Bind(() => Maybe.Some(new AnotherValue(0))); - newValue.GetType().Should().Be>(); - newValue.IsNone.Should().BeTrue(); - } - - [Fact] - public void None_bindsTo_None_by_function() - { - var value = Maybe.None(); - var newValue = value.Bind(val => Maybe.Some(new AnotherValue(val.Val + 1))); - newValue.GetType().Should().Be>(); - newValue.IsNone.Should().BeTrue(); - } + [Fact] + public void Some_bindsTo_SomeValue_by_action() + { + var value = Maybe.Some(new Value(0)); + var newValue = value.Bind(() => Maybe.Some(new AnotherValue(0))); + newValue.GetType().Should().Be>(); + newValue.IsSome.Should().BeTrue(); + } + + [Fact] + public void Some_bindsTo_SomeValue_by_function() + { + var value = Maybe.Some(new Value(0)); + var newValue = value.Bind(val => Maybe.Some(new AnotherValue(val.Val + 1))); + newValue.GetType().Should().Be>(); + newValue.IsSome.Should().BeTrue(); + } + + [Fact] + public void Some_bindsTo_None_by_action() + { + var value = Maybe.Some(new Value(0)); + var newValue = value.Bind(Maybe.None); + newValue.GetType().Should().Be>(); + newValue.IsNone.Should().BeTrue(); + } + + [Fact] + public void Some_bindsTo_None_by_function() + { + var value = Maybe.Some(new Value(0)); + var newValue = value.Bind(_ => Maybe.None()); + newValue.GetType().Should().Be>(); + newValue.IsNone.Should().BeTrue(); + } + + [Fact] + public void None_bindsTo_None_by_action() + { + var value = Maybe.None(); + var newValue = value.Bind(() => Maybe.Some(new AnotherValue(0))); + newValue.GetType().Should().Be>(); + newValue.IsNone.Should().BeTrue(); + } + + [Fact] + public void None_bindsTo_None_by_function() + { + var value = Maybe.None(); + var newValue = value.Bind(val => Maybe.Some(new AnotherValue(val.Val + 1))); + newValue.GetType().Should().Be>(); + newValue.IsNone.Should().BeTrue(); + } } \ No newline at end of file diff --git a/test/Monads.UnitTests/MaybeTests/MaybeCreationTests.cs b/test/Monads.UnitTests/MaybeTests/MaybeCreationTests.cs index 8ede64d..423d467 100644 --- a/test/Monads.UnitTests/MaybeTests/MaybeCreationTests.cs +++ b/test/Monads.UnitTests/MaybeTests/MaybeCreationTests.cs @@ -3,74 +3,74 @@ namespace Bogoware.Monads.UnitTests.MaybeTests; public class MaybeCreationTests { - [Fact] - public void Maybe_with_null_produces_a_None() - { - - Maybe sut = Maybe.From((string)null!); - sut.IsSome.Should().BeFalse(); - sut.Should().BeEquivalentTo(Maybe.None()); - } - - [Fact] - public void Maybe_with_notnull_produces_a_Some() - { - - var sut = Maybe.From("Some"); - sut.IsSome.Should().BeTrue(); - sut.Should().BeEquivalentTo(Maybe.Some("Some")); - } - - [Fact] - public void Some_with_notnull_is_successful() - { - - Maybe sut = Maybe.Some("Some"); - sut.IsSome.Should().BeTrue(); - sut.Should().BeEquivalentTo(Maybe.Some("Some")); - } - - [Fact] - public void Some_with_null_is_failure() - { - string value = null!; - Action act = () => Maybe.Some(value); + [Fact] + public void Maybe_with_null_produces_a_None() + { - act.Should().Throw(); - } - - [Fact] - public void Some_with_None_is_failure() - { - var value = Maybe.None(); - Action act = () => Maybe.Some(value); + Maybe sut = Maybe.From((string)null!); + sut.IsSome.Should().BeFalse(); + sut.Should().BeEquivalentTo(Maybe.None()); + } - act.Should().Throw(); - } + [Fact] + public void Maybe_with_notnull_produces_a_Some() + { - [Fact] - public void Maybe_copy_constructor() - { - var maybe = Maybe.From(new Value(0)); - var maybe2 = Maybe.From(maybe); - - maybe.Equals(maybe2).Should().BeTrue(); - } - - [Fact] - public void Maybe_from_struct_value_should_be_true() - { - bool? value = false; - var maybe = Maybe.From(value); - maybe.IsSome.Should().BeTrue(); - } - [Fact] - public void Maybe_from_struct_value_should_be_false() - { - Maybe maybe = Maybe.None(); - bool? value = default; - Maybe maybe2 = new Maybe(value); - maybe.IsNone.Should().BeTrue(); - maybe2.IsNone.Should().BeTrue(); - } + var sut = Maybe.From("Some"); + sut.IsSome.Should().BeTrue(); + sut.Should().BeEquivalentTo(Maybe.Some("Some")); + } + + [Fact] + public void Some_with_notnull_is_successful() + { + + Maybe sut = Maybe.Some("Some"); + sut.IsSome.Should().BeTrue(); + sut.Should().BeEquivalentTo(Maybe.Some("Some")); + } + + [Fact] + public void Some_with_null_is_failure() + { + string value = null!; + Action act = () => Maybe.Some(value); + + act.Should().Throw(); + } + + [Fact] + public void Some_with_None_is_failure() + { + var value = Maybe.None(); + Action act = () => Maybe.Some(value); + + act.Should().Throw(); + } + + [Fact] + public void Maybe_copy_constructor() + { + var maybe = Maybe.From(new Value(0)); + var maybe2 = Maybe.From(maybe); + + maybe.Equals(maybe2).Should().BeTrue(); + } + + [Fact] + public void Maybe_from_struct_value_should_be_true() + { + bool? value = false; + var maybe = Maybe.From(value); + maybe.IsSome.Should().BeTrue(); + } + [Fact] + public void Maybe_from_struct_value_should_be_false() + { + Maybe maybe = Maybe.None(); + bool? value = default; + Maybe maybe2 = new Maybe(value); + maybe.IsNone.Should().BeTrue(); + maybe2.IsNone.Should().BeTrue(); + } } \ No newline at end of file diff --git a/test/Monads.UnitTests/MaybeTests/MaybeEnumerableExtensionsTests.cs b/test/Monads.UnitTests/MaybeTests/MaybeEnumerableExtensionsTests.cs index 189be6a..a7c4518 100644 --- a/test/Monads.UnitTests/MaybeTests/MaybeEnumerableExtensionsTests.cs +++ b/test/Monads.UnitTests/MaybeTests/MaybeEnumerableExtensionsTests.cs @@ -4,161 +4,161 @@ namespace Bogoware.Monads.UnitTests.MaybeTests; public class MaybeEnumerableExtensionsTests { - private static readonly List _allIMaybeSome = new() - { - Maybe.Some(new Value(0)), - Maybe.Some(new Value(1)), - Maybe.Some(new Value(2)) - }; - - private static readonly List> _allMaybeSome = new() - { - Maybe.Some(new Value(0)), - Maybe.Some(new Value(1)), - Maybe.Some(new Value(2)) - }; - - private static readonly List> _allMaybeNone = new() - { - Maybe.None, - Maybe.None, - Maybe.None - }; - - private static readonly List _allIMaybeNone = new() - { - Maybe.None, - Maybe.None, - Maybe.None - }; - - private static readonly List> _maybeMixed = new() - { - Maybe.Some(new Value(0)), - Maybe.None, - Maybe.Some(new Value(2)) - }; - - private static readonly List _maybeIMixed = new() - { - Maybe.Some(new Value(0)), - Maybe.None, - Maybe.Some(new Value(2)) - }; - - [Fact] - public void AllSome_returns_true() - { - _allMaybeSome.AllSome().Should().BeTrue(); - _allIMaybeSome.AllSome().Should().BeTrue(); - } - - [Fact] - public void AllSome_returns_false() - { - _maybeMixed.AllSome().Should().BeFalse(); - _maybeIMixed.AllSome().Should().BeFalse(); - } - - [Fact] - public void AllNone_returns_true() - { - _allMaybeNone.AllNone().Should().BeTrue(); - _allIMaybeNone.AllNone().Should().BeTrue(); - } - - [Fact] - public void AllNone_returns_false() - { - _maybeMixed.AllNone().Should().BeFalse(); - _maybeIMixed.AllNone().Should().BeFalse(); - } - - [Fact] - public void AnySome_returns_true() - { - _maybeMixed.AnySome().Should().BeTrue(); - _maybeIMixed.AnySome().Should().BeTrue(); - _allMaybeSome.AnySome().Should().BeTrue(); - _allIMaybeSome.AnySome().Should().BeTrue(); - } - - [Fact] - public void AnySome_returns_false() - { - _allMaybeNone.AnySome().Should().BeFalse(); - _allIMaybeNone.AnySome().Should().BeFalse(); - } - - [Fact] - public void AnyNone_returns_true() - { - _maybeMixed.AnyNone().Should().BeTrue(); - _maybeIMixed.AnyNone().Should().BeTrue(); - _allMaybeNone.AnyNone().Should().BeTrue(); - _allIMaybeNone.AnyNone().Should().BeTrue(); - } - - [Fact] - public void AnyNone_returns_false() - { - _allMaybeSome.AnyNone().Should().BeFalse(); - _allIMaybeSome.AnyNone().Should().BeFalse(); - } - - [Fact] - public void SelectValues_discards_Nones() - { - _maybeMixed.Should().HaveCount(3); - _maybeMixed.SelectValues().Should().HaveCount(2); - } - - [Fact] - public void MapEach_remap_values_to_new_Some() - { - IEnumerable> actual = _maybeMixed.MapEach(v => new AnotherValue(v.Val)); - actual.Should().HaveCount(3); - actual.Count(m => m.IsSome).Should().Be(2); - actual.Count(m => m.IsNone).Should().Be(1); - } - - [Fact] - public void BindEach_remap_values_to_new_Some() - { - IEnumerable> actual = _maybeMixed.BindEach(v => Maybe.Some(new AnotherValue(v.Val))); - actual.Should().HaveCount(3); - actual.Count(m => m.IsSome).Should().Be(2); - actual.Count(m => m.IsNone).Should().Be(1); - } - - [Fact] - public void Where_works() - { - IEnumerable> maybes = new List> - { - new Value(0), - new Value(1), - new Value(2), - new Value(3) - }; - - IEnumerable> even = maybes.Where(v => v.Val % 2 == 0); - even.Should().HaveCount(2); - } - - [Fact] - public void WhereNot_works() - { - IEnumerable> maybes = new List> - { - new Value(0), - new Value(1), - new Value(2), - new Value(3), - new Value(5) - }; - - IEnumerable> even = maybes.WhereNot(v => v.Val % 2 == 0); - even.Should().HaveCount(3); - } + private static readonly List _allIMaybeSome = new() + { + Maybe.Some(new Value(0)), + Maybe.Some(new Value(1)), + Maybe.Some(new Value(2)) + }; + + private static readonly List> _allMaybeSome = new() + { + Maybe.Some(new Value(0)), + Maybe.Some(new Value(1)), + Maybe.Some(new Value(2)) + }; + + private static readonly List> _allMaybeNone = new() + { + Maybe.None, + Maybe.None, + Maybe.None + }; + + private static readonly List _allIMaybeNone = new() + { + Maybe.None, + Maybe.None, + Maybe.None + }; + + private static readonly List> _maybeMixed = new() + { + Maybe.Some(new Value(0)), + Maybe.None, + Maybe.Some(new Value(2)) + }; + + private static readonly List _maybeIMixed = new() + { + Maybe.Some(new Value(0)), + Maybe.None, + Maybe.Some(new Value(2)) + }; + + [Fact] + public void AllSome_returns_true() + { + _allMaybeSome.AllSome().Should().BeTrue(); + _allIMaybeSome.AllSome().Should().BeTrue(); + } + + [Fact] + public void AllSome_returns_false() + { + _maybeMixed.AllSome().Should().BeFalse(); + _maybeIMixed.AllSome().Should().BeFalse(); + } + + [Fact] + public void AllNone_returns_true() + { + _allMaybeNone.AllNone().Should().BeTrue(); + _allIMaybeNone.AllNone().Should().BeTrue(); + } + + [Fact] + public void AllNone_returns_false() + { + _maybeMixed.AllNone().Should().BeFalse(); + _maybeIMixed.AllNone().Should().BeFalse(); + } + + [Fact] + public void AnySome_returns_true() + { + _maybeMixed.AnySome().Should().BeTrue(); + _maybeIMixed.AnySome().Should().BeTrue(); + _allMaybeSome.AnySome().Should().BeTrue(); + _allIMaybeSome.AnySome().Should().BeTrue(); + } + + [Fact] + public void AnySome_returns_false() + { + _allMaybeNone.AnySome().Should().BeFalse(); + _allIMaybeNone.AnySome().Should().BeFalse(); + } + + [Fact] + public void AnyNone_returns_true() + { + _maybeMixed.AnyNone().Should().BeTrue(); + _maybeIMixed.AnyNone().Should().BeTrue(); + _allMaybeNone.AnyNone().Should().BeTrue(); + _allIMaybeNone.AnyNone().Should().BeTrue(); + } + + [Fact] + public void AnyNone_returns_false() + { + _allMaybeSome.AnyNone().Should().BeFalse(); + _allIMaybeSome.AnyNone().Should().BeFalse(); + } + + [Fact] + public void SelectValues_discards_Nones() + { + _maybeMixed.Should().HaveCount(3); + _maybeMixed.SelectValues().Should().HaveCount(2); + } + + [Fact] + public void MapEach_remap_values_to_new_Some() + { + IEnumerable> actual = _maybeMixed.MapEach(v => new AnotherValue(v.Val)); + actual.Should().HaveCount(3); + actual.Count(m => m.IsSome).Should().Be(2); + actual.Count(m => m.IsNone).Should().Be(1); + } + + [Fact] + public void BindEach_remap_values_to_new_Some() + { + IEnumerable> actual = _maybeMixed.BindEach(v => Maybe.Some(new AnotherValue(v.Val))); + actual.Should().HaveCount(3); + actual.Count(m => m.IsSome).Should().Be(2); + actual.Count(m => m.IsNone).Should().Be(1); + } + + [Fact] + public void Where_works() + { + IEnumerable> maybes = new List> + { + new Value(0), + new Value(1), + new Value(2), + new Value(3) + }; + + IEnumerable> even = maybes.Where(v => v.Val % 2 == 0); + even.Should().HaveCount(2); + } + + [Fact] + public void WhereNot_works() + { + IEnumerable> maybes = new List> + { + new Value(0), + new Value(1), + new Value(2), + new Value(3), + new Value(5) + }; + + IEnumerable> even = maybes.WhereNot(v => v.Val % 2 == 0); + even.Should().HaveCount(3); + } } \ No newline at end of file diff --git a/test/Monads.UnitTests/MaybeTests/MaybeEqualityTests.cs b/test/Monads.UnitTests/MaybeTests/MaybeEqualityTests.cs index 45862b6..3225f86 100644 --- a/test/Monads.UnitTests/MaybeTests/MaybeEqualityTests.cs +++ b/test/Monads.UnitTests/MaybeTests/MaybeEqualityTests.cs @@ -2,84 +2,84 @@ namespace Bogoware.Monads.UnitTests.MaybeTests; public class MaybeEqualityTests { - [Fact] - public void ObjectEquals_null_return_false() - { - var value1 = Maybe.Some(new Value(0)); - object value2 = null!; - value1.Equals(value2).Should().BeFalse(); - } - - [Fact] - public void ObjectEquals_return_true() - { - var value1 = Maybe.Some(new Value(0)); - object value2 = Maybe.Some(new Value(0)); - value1.Equals(value2).Should().BeTrue(); - } - - [Fact] - public void Some_are_notEquals_to_null() - { - var value1 = Maybe.Some(new Value(0)); - value1.Equals(null).Should().BeFalse(); - } - - [Fact] - public void Some_are_equals() - { - var value1 = Maybe.Some(new Value(0)); - var value2 = Maybe.Some(new Value(0)); - value1.Equals(value2).Should().BeTrue(); - value1.GetHashCode().Should().Be(value2.GetHashCode()); - } - - [Fact] - public void Some_are_not_equals_by_inner_value() - { - var value1 = Maybe.Some(new Value(0)); - var value2 = Maybe.Some(new Value(1)); - value1.Equals(value2).Should().BeFalse(); - } - - [Fact] - public void Some_are_not_equals_by_inner_type() - { - var value1 = Maybe.Some(new Value(0)); - var value2 = (object)Maybe.Some(new AnotherValue(0)); - value1.Equals(value2).Should().BeFalse(); - } - - [Fact] - public void None_are_equals_by_type() - { - var value1 = Maybe.None(); - var value2 = Maybe.None(); - value1.Equals(value2).Should().BeTrue(); - value1.GetHashCode().Should().Be(value2.GetHashCode()); - } - - [Fact] - public void None_are_not_equals_by_type() - { - var value1 = Maybe.None(); - var value2 = (object)Maybe.None(); - value1.Equals(value2).Should().BeFalse(); - } - - [Fact] - public void Some_equals_match_equality_op() - { - var value1 = Maybe.Some(new Value(0)); - var value2 = Maybe.Some(new Value(0)); - Assert.True(value1 == value2); - } - - [Fact] - public void Some_notEquals_dontMatch_equality_op() - { - var value1 = Maybe.Some(new Value(0)); - var value2 = Maybe.Some(new Value(1)); - Assert.True(value1 != value2); - } + [Fact] + public void ObjectEquals_null_return_false() + { + var value1 = Maybe.Some(new Value(0)); + object value2 = null!; + value1.Equals(value2).Should().BeFalse(); + } + + [Fact] + public void ObjectEquals_return_true() + { + var value1 = Maybe.Some(new Value(0)); + object value2 = Maybe.Some(new Value(0)); + value1.Equals(value2).Should().BeTrue(); + } + + [Fact] + public void Some_are_notEquals_to_null() + { + var value1 = Maybe.Some(new Value(0)); + value1.Equals(null).Should().BeFalse(); + } + + [Fact] + public void Some_are_equals() + { + var value1 = Maybe.Some(new Value(0)); + var value2 = Maybe.Some(new Value(0)); + value1.Equals(value2).Should().BeTrue(); + value1.GetHashCode().Should().Be(value2.GetHashCode()); + } + + [Fact] + public void Some_are_not_equals_by_inner_value() + { + var value1 = Maybe.Some(new Value(0)); + var value2 = Maybe.Some(new Value(1)); + value1.Equals(value2).Should().BeFalse(); + } + + [Fact] + public void Some_are_not_equals_by_inner_type() + { + var value1 = Maybe.Some(new Value(0)); + var value2 = (object)Maybe.Some(new AnotherValue(0)); + value1.Equals(value2).Should().BeFalse(); + } + + [Fact] + public void None_are_equals_by_type() + { + var value1 = Maybe.None(); + var value2 = Maybe.None(); + value1.Equals(value2).Should().BeTrue(); + value1.GetHashCode().Should().Be(value2.GetHashCode()); + } + + [Fact] + public void None_are_not_equals_by_type() + { + var value1 = Maybe.None(); + var value2 = (object)Maybe.None(); + value1.Equals(value2).Should().BeFalse(); + } + + [Fact] + public void Some_equals_match_equality_op() + { + var value1 = Maybe.Some(new Value(0)); + var value2 = Maybe.Some(new Value(0)); + Assert.True(value1 == value2); + } + + [Fact] + public void Some_notEquals_dontMatch_equality_op() + { + var value1 = Maybe.Some(new Value(0)); + var value2 = Maybe.Some(new Value(1)); + Assert.True(value1 != value2); + } } \ No newline at end of file diff --git a/test/Monads.UnitTests/MaybeTests/MaybeExecuteTests.cs b/test/Monads.UnitTests/MaybeTests/MaybeExecuteTests.cs index e19032b..280aa74 100644 --- a/test/Monads.UnitTests/MaybeTests/MaybeExecuteTests.cs +++ b/test/Monads.UnitTests/MaybeTests/MaybeExecuteTests.cs @@ -4,117 +4,117 @@ namespace Bogoware.Monads.UnitTests.MaybeTests; public class MaybeExecuteTests { - private readonly Mock _inspector = new(); - - [Fact] - public void IfSome_call_void_when_maybeIsSome() - { - var sut = Maybe.Some(new Value(0)); - sut.ExecuteIfSome(_inspector.Object.MethodVoid); - _inspector.Verify(i => i.MethodVoid()); - } - - [Fact] - public void IfSome_doesntCall_void_when_maybeIsNone() - { - var sut = Maybe.None(); - sut.ExecuteIfSome(_inspector.Object.MethodVoid); - _inspector.VerifyNoOtherCalls(); - } - - [Fact] - public void IfNone_doesntCall_void_when_maybeIsSome() - { - var sut = Maybe.None(); - sut.ExecuteIfNone(_inspector.Object.MethodVoid); - _inspector.Verify(i => i.MethodVoid()); - } - - [Fact] - public void IfNone_call_void_when_maybeIsNone() - { - var sut = Maybe.Some(new Value(0)); - sut.ExecuteIfNone(_inspector.Object.MethodVoid); - _inspector.VerifyNoOtherCalls(); - } - - [Fact] - public void IfSome_call_withArg_when_maybeIsSome() - { - var sut = Maybe.Some(new Value(0)); - sut.ExecuteIfSome(_inspector.Object.MethodWithValueArg); - _inspector.Verify(i => i.MethodWithValueArg(It.IsAny())); - } - - [Fact] - public void IfSome_doesntCall_withArg_when_maybeIsNone() - { - var sut = Maybe.None(); - sut.ExecuteIfSome(_inspector.Object.MethodWithValueArg); - _inspector.VerifyNoOtherCalls(); - } - - [Fact] - public async Task IfSome_call_async_when_maybeIsSome() - { - var sut = Maybe.Some(new Value(0)); - await sut.ExecuteIfSome(_inspector.Object.MethodVoidAsync); - _inspector.Verify(i => i.MethodVoidAsync()); - } - - [Fact] - public async Task IfSome_doesntCall_async_when_maybeIsNone() - { - var sut = Maybe.None(); - await sut.ExecuteIfSome(_inspector.Object.MethodVoidAsync); - _inspector.VerifyNoOtherCalls(); - } - - [Fact] - public async Task IfNone_doesntCall_async_when_maybeIsSome() - { - var sut = Maybe.None(); - await sut.ExecuteIfNone(_inspector.Object.MethodVoidAsync); - _inspector.Verify(i => i.MethodVoidAsync()); - } - - [Fact] - public async Task IfNone_call_void_async_maybeIsNone() - { - var sut = Maybe.Some(new Value(0)); - await sut.ExecuteIfNone(_inspector.Object.MethodVoidAsync); - _inspector.VerifyNoOtherCalls(); - } - - [Fact] - public async Task IfSome_call_asyncArg_when_maybeIsSome() - { - var sut = Maybe.Some(new Value(0)); - await sut.ExecuteIfSome(_inspector.Object.MethodWithValueArgAsync); - _inspector.Verify(i => i.MethodWithValueArgAsync(It.IsAny())); - } - - [Fact] - public async Task IfSome_doesntCall_asyncArg_when_maybeIsNone() - { - var sut = Maybe.None(); - await sut.ExecuteIfSome(_inspector.Object.MethodWithValueArgAsync); - _inspector.VerifyNoOtherCalls(); - } - - [Fact] - public void Execute_works() - { - var sut = Maybe.None(); - sut.Execute(_inspector.Object.MethodWithMaybeArg); - _inspector.Verify(i => i.MethodWithMaybeArg(It.IsAny>())); - } - - [Fact] - public async Task Execute_async_works() - { - var sut = Maybe.None(); - await sut.Execute(_inspector.Object.MethodWithMaybeArgAsync); - _inspector.Verify(i => i.MethodWithMaybeArgAsync(It.IsAny>())); - } + private readonly Mock _inspector = new(); + + [Fact] + public void IfSome_call_void_when_maybeIsSome() + { + var sut = Maybe.Some(new Value(0)); + sut.ExecuteIfSome(_inspector.Object.MethodVoid); + _inspector.Verify(i => i.MethodVoid()); + } + + [Fact] + public void IfSome_doesntCall_void_when_maybeIsNone() + { + var sut = Maybe.None(); + sut.ExecuteIfSome(_inspector.Object.MethodVoid); + _inspector.VerifyNoOtherCalls(); + } + + [Fact] + public void IfNone_doesntCall_void_when_maybeIsSome() + { + var sut = Maybe.None(); + sut.ExecuteIfNone(_inspector.Object.MethodVoid); + _inspector.Verify(i => i.MethodVoid()); + } + + [Fact] + public void IfNone_call_void_when_maybeIsNone() + { + var sut = Maybe.Some(new Value(0)); + sut.ExecuteIfNone(_inspector.Object.MethodVoid); + _inspector.VerifyNoOtherCalls(); + } + + [Fact] + public void IfSome_call_withArg_when_maybeIsSome() + { + var sut = Maybe.Some(new Value(0)); + sut.ExecuteIfSome(_inspector.Object.MethodWithValueArg); + _inspector.Verify(i => i.MethodWithValueArg(It.IsAny())); + } + + [Fact] + public void IfSome_doesntCall_withArg_when_maybeIsNone() + { + var sut = Maybe.None(); + sut.ExecuteIfSome(_inspector.Object.MethodWithValueArg); + _inspector.VerifyNoOtherCalls(); + } + + [Fact] + public async Task IfSome_call_async_when_maybeIsSome() + { + var sut = Maybe.Some(new Value(0)); + await sut.ExecuteIfSome(_inspector.Object.MethodVoidAsync); + _inspector.Verify(i => i.MethodVoidAsync()); + } + + [Fact] + public async Task IfSome_doesntCall_async_when_maybeIsNone() + { + var sut = Maybe.None(); + await sut.ExecuteIfSome(_inspector.Object.MethodVoidAsync); + _inspector.VerifyNoOtherCalls(); + } + + [Fact] + public async Task IfNone_doesntCall_async_when_maybeIsSome() + { + var sut = Maybe.None(); + await sut.ExecuteIfNone(_inspector.Object.MethodVoidAsync); + _inspector.Verify(i => i.MethodVoidAsync()); + } + + [Fact] + public async Task IfNone_call_void_async_maybeIsNone() + { + var sut = Maybe.Some(new Value(0)); + await sut.ExecuteIfNone(_inspector.Object.MethodVoidAsync); + _inspector.VerifyNoOtherCalls(); + } + + [Fact] + public async Task IfSome_call_asyncArg_when_maybeIsSome() + { + var sut = Maybe.Some(new Value(0)); + await sut.ExecuteIfSome(_inspector.Object.MethodWithValueArgAsync); + _inspector.Verify(i => i.MethodWithValueArgAsync(It.IsAny())); + } + + [Fact] + public async Task IfSome_doesntCall_asyncArg_when_maybeIsNone() + { + var sut = Maybe.None(); + await sut.ExecuteIfSome(_inspector.Object.MethodWithValueArgAsync); + _inspector.VerifyNoOtherCalls(); + } + + [Fact] + public void Execute_works() + { + var sut = Maybe.None(); + sut.Execute(_inspector.Object.MethodWithMaybeArg); + _inspector.Verify(i => i.MethodWithMaybeArg(It.IsAny>())); + } + + [Fact] + public async Task Execute_async_works() + { + var sut = Maybe.None(); + await sut.Execute(_inspector.Object.MethodWithMaybeArgAsync); + _inspector.Verify(i => i.MethodWithMaybeArgAsync(It.IsAny>())); + } } \ No newline at end of file diff --git a/test/Monads.UnitTests/MaybeTests/MaybeExtensionsTests.cs b/test/Monads.UnitTests/MaybeTests/MaybeExtensionsTests.cs index 2907ff8..956a636 100644 --- a/test/Monads.UnitTests/MaybeTests/MaybeExtensionsTests.cs +++ b/test/Monads.UnitTests/MaybeTests/MaybeExtensionsTests.cs @@ -2,54 +2,54 @@ namespace Bogoware.Monads.UnitTests.MaybeTests; public class MaybeExtensionsTests { - - [Fact] - public void NonEmptyEnumerable_produces_a_Some() - { - List values = new() { new(1), new(2) }; - var result = values.ToMaybe(); - result.IsSome.Should().BeTrue(); - result.GetValue(new Value(0)).Should().Be(new Value(1)); - } - - [Fact] - public void EmptyEnumerable_produces_a_None() - { - // ReSharper disable once CollectionNeverUpdated.Local - List values = new(); - var result = values.ToMaybe(); - result.IsNone.Should().BeTrue(); - } - - [Fact] - public void Where_satisfied_produces_a_Some() - { - var value = new Value(0); - var outcome = value.Where(v => v.Val == 0); - outcome.Equals(Maybe.Some(new Value(0))).Should().BeTrue(); - } - - [Fact] - public void Where_notSatisfied_produces_a_None() - { - var value = new Value(0); - var outcome = value.Where(v => v.Val == 1); - outcome.Equals(Maybe.None()).Should().BeTrue(); - } - - [Fact] - public void WhereNot_satisfied_produces_a_Some() - { - var value = new Value(0); - var outcome = value.WhereNot(v => v.Val == 1); - outcome.Equals(Maybe.Some(new Value(0))).Should().BeTrue(); - } - - [Fact] - public void WhereNot_notSatisfied_produces_a_None() - { - var value = new Value(0); - var outcome = value.WhereNot(v => v.Val == 0); - outcome.Equals(Maybe.None()).Should().BeTrue(); - } + + [Fact] + public void NonEmptyEnumerable_produces_a_Some() + { + List values = new() { new(1), new(2) }; + var result = values.ToMaybe(); + result.IsSome.Should().BeTrue(); + result.GetValue(new Value(0)).Should().Be(new Value(1)); + } + + [Fact] + public void EmptyEnumerable_produces_a_None() + { + // ReSharper disable once CollectionNeverUpdated.Local + List values = new(); + var result = values.ToMaybe(); + result.IsNone.Should().BeTrue(); + } + + [Fact] + public void Where_satisfied_produces_a_Some() + { + var value = new Value(0); + var outcome = value.Where(v => v.Val == 0); + outcome.Equals(Maybe.Some(new Value(0))).Should().BeTrue(); + } + + [Fact] + public void Where_notSatisfied_produces_a_None() + { + var value = new Value(0); + var outcome = value.Where(v => v.Val == 1); + outcome.Equals(Maybe.None()).Should().BeTrue(); + } + + [Fact] + public void WhereNot_satisfied_produces_a_Some() + { + var value = new Value(0); + var outcome = value.WhereNot(v => v.Val == 1); + outcome.Equals(Maybe.Some(new Value(0))).Should().BeTrue(); + } + + [Fact] + public void WhereNot_notSatisfied_produces_a_None() + { + var value = new Value(0); + var outcome = value.WhereNot(v => v.Val == 0); + outcome.Equals(Maybe.None()).Should().BeTrue(); + } } \ No newline at end of file diff --git a/test/Monads.UnitTests/MaybeTests/MaybeGetValueTests.cs b/test/Monads.UnitTests/MaybeTests/MaybeGetValueTests.cs index c445ab7..89a9fc2 100644 --- a/test/Monads.UnitTests/MaybeTests/MaybeGetValueTests.cs +++ b/test/Monads.UnitTests/MaybeTests/MaybeGetValueTests.cs @@ -3,39 +3,39 @@ namespace Bogoware.Monads.UnitTests.MaybeTests; public class MaybeGetValueTests { - [Fact] - public void Some_defaults_to_itsValue() - { - var some = Maybe.Some(new Value(666)); - var value = some.GetValue(new Value(0)); - - value.Should().Be(new Value(666)); - } - - [Fact] - public void None_defaults_to_defaultValue() - { - var some = Maybe.None(); - var value = some.GetValue(new Value(0)); - - value.Should().Be(new Value(0)); - } - - [Fact] - public void Some_lazyDefaults_to_itsValue() - { - var some = Maybe.Some(new Value(666)); - var value = some.GetValue(() => new Value(0)); - - value.Should().Be(new Value(666)); - } - - [Fact] - public void None_lazyDefaults_to_defaultValue() - { - var some = Maybe.None(); - var value = some.GetValue(() => new Value(0)); - - value.Should().Be(new Value(0)); - } + [Fact] + public void Some_defaults_to_itsValue() + { + var some = Maybe.Some(new Value(666)); + var value = some.GetValue(new Value(0)); + + value.Should().Be(new Value(666)); + } + + [Fact] + public void None_defaults_to_defaultValue() + { + var some = Maybe.None(); + var value = some.GetValue(new Value(0)); + + value.Should().Be(new Value(0)); + } + + [Fact] + public void Some_lazyDefaults_to_itsValue() + { + var some = Maybe.Some(new Value(666)); + var value = some.GetValue(() => new Value(0)); + + value.Should().Be(new Value(666)); + } + + [Fact] + public void None_lazyDefaults_to_defaultValue() + { + var some = Maybe.None(); + var value = some.GetValue(() => new Value(0)); + + value.Should().Be(new Value(0)); + } } \ No newline at end of file diff --git a/test/Monads.UnitTests/MaybeTests/MaybeLinqTests.cs b/test/Monads.UnitTests/MaybeTests/MaybeLinqTests.cs index 37b5054..00ecd4b 100644 --- a/test/Monads.UnitTests/MaybeTests/MaybeLinqTests.cs +++ b/test/Monads.UnitTests/MaybeTests/MaybeLinqTests.cs @@ -4,118 +4,118 @@ namespace Bogoware.Monads.UnitTests.MaybeTests; public class MaybeLinqTests { - [Fact] - public void Select_value_from_Some() - { - var sut = Maybe.Some(new Value(1)); - var values = - from v in sut - select v.Val; - - values.Should().BeEquivalentTo(new List { 1 }); - } - - [Fact] - public void Select_value_from_None() - { - var sut = Maybe.None(); - var values = - from v in sut - select v.Val; - - values.Should().BeEmpty(); - } - - [Fact] - public void Where_satisfied_returns_a_nonEmpty_enumerable() - { - var sut = Maybe.Some(new Value(1)); - var values = - from v in sut - where v.Val == 1 - select v.Val; - - values.Should().BeEquivalentTo(new List { 1 }); - } - - [Fact] - public void Where_notSatisfied_returns_an_Empty_enumerable() - { - var sut = Maybe.Some(new Value(1)); - var values = - from v in sut - where v.Val == 0 - select v.Val; - - values.Should().BeEmpty(); - } - - [Fact] - public void WhereNot_satisfied_returns_a_nonEmpty_enumerable() - { - var sut = Maybe.Some(new Value(1)); - var values = - from v in sut - where v.Val != 0 - select v.Val; - - values.Should().BeEquivalentTo(new List { 1 }); - } - - [Fact] - public void WhereNot_notSatisfied_returns_an_Empty_enumerable() - { - var sut = Maybe.Some(new Value(1)); - var values = - from v in sut - where v.Val != 1 - select v.Val; - - values.Should().BeEmpty(); - } - - [Fact] - public void Aggregate_values() - { - var maybes = new List> - { - Maybe.Some(new Value(1)), - Maybe.Some(new Value(2)), - Maybe.None, - Maybe.Some(new Value(3)), - Maybe.Some(new Value(4)), - }; - - // Pure linq style - var values1 = - from maybe in maybes - from value in maybe - where value.Val % 2 == 0 - select value.Val; - values1.Sum().Should().Be(6); - - // filter in pure linq style - var values2 = - from maybe in maybes.Where(v => v.Val % 2 == 0) - from v in maybe - select v.Val; - values2.Sum().Should().Be(6); - - // filter over monads - var values3 = - from maybe in maybes - where maybe.Satisfy(v => v.Val % 2 == 0) - from v in maybe - select v.Val; - values3.Sum().Should().Be(6); - - - } - - [Fact] - public void IEnumerable_coverage() - { - var sut = (IEnumerable) Maybe.Some(new Value(1)); - sut.GetEnumerator().Should().NotBeNull(); - } + [Fact] + public void Select_value_from_Some() + { + var sut = Maybe.Some(new Value(1)); + var values = + from v in sut + select v.Val; + + values.Should().BeEquivalentTo(new List { 1 }); + } + + [Fact] + public void Select_value_from_None() + { + var sut = Maybe.None(); + var values = + from v in sut + select v.Val; + + values.Should().BeEmpty(); + } + + [Fact] + public void Where_satisfied_returns_a_nonEmpty_enumerable() + { + var sut = Maybe.Some(new Value(1)); + var values = + from v in sut + where v.Val == 1 + select v.Val; + + values.Should().BeEquivalentTo(new List { 1 }); + } + + [Fact] + public void Where_notSatisfied_returns_an_Empty_enumerable() + { + var sut = Maybe.Some(new Value(1)); + var values = + from v in sut + where v.Val == 0 + select v.Val; + + values.Should().BeEmpty(); + } + + [Fact] + public void WhereNot_satisfied_returns_a_nonEmpty_enumerable() + { + var sut = Maybe.Some(new Value(1)); + var values = + from v in sut + where v.Val != 0 + select v.Val; + + values.Should().BeEquivalentTo(new List { 1 }); + } + + [Fact] + public void WhereNot_notSatisfied_returns_an_Empty_enumerable() + { + var sut = Maybe.Some(new Value(1)); + var values = + from v in sut + where v.Val != 1 + select v.Val; + + values.Should().BeEmpty(); + } + + [Fact] + public void Aggregate_values() + { + var maybes = new List> + { + Maybe.Some(new Value(1)), + Maybe.Some(new Value(2)), + Maybe.None, + Maybe.Some(new Value(3)), + Maybe.Some(new Value(4)), + }; + + // Pure linq style + var values1 = + from maybe in maybes + from value in maybe + where value.Val % 2 == 0 + select value.Val; + values1.Sum().Should().Be(6); + + // filter in pure linq style + var values2 = + from maybe in maybes.Where(v => v.Val % 2 == 0) + from v in maybe + select v.Val; + values2.Sum().Should().Be(6); + + // filter over monads + var values3 = + from maybe in maybes + where maybe.Satisfy(v => v.Val % 2 == 0) + from v in maybe + select v.Val; + values3.Sum().Should().Be(6); + + + } + + [Fact] + public void IEnumerable_coverage() + { + var sut = (IEnumerable)Maybe.Some(new Value(1)); + sut.GetEnumerator().Should().NotBeNull(); + } } \ No newline at end of file diff --git a/test/Monads.UnitTests/MaybeTests/MaybeMapTests.cs b/test/Monads.UnitTests/MaybeTests/MaybeMapTests.cs index 8d794ac..9ebfaa0 100644 --- a/test/Monads.UnitTests/MaybeTests/MaybeMapTests.cs +++ b/test/Monads.UnitTests/MaybeTests/MaybeMapTests.cs @@ -3,52 +3,52 @@ namespace Bogoware.Monads.UnitTests.MaybeTests; public class MaybeMapTests { - [Fact] - public void Some_mapsTo_SomeValue() - { - var value = Maybe.Some("0"); - Maybe newValue = value.Map("Hello"); - newValue.IsSome.Should().BeTrue(); - } - - [Fact] - public void Some_mapsTo_SomeValue_by_action() - { - var value = Maybe.Some("0"); - Maybe newValue = value.Map(() => "Hello"); - newValue.IsSome.Should().BeTrue(); - } - - [Fact] - public void Some_mapsTo_SomeValue_by_function() - { - var value = Maybe.Some("0"); - Maybe newValue = value.Map(num => $"Hello {num}"); - newValue.IsSome.Should().BeTrue(); - } - - [Fact] - public void None_mapsTo_None_by_Value() - { - var value = Maybe.None(); - value.IsNone.Should().BeTrue(); - Maybe newValue = value.Map("Hello"); - newValue.IsNone.Should().BeTrue(); - } - - [Fact] - public void None_mapsTo_None_by_action() - { - var value = Maybe.None(); - Maybe newValue = value.Map(() => "Hello"); - newValue.IsNone.Should().BeTrue(); - } - - [Fact] - public void None_mapsTo_None_by_function() - { - var value = Maybe.None(); - Maybe newValue = value.Map(num => $"Hello {num}"); - newValue.IsNone.Should().BeTrue(); - } + [Fact] + public void Some_mapsTo_SomeValue() + { + var value = Maybe.Some("0"); + Maybe newValue = value.Map("Hello"); + newValue.IsSome.Should().BeTrue(); + } + + [Fact] + public void Some_mapsTo_SomeValue_by_action() + { + var value = Maybe.Some("0"); + Maybe newValue = value.Map(() => "Hello"); + newValue.IsSome.Should().BeTrue(); + } + + [Fact] + public void Some_mapsTo_SomeValue_by_function() + { + var value = Maybe.Some("0"); + Maybe newValue = value.Map(num => $"Hello {num}"); + newValue.IsSome.Should().BeTrue(); + } + + [Fact] + public void None_mapsTo_None_by_Value() + { + var value = Maybe.None(); + value.IsNone.Should().BeTrue(); + Maybe newValue = value.Map("Hello"); + newValue.IsNone.Should().BeTrue(); + } + + [Fact] + public void None_mapsTo_None_by_action() + { + var value = Maybe.None(); + Maybe newValue = value.Map(() => "Hello"); + newValue.IsNone.Should().BeTrue(); + } + + [Fact] + public void None_mapsTo_None_by_function() + { + var value = Maybe.None(); + Maybe newValue = value.Map(num => $"Hello {num}"); + newValue.IsNone.Should().BeTrue(); + } } \ No newline at end of file diff --git a/test/Monads.UnitTests/MaybeTests/MaybeMatchTests.cs b/test/Monads.UnitTests/MaybeTests/MaybeMatchTests.cs index 716cfd6..d5340bd 100644 --- a/test/Monads.UnitTests/MaybeTests/MaybeMatchTests.cs +++ b/test/Monads.UnitTests/MaybeTests/MaybeMatchTests.cs @@ -2,99 +2,99 @@ namespace Bogoware.Monads.UnitTests.MaybeTests; public class MaybeMatchTests { - [Fact] - public void Match_some_with_values() - { - var sut = Maybe.Some("Hello World"); - var actual = sut.Match("some", "none"); - actual.Should().Be("some"); - } - - [Fact] - public void Match_none_with_values() - { - var sut = Maybe.None(); - var actual = sut.Match("some", "none"); - actual.Should().Be("none"); - } - - [Fact] - public void Match_some_with_funcAndValue() - { - var sut = Maybe.Some("Hello World"); - var actual = sut.Match(_ => "some", "none"); - actual.Should().Be("some"); - } - - [Fact] - public void Match_none_with_funcAndValue() - { - var sut = Maybe.None(); - var actual = sut.Match(_ => "some", "none"); - actual.Should().Be("none"); - } - - [Fact] - public void Match_some_with_funcs() - { - var sut = Maybe.Some("Hello World"); - var actual = sut.Match(_ => "some", () => "none"); - actual.Should().Be("some"); - } - - [Fact] - public void Match_none_with_funcs() - { - var sut = Maybe.None(); - var actual = sut.Match(_ => "some", () => "none"); - actual.Should().Be("none"); - } - - [Fact] - public async Task Match_some_with_leftAsync() - { - var sut = Maybe.Some("Hello World"); - var actual = await sut.Match(_ => Task.FromResult("some"), () => "none"); - actual.Should().Be("some"); - } - - [Fact] - public async Task Match_none_with_leftAsync() - { - var sut = Maybe.None(); - var actual = await sut.Match(_ => Task.FromResult("some"), () => "none"); - actual.Should().Be("none"); - } - - [Fact] - public async Task Match_some_with_rightAsync() - { - var sut = Maybe.Some("Hello World"); - var actual = await sut.Match(_ => "some", () => Task.FromResult("none")); - actual.Should().Be("some"); - } - - [Fact] - public async Task Match_none_with_rightAsync() - { - var sut = Maybe.None(); - var actual = await sut.Match(_ => "some", () => Task.FromResult("none")); - actual.Should().Be("none"); - } - - [Fact] - public async Task Match_some_with_bothAsync() - { - var sut = Maybe.Some("Hello World"); - var actual = await sut.Match(_ => Task.FromResult("some"), () => Task.FromResult("none")); - actual.Should().Be("some"); - } - - [Fact] - public async Task Match_none_with_bothAsync() - { - var sut = Maybe.None(); - var actual = await sut.Match(_ => Task.FromResult("some"), () => Task.FromResult("none")); - actual.Should().Be("none"); - } + [Fact] + public void Match_some_with_values() + { + var sut = Maybe.Some("Hello World"); + var actual = sut.Match("some", "none"); + actual.Should().Be("some"); + } + + [Fact] + public void Match_none_with_values() + { + var sut = Maybe.None(); + var actual = sut.Match("some", "none"); + actual.Should().Be("none"); + } + + [Fact] + public void Match_some_with_funcAndValue() + { + var sut = Maybe.Some("Hello World"); + var actual = sut.Match(_ => "some", "none"); + actual.Should().Be("some"); + } + + [Fact] + public void Match_none_with_funcAndValue() + { + var sut = Maybe.None(); + var actual = sut.Match(_ => "some", "none"); + actual.Should().Be("none"); + } + + [Fact] + public void Match_some_with_funcs() + { + var sut = Maybe.Some("Hello World"); + var actual = sut.Match(_ => "some", () => "none"); + actual.Should().Be("some"); + } + + [Fact] + public void Match_none_with_funcs() + { + var sut = Maybe.None(); + var actual = sut.Match(_ => "some", () => "none"); + actual.Should().Be("none"); + } + + [Fact] + public async Task Match_some_with_leftAsync() + { + var sut = Maybe.Some("Hello World"); + var actual = await sut.Match(_ => Task.FromResult("some"), () => "none"); + actual.Should().Be("some"); + } + + [Fact] + public async Task Match_none_with_leftAsync() + { + var sut = Maybe.None(); + var actual = await sut.Match(_ => Task.FromResult("some"), () => "none"); + actual.Should().Be("none"); + } + + [Fact] + public async Task Match_some_with_rightAsync() + { + var sut = Maybe.Some("Hello World"); + var actual = await sut.Match(_ => "some", () => Task.FromResult("none")); + actual.Should().Be("some"); + } + + [Fact] + public async Task Match_none_with_rightAsync() + { + var sut = Maybe.None(); + var actual = await sut.Match(_ => "some", () => Task.FromResult("none")); + actual.Should().Be("none"); + } + + [Fact] + public async Task Match_some_with_bothAsync() + { + var sut = Maybe.Some("Hello World"); + var actual = await sut.Match(_ => Task.FromResult("some"), () => Task.FromResult("none")); + actual.Should().Be("some"); + } + + [Fact] + public async Task Match_none_with_bothAsync() + { + var sut = Maybe.None(); + var actual = await sut.Match(_ => Task.FromResult("some"), () => Task.FromResult("none")); + actual.Should().Be("none"); + } } \ No newline at end of file diff --git a/test/Monads.UnitTests/MaybeTests/MaybeOfTypeTests.cs b/test/Monads.UnitTests/MaybeTests/MaybeOfTypeTests.cs index da0d3be..982add8 100644 --- a/test/Monads.UnitTests/MaybeTests/MaybeOfTypeTests.cs +++ b/test/Monads.UnitTests/MaybeTests/MaybeOfTypeTests.cs @@ -3,31 +3,31 @@ namespace Bogoware.Monads.UnitTests.MaybeTests; public class MaybeOfTypeTests { - class Base - { - - } - - class Derived : Base - { - - } - - [Fact] - public void SuccessfulDowncast_produces_Some() - { - Maybe value1 = Maybe.Some((Base)new Derived()); - Maybe value2 = value1.OfType(); - - value2.IsSome.Should().BeTrue(); - } - - [Fact] - public void ImpossibleDowncast_produces_None() - { - Maybe value1 = Maybe.Some(""); - Maybe value2 = value1.OfType(); - - value2.IsNone.Should().BeTrue(); - } + class Base + { + + } + + class Derived : Base + { + + } + + [Fact] + public void SuccessfulDowncast_produces_Some() + { + Maybe value1 = Maybe.Some((Base)new Derived()); + Maybe value2 = value1.OfType(); + + value2.IsSome.Should().BeTrue(); + } + + [Fact] + public void ImpossibleDowncast_produces_None() + { + Maybe value1 = Maybe.Some(""); + Maybe value2 = value1.OfType(); + + value2.IsNone.Should().BeTrue(); + } } \ No newline at end of file diff --git a/test/Monads.UnitTests/MaybeTests/MaybeOperatorsTests.cs b/test/Monads.UnitTests/MaybeTests/MaybeOperatorsTests.cs index 2df2537..0b91ef7 100644 --- a/test/Monads.UnitTests/MaybeTests/MaybeOperatorsTests.cs +++ b/test/Monads.UnitTests/MaybeTests/MaybeOperatorsTests.cs @@ -2,23 +2,23 @@ namespace Bogoware.Monads.UnitTests.MaybeTests; public class MaybeOperatorsTests { - [Fact] - public void Implicit_conversion_to_Some() - { - Maybe GetSome() => new Value(0); + [Fact] + public void Implicit_conversion_to_Some() + { + Maybe GetSome() => new Value(0); - var value = GetSome(); + var value = GetSome(); - value.Equals(Maybe.Some(new Value(0))).Should().BeTrue(); - } - - [Fact] - public void Implicit_conversion_to_None() - { - Maybe GetSome() => null; + value.Equals(Maybe.Some(new Value(0))).Should().BeTrue(); + } - var value = GetSome(); + [Fact] + public void Implicit_conversion_to_None() + { + Maybe GetSome() => null; - value.Equals(Maybe.None()).Should().BeTrue(); - } + var value = GetSome(); + + value.Equals(Maybe.None()).Should().BeTrue(); + } } \ No newline at end of file diff --git a/test/Monads.UnitTests/MaybeTests/MaybeTests.cs b/test/Monads.UnitTests/MaybeTests/MaybeTests.cs index 1e313e0..49eaa38 100644 --- a/test/Monads.UnitTests/MaybeTests/MaybeTests.cs +++ b/test/Monads.UnitTests/MaybeTests/MaybeTests.cs @@ -2,17 +2,17 @@ namespace Bogoware.Monads.UnitTests.MaybeTests; public class MaybeTests { - [Fact] - public void Unit_success() - { - var value = Result.Unit; - value.Equals(Unit.Instance).Should().Be(true); - } - - [Fact] - public void None_success() - { - var value = Maybe.None(); - value.Equals(Maybe.None()).Should().Be(true); - } + [Fact] + public void Unit_success() + { + var value = Result.Unit; + value.Equals(Unit.Instance).Should().Be(true); + } + + [Fact] + public void None_success() + { + var value = Maybe.None(); + value.Equals(Maybe.None()).Should().Be(true); + } } \ No newline at end of file diff --git a/test/Monads.UnitTests/MaybeTests/MaybeToResultTests.cs b/test/Monads.UnitTests/MaybeTests/MaybeToResultTests.cs index 03b4ed0..be5b337 100644 --- a/test/Monads.UnitTests/MaybeTests/MaybeToResultTests.cs +++ b/test/Monads.UnitTests/MaybeTests/MaybeToResultTests.cs @@ -2,47 +2,47 @@ namespace Bogoware.Monads.UnitTests.MaybeTests; public class MaybeToResultTests { - [Fact] - public void Some_ToResult_ShouldReturnAnError() - { - var sut = Maybe.Some("SomeValue"); - - var actual = sut.ToResult(() => new LogicError("Not Found")); - - actual.IsSuccess.Should().BeTrue(); - actual.GetValueOrThrow().Should().Be("SomeValue"); - } - - [Fact] - public void None_ToResult_ShouldReturnAnError() - { - var sut = Maybe.None(); - - var actual = sut.ToResult(() => new LogicError("Not Found")); - - actual.IsFailure.Should().BeTrue(); - } - - [Fact] - public async Task Some_ToResult_ShouldReturnAnError_withAsync() - { - var sut = Maybe.Some("SomeValue"); - var errorFunc = new Func>(() => Task.FromResult(new LogicError("Not Found"))); - - var actual = await sut.ToResult(errorFunc); - - actual.IsSuccess.Should().BeTrue(); - actual.GetValueOrThrow().Should().Be("SomeValue"); - } - - [Fact] - public async Task None_ToResult_ShouldReturnAnError_withAsync() - { - var sut = Maybe.None(); - var errorFunc = new Func>(() => Task.FromResult(new LogicError("Not Found"))); - - var actual = await sut.ToResult(errorFunc); - - actual.IsFailure.Should().BeTrue(); - } + [Fact] + public void Some_ToResult_ShouldReturnAnError() + { + var sut = Maybe.Some("SomeValue"); + + var actual = sut.ToResult(() => new LogicError("Not Found")); + + actual.IsSuccess.Should().BeTrue(); + actual.GetValueOrThrow().Should().Be("SomeValue"); + } + + [Fact] + public void None_ToResult_ShouldReturnAnError() + { + var sut = Maybe.None(); + + var actual = sut.ToResult(() => new LogicError("Not Found")); + + actual.IsFailure.Should().BeTrue(); + } + + [Fact] + public async Task Some_ToResult_ShouldReturnAnError_withAsync() + { + var sut = Maybe.Some("SomeValue"); + var errorFunc = new Func>(() => Task.FromResult(new LogicError("Not Found"))); + + var actual = await sut.ToResult(errorFunc); + + actual.IsSuccess.Should().BeTrue(); + actual.GetValueOrThrow().Should().Be("SomeValue"); + } + + [Fact] + public async Task None_ToResult_ShouldReturnAnError_withAsync() + { + var sut = Maybe.None(); + var errorFunc = new Func>(() => Task.FromResult(new LogicError("Not Found"))); + + var actual = await sut.ToResult(errorFunc); + + actual.IsFailure.Should().BeTrue(); + } } \ No newline at end of file diff --git a/test/Monads.UnitTests/MaybeTests/MaybeToStringTests.cs b/test/Monads.UnitTests/MaybeTests/MaybeToStringTests.cs index b39faa7..663672a 100644 --- a/test/Monads.UnitTests/MaybeTests/MaybeToStringTests.cs +++ b/test/Monads.UnitTests/MaybeTests/MaybeToStringTests.cs @@ -2,28 +2,28 @@ namespace Bogoware.Monads.UnitTests.MaybeTests; public class MaybeToStringTests { - [Fact] - public void Some_toString() - { - var value = Maybe.Some("Hello"); - value.ToString().Should().Be("Some(Hello)"); - } - [Fact] - public void None_toString() - { - var value = Maybe.None(); - value.ToString().Should().Be("None()"); - } - [Fact] - public void NoneUnit_toString() - { - var value = Maybe.None(); - value.ToString().Should().Be("None()"); - } - [Fact] - public void NoneGenerics_toString() - { - var value = Maybe.None>(); - value.ToString().Should().Be("None>()"); - } + [Fact] + public void Some_toString() + { + var value = Maybe.Some("Hello"); + value.ToString().Should().Be("Some(Hello)"); + } + [Fact] + public void None_toString() + { + var value = Maybe.None(); + value.ToString().Should().Be("None()"); + } + [Fact] + public void NoneUnit_toString() + { + var value = Maybe.None(); + value.ToString().Should().Be("None()"); + } + [Fact] + public void NoneGenerics_toString() + { + var value = Maybe.None>(); + value.ToString().Should().Be("None>()"); + } } \ No newline at end of file diff --git a/test/Monads.UnitTests/MaybeTests/MaybeWithDefaultTests.cs b/test/Monads.UnitTests/MaybeTests/MaybeWithDefaultTests.cs index f83b5d5..149937b 100644 --- a/test/Monads.UnitTests/MaybeTests/MaybeWithDefaultTests.cs +++ b/test/Monads.UnitTests/MaybeTests/MaybeWithDefaultTests.cs @@ -2,30 +2,30 @@ namespace Bogoware.Monads.UnitTests.MaybeTests; public class MaybeWithDefaultTests { - [Fact] - public void WithDefault_value() - { - var none = Maybe.None(); - var some = none.WithDefault("Some"); - some.IsSome.Should().BeTrue(); - some.GetValue("").Should().Be("Some"); - } - - [Fact] - public void WithDefault_function() - { - var none = Maybe.None(); - var some = none.WithDefault(() => "Some"); - some.IsSome.Should().BeTrue(); - some.GetValue("").Should().Be("Some"); - } - - [Fact] - public async Task WithDefault_asyncFunction() - { - var none = Maybe.None(); - var some = await none.WithDefault(() => Task.FromResult("Some")); - some.IsSome.Should().BeTrue(); - some.GetValue("").Should().Be("Some"); - } + [Fact] + public void WithDefault_value() + { + var none = Maybe.None(); + var some = none.WithDefault("Some"); + some.IsSome.Should().BeTrue(); + some.GetValue("").Should().Be("Some"); + } + + [Fact] + public void WithDefault_function() + { + var none = Maybe.None(); + var some = none.WithDefault(() => "Some"); + some.IsSome.Should().BeTrue(); + some.GetValue("").Should().Be("Some"); + } + + [Fact] + public async Task WithDefault_asyncFunction() + { + var none = Maybe.None(); + var some = await none.WithDefault(() => Task.FromResult("Some")); + some.IsSome.Should().BeTrue(); + some.GetValue("").Should().Be("Some"); + } } \ No newline at end of file diff --git a/test/Monads.UnitTests/ResultTests/ResultBindTests.cs b/test/Monads.UnitTests/ResultTests/ResultBindTests.cs index f257615..28fc092 100644 --- a/test/Monads.UnitTests/ResultTests/ResultBindTests.cs +++ b/test/Monads.UnitTests/ResultTests/ResultBindTests.cs @@ -3,78 +3,78 @@ namespace Bogoware.Monads.UnitTests.ResultTests; public class ResultBindTests { - private static readonly Result _success = new(new Value(0)); - private static readonly Result _failed = new(new LogicError("Something went wrong")); + private static readonly Result _success = new(new Value(0)); + private static readonly Result _failed = new(new LogicError("Something went wrong")); - [Fact] - public void Success_bind_constant() - { - Result actual = _success.Bind(new Result("success")); - actual.IsSuccess.Should().BeTrue(); - } + [Fact] + public void Success_bind_constant() + { + Result actual = _success.Bind(new Result("success")); + actual.IsSuccess.Should().BeTrue(); + } - [Fact] - public void Failure_bind_constant() - { - Result actual = _failed.Bind(new Result("success")); - actual.IsFailure.Should().BeTrue(); - } + [Fact] + public void Failure_bind_constant() + { + Result actual = _failed.Bind(new Result("success")); + actual.IsFailure.Should().BeTrue(); + } - [Fact] - public void Success_bind_voidFunction() - { - Result actual = _success.Bind(() => new Result("success")); - actual.IsSuccess.Should().BeTrue(); - } + [Fact] + public void Success_bind_voidFunction() + { + Result actual = _success.Bind(() => new Result("success")); + actual.IsSuccess.Should().BeTrue(); + } - [Fact] - public void Failure_bind_voidFunction() - { - Result actual = _failed.Bind(() => new Result("success")); - actual.IsFailure.Should().BeTrue(); - } + [Fact] + public void Failure_bind_voidFunction() + { + Result actual = _failed.Bind(() => new Result("success")); + actual.IsFailure.Should().BeTrue(); + } - [Fact] - public async Task Success_bind_asyncVoidFunction() - { - Result actual = await _success.Bind(() => Task.FromResult(new Result("success"))); - actual.IsSuccess.Should().BeTrue(); - } + [Fact] + public async Task Success_bind_asyncVoidFunction() + { + Result actual = await _success.Bind(() => Task.FromResult(new Result("success"))); + actual.IsSuccess.Should().BeTrue(); + } - [Fact] - public async Task Failure_bind_asyncVoidFunction() - { - Result actual = await _failed.Bind(() => Task.FromResult(new Result("success"))); - actual.IsFailure.Should().BeTrue(); - } + [Fact] + public async Task Failure_bind_asyncVoidFunction() + { + Result actual = await _failed.Bind(() => Task.FromResult(new Result("success"))); + actual.IsFailure.Should().BeTrue(); + } - [Fact] - public void Success_bind_function() - { - Result actual = _success.Bind(success => new Result($"success: {success}")); - actual.IsSuccess.Should().BeTrue(); - } + [Fact] + public void Success_bind_function() + { + Result actual = _success.Bind(success => new Result($"success: {success}")); + actual.IsSuccess.Should().BeTrue(); + } - [Fact] - public void Failure_bind_function() - { - Result actual = _failed.Bind(success => new Result($"success: {success}")); - actual.IsFailure.Should().BeTrue(); - } + [Fact] + public void Failure_bind_function() + { + Result actual = _failed.Bind(success => new Result($"success: {success}")); + actual.IsFailure.Should().BeTrue(); + } - [Fact] - public async Task Success_bind_asyncFunction() - { - Result actual = - await _success.Bind(success => Task.FromResult(new Result($"success: {success}"))); - actual.IsSuccess.Should().BeTrue(); - } + [Fact] + public async Task Success_bind_asyncFunction() + { + Result actual = + await _success.Bind(success => Task.FromResult(new Result($"success: {success}"))); + actual.IsSuccess.Should().BeTrue(); + } - [Fact] - public async Task Failure_bind_asyncFunction() - { - Result actual = - await _failed.Bind(success => Task.FromResult(new Result($"success: {success}"))); - actual.IsFailure.Should().BeTrue(); - } + [Fact] + public async Task Failure_bind_asyncFunction() + { + Result actual = + await _failed.Bind(success => Task.FromResult(new Result($"success: {success}"))); + actual.IsFailure.Should().BeTrue(); + } } \ No newline at end of file diff --git a/test/Monads.UnitTests/ResultTests/ResultCreationTests.cs b/test/Monads.UnitTests/ResultTests/ResultCreationTests.cs index 804108d..c497765 100644 --- a/test/Monads.UnitTests/ResultTests/ResultCreationTests.cs +++ b/test/Monads.UnitTests/ResultTests/ResultCreationTests.cs @@ -2,127 +2,127 @@ namespace Bogoware.Monads.UnitTests.ResultTests; public class ResultCreationTests { - [Fact] - public void Create_successful_result() - { - var sut = Result.Success(new Value(0)); - sut.IsSuccess.Should().BeTrue(); - sut.IsFailure.Should().BeFalse(); - } - - [Fact] - public void Create_failed_result() - { - var sut = Result.Failure(new LogicError("Something went wrong")); - sut.IsSuccess.Should().BeFalse(); - sut.IsFailure.Should().BeTrue(); - } - - [Fact] - public void Create_successful_unitResult() - { - var sut = Result.Unit; - sut.IsSuccess.Should().BeTrue(); - sut.IsFailure.Should().BeFalse(); - } - - [Fact] - public void Create_failed_unitResult() - { - Result sut = new LogicError("Something went wrong"); - sut.IsSuccess.Should().BeFalse(); - sut.IsFailure.Should().BeTrue(); - } - - [Fact] - public void GetValue_works_with_successfulResults() - { - var sut = Result.Unit; - var unit = sut.GetValueOrThrow(); - unit.Should().NotBeNull(); - } - - [Fact] - public void GetValue_works_with_failedResults() - { - Result sut = new LogicError("Something went wrong"); - - sut - .Invoking(u => u.GetValueOrThrow()) - .Should().ThrowExactly(); - } - - [Fact] - public void GetError_works_with_failedResults() - { - Result sut = new LogicError("Something went wrong"); - var unit = sut.GetErrorOrThrow(); - unit.Should().NotBeNull(); - } - - [Fact] - public void GetError_works_with_successResults() - { - var sut = Result.Unit; - - sut - .Invoking(u => u.GetErrorOrThrow()) - .Should().ThrowExactly(); - } - - [Fact] - public void Create_successful_with_struct_result() - { - var sut = Result.Success(true); - sut.IsSuccess.Should().BeTrue(); - sut.IsFailure.Should().BeFalse(); - } - - [Fact] - public void Create_failed_with_struct_result() - { - var sut = Result.Failure(new LogicError("Something went wrong")); - sut.IsSuccess.Should().BeFalse(); - sut.IsFailure.Should().BeTrue(); - } - - [Fact] - public void Create_copy_ctor_successful() - { - var result1 = Result.Success("value"); - var result2 = new Result(result1); - result1.IsSuccess.Should().Be(result2.IsSuccess); - result1.IsFailure.Should().Be(result2.IsFailure); - result1.GetValueOrThrow().Should().Be(result2.GetValueOrThrow()); - } - - [Fact] - public void Create_copy_ctor_failure() - { - var result1 = Result.Failure("some error"); - var result2 = new Result(result1); - result1.IsSuccess.Should().Be(result2.IsSuccess); - result1.IsFailure.Should().Be(result2.IsFailure); - result1.GetErrorOrThrow().Should().Be(result2.GetErrorOrThrow()); - } - - [Fact] - public void Create_via_Result_from_successful_result() - { - var result1 = Result.Success("value"); - var result2 = Result.Bind(() => result1); - result1.IsSuccess.Should().Be(result2.IsSuccess); - result1.IsFailure.Should().Be(result2.IsFailure); - result1.GetValueOrThrow().Should().Be(result2.GetValueOrThrow()); - } - - [Fact] - public async Task Create_via_Result_from_successful_result_async() - { - var result1 = Result.Success("value"); - var result2 = await Result.Bind(() => Task.FromResult(result1)); - result1.IsSuccess.Should().Be(result2.IsSuccess); - result1.IsFailure.Should().Be(result2.IsFailure); - result1.GetValueOrThrow().Should().Be(result2.GetValueOrThrow()); - } + [Fact] + public void Create_successful_result() + { + var sut = Result.Success(new Value(0)); + sut.IsSuccess.Should().BeTrue(); + sut.IsFailure.Should().BeFalse(); + } + + [Fact] + public void Create_failed_result() + { + var sut = Result.Failure(new LogicError("Something went wrong")); + sut.IsSuccess.Should().BeFalse(); + sut.IsFailure.Should().BeTrue(); + } + + [Fact] + public void Create_successful_unitResult() + { + var sut = Result.Unit; + sut.IsSuccess.Should().BeTrue(); + sut.IsFailure.Should().BeFalse(); + } + + [Fact] + public void Create_failed_unitResult() + { + Result sut = new LogicError("Something went wrong"); + sut.IsSuccess.Should().BeFalse(); + sut.IsFailure.Should().BeTrue(); + } + + [Fact] + public void GetValue_works_with_successfulResults() + { + var sut = Result.Unit; + var unit = sut.GetValueOrThrow(); + unit.Should().NotBeNull(); + } + + [Fact] + public void GetValue_works_with_failedResults() + { + Result sut = new LogicError("Something went wrong"); + + sut + .Invoking(u => u.GetValueOrThrow()) + .Should().ThrowExactly(); + } + + [Fact] + public void GetError_works_with_failedResults() + { + Result sut = new LogicError("Something went wrong"); + var unit = sut.GetErrorOrThrow(); + unit.Should().NotBeNull(); + } + + [Fact] + public void GetError_works_with_successResults() + { + var sut = Result.Unit; + + sut + .Invoking(u => u.GetErrorOrThrow()) + .Should().ThrowExactly(); + } + + [Fact] + public void Create_successful_with_struct_result() + { + var sut = Result.Success(true); + sut.IsSuccess.Should().BeTrue(); + sut.IsFailure.Should().BeFalse(); + } + + [Fact] + public void Create_failed_with_struct_result() + { + var sut = Result.Failure(new LogicError("Something went wrong")); + sut.IsSuccess.Should().BeFalse(); + sut.IsFailure.Should().BeTrue(); + } + + [Fact] + public void Create_copy_ctor_successful() + { + var result1 = Result.Success("value"); + var result2 = new Result(result1); + result1.IsSuccess.Should().Be(result2.IsSuccess); + result1.IsFailure.Should().Be(result2.IsFailure); + result1.GetValueOrThrow().Should().Be(result2.GetValueOrThrow()); + } + + [Fact] + public void Create_copy_ctor_failure() + { + var result1 = Result.Failure("some error"); + var result2 = new Result(result1); + result1.IsSuccess.Should().Be(result2.IsSuccess); + result1.IsFailure.Should().Be(result2.IsFailure); + result1.GetErrorOrThrow().Should().Be(result2.GetErrorOrThrow()); + } + + [Fact] + public void Create_via_Result_from_successful_result() + { + var result1 = Result.Success("value"); + var result2 = Result.Bind(() => result1); + result1.IsSuccess.Should().Be(result2.IsSuccess); + result1.IsFailure.Should().Be(result2.IsFailure); + result1.GetValueOrThrow().Should().Be(result2.GetValueOrThrow()); + } + + [Fact] + public async Task Create_via_Result_from_successful_result_async() + { + var result1 = Result.Success("value"); + var result2 = await Result.Bind(() => Task.FromResult(result1)); + result1.IsSuccess.Should().Be(result2.IsSuccess); + result1.IsFailure.Should().Be(result2.IsFailure); + result1.GetValueOrThrow().Should().Be(result2.GetValueOrThrow()); + } } \ No newline at end of file diff --git a/test/Monads.UnitTests/ResultTests/ResultEnsureTests.cs b/test/Monads.UnitTests/ResultTests/ResultEnsureTests.cs index eb55079..eeb6c9d 100644 --- a/test/Monads.UnitTests/ResultTests/ResultEnsureTests.cs +++ b/test/Monads.UnitTests/ResultTests/ResultEnsureTests.cs @@ -3,90 +3,90 @@ namespace Bogoware.Monads.UnitTests.ResultTests; public class ResultEnsureTests { - private static readonly Result _success = new(new Value(0)); - private static readonly Result _failed = new(new LogicError("Something went wrong")); + private static readonly Result _success = new(new Value(0)); + private static readonly Result _failed = new(new LogicError("Something went wrong")); - [Fact] - public void Success_predicateTrue_constant() - { - var actual = _success.Ensure(value => true, new LogicError("Failed")); - actual.IsSuccess.Should().BeTrue(); - } - - [Fact] - public void Success_predicateFalse_constant() - { - var actual = _success.Ensure(value => false, new LogicError("Failed")); - actual.IsFailure.Should().BeTrue(); - } - - [Fact] - public void Failure_predicateTrue_constant() - { - var actual = _failed.Ensure(value => true, new LogicError("Failed")); - actual.IsFailure.Should().BeTrue(); - } - - [Fact] - public void Failure_predicateFalse_constant() - { - var actual = _failed.Ensure(value => false, new LogicError("Failed")); - actual.IsFailure.Should().BeTrue(); - } - - [Fact] - public async Task Success_asyncPredicateTrue_constant() - { - var actual = await _success.Ensure(value => Task.FromResult( true), new LogicError("Failed")); - actual.IsSuccess.Should().BeTrue(); - } - - [Fact] - public async Task Success_asyncPredicateFalse_constant() - { - var actual = await _success.Ensure(value => Task.FromResult(false), new LogicError("Failed")); - actual.IsFailure.Should().BeTrue(); - } - - [Fact] - public async Task Failure_asyncPredicateTrue_constant() - { - var actual = await _failed.Ensure(value => Task.FromResult(true), new LogicError("Failed")); - actual.IsFailure.Should().BeTrue(); - } - - [Fact] - public async Task Failure_asyncPredicateFalse_constant() - { - var actual = await _failed.Ensure(value => Task.FromResult(false), new LogicError("Failed")); - actual.IsFailure.Should().BeTrue(); - } - - [Fact] - public void Success_predicateTrue_function() - { - var actual = _success.Ensure(value => true, () => new LogicError("Failed")); - actual.IsSuccess.Should().BeTrue(); - } - - [Fact] - public void Success_predicateFalse_function() - { - var actual = _success.Ensure(value => false, () => new LogicError("Failed")); - actual.IsFailure.Should().BeTrue(); - } - - [Fact] - public async Task Success_predicateTrue_asyncFunction() - { - var actual = await _success.Ensure(value => true, () => Task.FromResult(new LogicError("Failed"))); - actual.IsSuccess.Should().BeTrue(); - } - - [Fact] - public async Task Success_predicateFalse_asyncFunction() - { - var actual = await _success.Ensure(value => false, () => Task.FromResult(new LogicError("Failed"))); - actual.IsFailure.Should().BeTrue(); - } + [Fact] + public void Success_predicateTrue_constant() + { + var actual = _success.Ensure(value => true, new LogicError("Failed")); + actual.IsSuccess.Should().BeTrue(); + } + + [Fact] + public void Success_predicateFalse_constant() + { + var actual = _success.Ensure(value => false, new LogicError("Failed")); + actual.IsFailure.Should().BeTrue(); + } + + [Fact] + public void Failure_predicateTrue_constant() + { + var actual = _failed.Ensure(value => true, new LogicError("Failed")); + actual.IsFailure.Should().BeTrue(); + } + + [Fact] + public void Failure_predicateFalse_constant() + { + var actual = _failed.Ensure(value => false, new LogicError("Failed")); + actual.IsFailure.Should().BeTrue(); + } + + [Fact] + public async Task Success_asyncPredicateTrue_constant() + { + var actual = await _success.Ensure(value => Task.FromResult(true), new LogicError("Failed")); + actual.IsSuccess.Should().BeTrue(); + } + + [Fact] + public async Task Success_asyncPredicateFalse_constant() + { + var actual = await _success.Ensure(value => Task.FromResult(false), new LogicError("Failed")); + actual.IsFailure.Should().BeTrue(); + } + + [Fact] + public async Task Failure_asyncPredicateTrue_constant() + { + var actual = await _failed.Ensure(value => Task.FromResult(true), new LogicError("Failed")); + actual.IsFailure.Should().BeTrue(); + } + + [Fact] + public async Task Failure_asyncPredicateFalse_constant() + { + var actual = await _failed.Ensure(value => Task.FromResult(false), new LogicError("Failed")); + actual.IsFailure.Should().BeTrue(); + } + + [Fact] + public void Success_predicateTrue_function() + { + var actual = _success.Ensure(value => true, () => new LogicError("Failed")); + actual.IsSuccess.Should().BeTrue(); + } + + [Fact] + public void Success_predicateFalse_function() + { + var actual = _success.Ensure(value => false, () => new LogicError("Failed")); + actual.IsFailure.Should().BeTrue(); + } + + [Fact] + public async Task Success_predicateTrue_asyncFunction() + { + var actual = await _success.Ensure(value => true, () => Task.FromResult(new LogicError("Failed"))); + actual.IsSuccess.Should().BeTrue(); + } + + [Fact] + public async Task Success_predicateFalse_asyncFunction() + { + var actual = await _success.Ensure(value => false, () => Task.FromResult(new LogicError("Failed"))); + actual.IsFailure.Should().BeTrue(); + } } \ No newline at end of file diff --git a/test/Monads.UnitTests/ResultTests/ResultEnumerableExtensionsTests.cs b/test/Monads.UnitTests/ResultTests/ResultEnumerableExtensionsTests.cs index 6459137..0abce71 100644 --- a/test/Monads.UnitTests/ResultTests/ResultEnumerableExtensionsTests.cs +++ b/test/Monads.UnitTests/ResultTests/ResultEnumerableExtensionsTests.cs @@ -4,223 +4,223 @@ namespace Bogoware.Monads.UnitTests.ResultTests; public class ResultEnumerableExtensionsTests { - private static readonly List> _allResultSuccess = new() - { - Result.Success(new Value(0)), - Result.Success(new Value(1)), - Result.Success(new Value(2)) - }; - - private static readonly List _allIResultSuccess = new() - { - Result.Success(new Value(0)), - Result.Success(new Value(1)), - Result.Success(new Value(2)) - }; - - private static readonly List> _allResultFailure = new() - { - Result.Failure("Error 1"), - Result.Failure("Error 2"), - Result.Failure("Error 3") - }; - - private static readonly List _allIResultFailure = new() - { - Result.Failure("Error 1"), - Result.Failure("Error 2"), - Result.Failure("Error 3") - }; - - private static readonly List> _resultMixed = new() - { - Result.Success(new Value(0)), - Result.Failure("Error"), - Result.Success(new Value(2)), - }; - - private static readonly List _resultIMixed = new() - { - Result.Success(new Value(0)), - Result.Failure("Error"), - Result.Success(new Value(2)), - }; - - [Fact] - public void AllSuccess_returns_true() - { - _allResultSuccess.AllSuccess().Should().BeTrue(); - _allIResultSuccess.AllSuccess().Should().BeTrue(); - } - - [Fact] - public void AllSuccess_returns_false() - { - _resultMixed.AllSuccess().Should().BeFalse(); - _resultIMixed.AllSuccess().Should().BeFalse(); - } - - [Fact] - public void AllFailure_returns_true() - { - _allResultFailure.AllFailure().Should().BeTrue(); - _allIResultFailure.AllFailure().Should().BeTrue(); - } - - [Fact] - public void AllFailure_returns_false() - { - _resultMixed.AllFailure().Should().BeFalse(); - _resultIMixed.AllFailure().Should().BeFalse(); - } - - [Fact] - public void AnySuccess_returns_true() - { - _resultMixed.AnySuccess().Should().BeTrue(); - _resultIMixed.AnySuccess().Should().BeTrue(); - _allResultSuccess.AnySuccess().Should().BeTrue(); - _allIResultSuccess.AnySuccess().Should().BeTrue(); - } - - [Fact] - public void AnySuccess_returns_false() - { - _allResultFailure.AnySuccess().Should().BeFalse(); - _allIResultFailure.AnySuccess().Should().BeFalse(); - } - - [Fact] - public void AnyFailure_returns_true() - { - _resultMixed.AnyFailure().Should().BeTrue(); - _resultIMixed.AnyFailure().Should().BeTrue(); - _allResultFailure.AnyFailure().Should().BeTrue(); - _allIResultFailure.AnyFailure().Should().BeTrue(); - } - - [Fact] - public void AnyFailure_returns_false() - { - _allResultSuccess.AnyFailure().Should().BeFalse(); - _allIResultSuccess.AnyFailure().Should().BeFalse(); - } - - [Fact] - public void SelectValues_discards_Nones() - { - _resultMixed.Should().HaveCount(3); - _resultMixed.SelectValues().Should().HaveCount(2); - } - - [Fact] - public void MapEach_remap_values_to_new_Some() - { - IEnumerable> actual = _resultMixed.MapEach(v => new AnotherValue(v.Val)); - actual.Should().HaveCount(3); - actual.Count(r => r.IsSuccess).Should().Be(2); - actual.Count(r => r.IsFailure).Should().Be(1); - } - - [Fact] - public void BindEach_remap_values_to_new_Some() - { - IEnumerable> actual = _resultMixed.BindEach(v => Result.Success(new AnotherValue(v.Val))); - actual.Should().HaveCount(3); - actual.Count(r => r.IsSuccess).Should().Be(2); - actual.Count(r => r.IsFailure).Should().Be(1); - } - - [Fact] - public void Where_works() - { - IEnumerable> results = new List> - { - Result.Success(new Value(0)), - Result.Success(new Value(1)), - Result.Success(new Value(2)), - Result.Success(new Value(3)) - }; - - IEnumerable> even = results.Where(v => v.Val % 2 == 0); - even.Should().HaveCount(2); - } - - [Fact] - public void WhereNot_works() - { - IEnumerable> results = new List> - { - Result.Success(new Value(0)), - Result.Success(new Value(1)), - Result.Success(new Value(2)), - Result.Success(new Value(3)), - Result.Success(new Value(5)) - }; - - IEnumerable> even = results.WhereNot(v => v.Val % 2 == 0); - even.Should().HaveCount(3); - } - - [Fact] - public void AggregateResult_AllSuccess_Returns_a_Success() - { - IEnumerable> results = new List> - { - Result.Success(new Value(0)), - Result.Success(new Value(1)), - Result.Success(new Value(2)), - Result.Success(new Value(3)), - Result.Success(new Value(5)) - }; - - var actual = results.AggregateResults(); - - actual.Should().BeOfType>>(); - actual.IsSuccess.Should().BeTrue(); - actual.IsFailure.Should().BeFalse(); - actual.GetValueOrThrow().Should().BeEquivalentTo(results.Select(r => r.GetValueOrThrow())); - } - - [Fact] - public void AggregateResult_AllFailures_Returns_a_Failure() - { - IEnumerable> results = new List> - { - Result.Failure("Error 1"), - Result.Failure("Error 2"), - Result.Failure("Error 3"), - Result.Failure("Error 4"), - Result.Failure("Error 5") - }; - - var actual = results.AggregateResults(); - var expectedError = new AggregateError(results.Select(r => r.GetErrorOrThrow())); - - actual.Should().BeOfType>>(); - actual.IsFailure.Should().BeTrue(); - actual.IsSuccess.Should().BeFalse(); - actual.GetErrorOrThrow().Should().BeEquivalentTo(expectedError); - } - - [Fact] - public void AggregateResult_SomeFailures_Returns_a_Failure() - { - var results = new List> - { - Result.Success(new Value(0)), - Result.Failure("Error 1"), - Result.Success(new Value(2)), - Result.Failure("Error 3"), - Result.Success(new Value(5)) - }; - - var actual = results.AggregateResults(); - var expectedError = new AggregateError(results.Where(r => r.IsFailure).Select(r => r.GetErrorOrThrow())); - - actual.Should().BeOfType>>(); - actual.IsFailure.Should().BeTrue(); - actual.IsSuccess.Should().BeFalse(); - actual.GetErrorOrThrow().Should().BeEquivalentTo(expectedError); - } + private static readonly List> _allResultSuccess = new() + { + Result.Success(new Value(0)), + Result.Success(new Value(1)), + Result.Success(new Value(2)) + }; + + private static readonly List _allIResultSuccess = new() + { + Result.Success(new Value(0)), + Result.Success(new Value(1)), + Result.Success(new Value(2)) + }; + + private static readonly List> _allResultFailure = new() + { + Result.Failure("Error 1"), + Result.Failure("Error 2"), + Result.Failure("Error 3") + }; + + private static readonly List _allIResultFailure = new() + { + Result.Failure("Error 1"), + Result.Failure("Error 2"), + Result.Failure("Error 3") + }; + + private static readonly List> _resultMixed = new() + { + Result.Success(new Value(0)), + Result.Failure("Error"), + Result.Success(new Value(2)), + }; + + private static readonly List _resultIMixed = new() + { + Result.Success(new Value(0)), + Result.Failure("Error"), + Result.Success(new Value(2)), + }; + + [Fact] + public void AllSuccess_returns_true() + { + _allResultSuccess.AllSuccess().Should().BeTrue(); + _allIResultSuccess.AllSuccess().Should().BeTrue(); + } + + [Fact] + public void AllSuccess_returns_false() + { + _resultMixed.AllSuccess().Should().BeFalse(); + _resultIMixed.AllSuccess().Should().BeFalse(); + } + + [Fact] + public void AllFailure_returns_true() + { + _allResultFailure.AllFailure().Should().BeTrue(); + _allIResultFailure.AllFailure().Should().BeTrue(); + } + + [Fact] + public void AllFailure_returns_false() + { + _resultMixed.AllFailure().Should().BeFalse(); + _resultIMixed.AllFailure().Should().BeFalse(); + } + + [Fact] + public void AnySuccess_returns_true() + { + _resultMixed.AnySuccess().Should().BeTrue(); + _resultIMixed.AnySuccess().Should().BeTrue(); + _allResultSuccess.AnySuccess().Should().BeTrue(); + _allIResultSuccess.AnySuccess().Should().BeTrue(); + } + + [Fact] + public void AnySuccess_returns_false() + { + _allResultFailure.AnySuccess().Should().BeFalse(); + _allIResultFailure.AnySuccess().Should().BeFalse(); + } + + [Fact] + public void AnyFailure_returns_true() + { + _resultMixed.AnyFailure().Should().BeTrue(); + _resultIMixed.AnyFailure().Should().BeTrue(); + _allResultFailure.AnyFailure().Should().BeTrue(); + _allIResultFailure.AnyFailure().Should().BeTrue(); + } + + [Fact] + public void AnyFailure_returns_false() + { + _allResultSuccess.AnyFailure().Should().BeFalse(); + _allIResultSuccess.AnyFailure().Should().BeFalse(); + } + + [Fact] + public void SelectValues_discards_Nones() + { + _resultMixed.Should().HaveCount(3); + _resultMixed.SelectValues().Should().HaveCount(2); + } + + [Fact] + public void MapEach_remap_values_to_new_Some() + { + IEnumerable> actual = _resultMixed.MapEach(v => new AnotherValue(v.Val)); + actual.Should().HaveCount(3); + actual.Count(r => r.IsSuccess).Should().Be(2); + actual.Count(r => r.IsFailure).Should().Be(1); + } + + [Fact] + public void BindEach_remap_values_to_new_Some() + { + IEnumerable> actual = _resultMixed.BindEach(v => Result.Success(new AnotherValue(v.Val))); + actual.Should().HaveCount(3); + actual.Count(r => r.IsSuccess).Should().Be(2); + actual.Count(r => r.IsFailure).Should().Be(1); + } + + [Fact] + public void Where_works() + { + IEnumerable> results = new List> + { + Result.Success(new Value(0)), + Result.Success(new Value(1)), + Result.Success(new Value(2)), + Result.Success(new Value(3)) + }; + + IEnumerable> even = results.Where(v => v.Val % 2 == 0); + even.Should().HaveCount(2); + } + + [Fact] + public void WhereNot_works() + { + IEnumerable> results = new List> + { + Result.Success(new Value(0)), + Result.Success(new Value(1)), + Result.Success(new Value(2)), + Result.Success(new Value(3)), + Result.Success(new Value(5)) + }; + + IEnumerable> even = results.WhereNot(v => v.Val % 2 == 0); + even.Should().HaveCount(3); + } + + [Fact] + public void AggregateResult_AllSuccess_Returns_a_Success() + { + IEnumerable> results = new List> + { + Result.Success(new Value(0)), + Result.Success(new Value(1)), + Result.Success(new Value(2)), + Result.Success(new Value(3)), + Result.Success(new Value(5)) + }; + + var actual = results.AggregateResults(); + + actual.Should().BeOfType>>(); + actual.IsSuccess.Should().BeTrue(); + actual.IsFailure.Should().BeFalse(); + actual.GetValueOrThrow().Should().BeEquivalentTo(results.Select(r => r.GetValueOrThrow())); + } + + [Fact] + public void AggregateResult_AllFailures_Returns_a_Failure() + { + IEnumerable> results = new List> + { + Result.Failure("Error 1"), + Result.Failure("Error 2"), + Result.Failure("Error 3"), + Result.Failure("Error 4"), + Result.Failure("Error 5") + }; + + var actual = results.AggregateResults(); + var expectedError = new AggregateError(results.Select(r => r.GetErrorOrThrow())); + + actual.Should().BeOfType>>(); + actual.IsFailure.Should().BeTrue(); + actual.IsSuccess.Should().BeFalse(); + actual.GetErrorOrThrow().Should().BeEquivalentTo(expectedError); + } + + [Fact] + public void AggregateResult_SomeFailures_Returns_a_Failure() + { + var results = new List> + { + Result.Success(new Value(0)), + Result.Failure("Error 1"), + Result.Success(new Value(2)), + Result.Failure("Error 3"), + Result.Success(new Value(5)) + }; + + var actual = results.AggregateResults(); + var expectedError = new AggregateError(results.Where(r => r.IsFailure).Select(r => r.GetErrorOrThrow())); + + actual.Should().BeOfType>>(); + actual.IsFailure.Should().BeTrue(); + actual.IsSuccess.Should().BeFalse(); + actual.GetErrorOrThrow().Should().BeEquivalentTo(expectedError); + } } \ No newline at end of file diff --git a/test/Monads.UnitTests/ResultTests/ResultEqualityTests.cs b/test/Monads.UnitTests/ResultTests/ResultEqualityTests.cs index 5373c58..654168a 100644 --- a/test/Monads.UnitTests/ResultTests/ResultEqualityTests.cs +++ b/test/Monads.UnitTests/ResultTests/ResultEqualityTests.cs @@ -2,41 +2,41 @@ namespace Bogoware.Monads.UnitTests.ResultTests; public class ResultEqualityTests { - [Fact] - public void Success_are_equals() - { - var success = Result.Success("Hello"); - var other = Result.Success("Hello"); - - success.Equals(other).Should().BeTrue(); - success.GetHashCode().Should().Be(other.GetHashCode()); - } - - [Fact] - public void Success_arent_equals() - { - var success = Result.Success("Hello"); - var other = Result.Success("World"); - - success.Equals(other).Should().BeFalse(); - } - - [Fact] - public void Failure_are_equals() - { - var failure = Result.Failure(new LogicError("Error")); - Result other = new LogicError("Error"); - - failure.Equals(other).Should().BeTrue(); - failure.GetHashCode().Should().Be(other.GetHashCode()); - } - - [Fact] - public void Failure_arent_equals() - { - var failure = Result.Failure(new LogicError("Error")); - Result other = new LogicError("Another error"); - - failure.Equals(other).Should().BeFalse(); - } + [Fact] + public void Success_are_equals() + { + var success = Result.Success("Hello"); + var other = Result.Success("Hello"); + + success.Equals(other).Should().BeTrue(); + success.GetHashCode().Should().Be(other.GetHashCode()); + } + + [Fact] + public void Success_arent_equals() + { + var success = Result.Success("Hello"); + var other = Result.Success("World"); + + success.Equals(other).Should().BeFalse(); + } + + [Fact] + public void Failure_are_equals() + { + var failure = Result.Failure(new LogicError("Error")); + Result other = new LogicError("Error"); + + failure.Equals(other).Should().BeTrue(); + failure.GetHashCode().Should().Be(other.GetHashCode()); + } + + [Fact] + public void Failure_arent_equals() + { + var failure = Result.Failure(new LogicError("Error")); + Result other = new LogicError("Another error"); + + failure.Equals(other).Should().BeFalse(); + } } \ No newline at end of file diff --git a/test/Monads.UnitTests/ResultTests/ResultExecuteTests.cs b/test/Monads.UnitTests/ResultTests/ResultExecuteTests.cs index fd8e54a..199089d 100644 --- a/test/Monads.UnitTests/ResultTests/ResultExecuteTests.cs +++ b/test/Monads.UnitTests/ResultTests/ResultExecuteTests.cs @@ -4,175 +4,175 @@ namespace Bogoware.Monads.UnitTests.ResultTests; public class ResultExecuteTests { - private static readonly Result _success = new(new Value(0)); - private static readonly Result _failed = new(new LogicError("Something went wrong")); - private readonly Mock _inspector = new(); - - [Fact] - public void Successful_executeIfSuccess_calls_voidFunction() - { - _success.ExecuteIfSuccess(_inspector.Object.MethodVoid); - _inspector.Verify(i => i.MethodVoid()); - } - - [Fact] - public void Successful_executeIfFailure_doesntCall_voidFunction() - { - _success.ExecuteIfFailure(_inspector.Object.MethodVoid); - _inspector.VerifyNoOtherCalls(); - } - - [Fact] - public void Failure_executeIfSuccess_doesntCall_voidFunction() - { - _failed.ExecuteIfSuccess(_inspector.Object.MethodVoid); - _inspector.VerifyNoOtherCalls(); - } - - [Fact] - public void Failure_executeIfFailure_calls_voidFunction() - { - _failed.ExecuteIfFailure(_inspector.Object.MethodVoid); - _inspector.Verify(i => i.MethodVoid()); - } - - [Fact] - public async Task Successful_executeIfSuccess_calls_asyncVoidFunction() - { - await _success.ExecuteIfSuccess(_inspector.Object.MethodVoidAsync); - _inspector.Verify(i => i.MethodVoidAsync()); - } - - [Fact] - public async Task Successful_executeIfFailure_doesntCall_asyncVoidFunction() - { - await _success.ExecuteIfFailure(_inspector.Object.MethodVoidAsync); - _inspector.VerifyNoOtherCalls(); - } - - [Fact] - public async Task Failure_executeIfSuccess_doesntCall_asyncVoidFunction() - { - await _failed.ExecuteIfSuccess(_inspector.Object.MethodVoidAsync); - _inspector.VerifyNoOtherCalls(); - } - - [Fact] - public async Task Failure_executeIfFailure_calls_asyncVoidFunction() - { - await _failed.ExecuteIfFailure(_inspector.Object.MethodVoidAsync); - _inspector.Verify(i => i.MethodVoidAsync()); - } - - [Fact] - public void Successful_executeIfSuccess_calls_function() - { - _success.ExecuteIfSuccess(_inspector.Object.MethodWithValueArg); - _inspector.Verify(i => i.MethodWithValueArg(It.IsAny())); - } - - [Fact] - public void Successful_executeIfFailure_doesntCall_function() - { - _success.ExecuteIfFailure(_inspector.Object.MethodWithErrorArg); - _inspector.VerifyNoOtherCalls(); - } - - [Fact] - public void Failure_executeIfSuccess_doesntCall_function() - { - _failed.ExecuteIfSuccess(_inspector.Object.MethodWithValueArg); - _inspector.VerifyNoOtherCalls(); - } - - [Fact] - public void Failure_executeIfFailure_calls_function() - { - _failed.ExecuteIfFailure(_inspector.Object.MethodWithErrorArg); - _inspector.Verify(i => i.MethodWithErrorArg(It.IsAny())); - } - - [Fact] - public async Task Successful_executeIfSuccess_calls_asyncFunction() - { - await _success.ExecuteIfSuccess(_inspector.Object.MethodWithValueArgAsync); - _inspector.Verify(i => i.MethodWithValueArgAsync(It.IsAny())); - } - - [Fact] - public async Task Successful_executeIfFailure_doesntCall_asyncFunction() - { - await _success.ExecuteIfFailure(_inspector.Object.MethodWithErrorArgAsync); - _inspector.VerifyNoOtherCalls(); - } - - [Fact] - public async Task Failure_executeIfSuccess_doesntCall_asyncFunction() - { - await _failed.ExecuteIfSuccess(_inspector.Object.MethodWithValueArgAsync); - _inspector.VerifyNoOtherCalls(); - } - - [Fact] - public async Task Failure_executeIfFailure_calls_asyncFunction() - { - await _failed.ExecuteIfFailure(_inspector.Object.MethodWithErrorArgAsync); - _inspector.Verify(i => i.MethodWithErrorArgAsync(It.IsAny())); - } - - [Fact] - public void Successful_execute_calls_voidFunction() - { - _success.Execute(_inspector.Object.MethodVoid); - _inspector.Verify(i => i.MethodVoid()); - } - - [Fact] - public void Failure_execute_calls_voidFunction() - { - _failed.Execute(_inspector.Object.MethodVoid); - _inspector.Verify(i => i.MethodVoid()); - } - - [Fact] - public async Task Successful_execute_calls_asyncVoidFunction() - { - await _success.Execute(_inspector.Object.MethodVoidAsync); - _inspector.Verify(i => i.MethodVoidAsync()); - } - - [Fact] - public async Task Failure_execute_calls_asyncVoidFunction() - { - await _failed.Execute(_inspector.Object.MethodVoidAsync); - _inspector.Verify(i => i.MethodVoidAsync()); - } - - [Fact] - public void Successful_execute_calls_function() - { - _success.Execute(_inspector.Object.MethodWithResultArg); - _inspector.Verify(i => i.MethodWithResultArg(It.IsAny>())); - } - - [Fact] - public void Failure_execute_calls_function() - { - _failed.Execute(_inspector.Object.MethodWithResultArg); - _inspector.Verify(i => i.MethodWithResultArg(It.IsAny>())); - } - - [Fact] - public async Task Successful_execute_calls_asyncFunction() - { - await _success.Execute(_inspector.Object.MethodWithResultArgAsync); - _inspector.Verify(i => i.MethodWithResultArgAsync(It.IsAny>())); - } - - [Fact] - public async Task Failure_execute_calls_asyncFunction() - { - await _failed.Execute(_inspector.Object.MethodWithResultArgAsync); - _inspector.Verify(i => i.MethodWithResultArgAsync(It.IsAny>())); - } + private static readonly Result _success = new(new Value(0)); + private static readonly Result _failed = new(new LogicError("Something went wrong")); + private readonly Mock _inspector = new(); + + [Fact] + public void Successful_executeIfSuccess_calls_voidFunction() + { + _success.ExecuteIfSuccess(_inspector.Object.MethodVoid); + _inspector.Verify(i => i.MethodVoid()); + } + + [Fact] + public void Successful_executeIfFailure_doesntCall_voidFunction() + { + _success.ExecuteIfFailure(_inspector.Object.MethodVoid); + _inspector.VerifyNoOtherCalls(); + } + + [Fact] + public void Failure_executeIfSuccess_doesntCall_voidFunction() + { + _failed.ExecuteIfSuccess(_inspector.Object.MethodVoid); + _inspector.VerifyNoOtherCalls(); + } + + [Fact] + public void Failure_executeIfFailure_calls_voidFunction() + { + _failed.ExecuteIfFailure(_inspector.Object.MethodVoid); + _inspector.Verify(i => i.MethodVoid()); + } + + [Fact] + public async Task Successful_executeIfSuccess_calls_asyncVoidFunction() + { + await _success.ExecuteIfSuccess(_inspector.Object.MethodVoidAsync); + _inspector.Verify(i => i.MethodVoidAsync()); + } + + [Fact] + public async Task Successful_executeIfFailure_doesntCall_asyncVoidFunction() + { + await _success.ExecuteIfFailure(_inspector.Object.MethodVoidAsync); + _inspector.VerifyNoOtherCalls(); + } + + [Fact] + public async Task Failure_executeIfSuccess_doesntCall_asyncVoidFunction() + { + await _failed.ExecuteIfSuccess(_inspector.Object.MethodVoidAsync); + _inspector.VerifyNoOtherCalls(); + } + + [Fact] + public async Task Failure_executeIfFailure_calls_asyncVoidFunction() + { + await _failed.ExecuteIfFailure(_inspector.Object.MethodVoidAsync); + _inspector.Verify(i => i.MethodVoidAsync()); + } + + [Fact] + public void Successful_executeIfSuccess_calls_function() + { + _success.ExecuteIfSuccess(_inspector.Object.MethodWithValueArg); + _inspector.Verify(i => i.MethodWithValueArg(It.IsAny())); + } + + [Fact] + public void Successful_executeIfFailure_doesntCall_function() + { + _success.ExecuteIfFailure(_inspector.Object.MethodWithErrorArg); + _inspector.VerifyNoOtherCalls(); + } + + [Fact] + public void Failure_executeIfSuccess_doesntCall_function() + { + _failed.ExecuteIfSuccess(_inspector.Object.MethodWithValueArg); + _inspector.VerifyNoOtherCalls(); + } + + [Fact] + public void Failure_executeIfFailure_calls_function() + { + _failed.ExecuteIfFailure(_inspector.Object.MethodWithErrorArg); + _inspector.Verify(i => i.MethodWithErrorArg(It.IsAny())); + } + + [Fact] + public async Task Successful_executeIfSuccess_calls_asyncFunction() + { + await _success.ExecuteIfSuccess(_inspector.Object.MethodWithValueArgAsync); + _inspector.Verify(i => i.MethodWithValueArgAsync(It.IsAny())); + } + + [Fact] + public async Task Successful_executeIfFailure_doesntCall_asyncFunction() + { + await _success.ExecuteIfFailure(_inspector.Object.MethodWithErrorArgAsync); + _inspector.VerifyNoOtherCalls(); + } + + [Fact] + public async Task Failure_executeIfSuccess_doesntCall_asyncFunction() + { + await _failed.ExecuteIfSuccess(_inspector.Object.MethodWithValueArgAsync); + _inspector.VerifyNoOtherCalls(); + } + + [Fact] + public async Task Failure_executeIfFailure_calls_asyncFunction() + { + await _failed.ExecuteIfFailure(_inspector.Object.MethodWithErrorArgAsync); + _inspector.Verify(i => i.MethodWithErrorArgAsync(It.IsAny())); + } + + [Fact] + public void Successful_execute_calls_voidFunction() + { + _success.Execute(_inspector.Object.MethodVoid); + _inspector.Verify(i => i.MethodVoid()); + } + + [Fact] + public void Failure_execute_calls_voidFunction() + { + _failed.Execute(_inspector.Object.MethodVoid); + _inspector.Verify(i => i.MethodVoid()); + } + + [Fact] + public async Task Successful_execute_calls_asyncVoidFunction() + { + await _success.Execute(_inspector.Object.MethodVoidAsync); + _inspector.Verify(i => i.MethodVoidAsync()); + } + + [Fact] + public async Task Failure_execute_calls_asyncVoidFunction() + { + await _failed.Execute(_inspector.Object.MethodVoidAsync); + _inspector.Verify(i => i.MethodVoidAsync()); + } + + [Fact] + public void Successful_execute_calls_function() + { + _success.Execute(_inspector.Object.MethodWithResultArg); + _inspector.Verify(i => i.MethodWithResultArg(It.IsAny>())); + } + + [Fact] + public void Failure_execute_calls_function() + { + _failed.Execute(_inspector.Object.MethodWithResultArg); + _inspector.Verify(i => i.MethodWithResultArg(It.IsAny>())); + } + + [Fact] + public async Task Successful_execute_calls_asyncFunction() + { + await _success.Execute(_inspector.Object.MethodWithResultArgAsync); + _inspector.Verify(i => i.MethodWithResultArgAsync(It.IsAny>())); + } + + [Fact] + public async Task Failure_execute_calls_asyncFunction() + { + await _failed.Execute(_inspector.Object.MethodWithResultArgAsync); + _inspector.Verify(i => i.MethodWithResultArgAsync(It.IsAny>())); + } } \ No newline at end of file diff --git a/test/Monads.UnitTests/ResultTests/ResultImplicitConversionsTests.cs b/test/Monads.UnitTests/ResultTests/ResultImplicitConversionsTests.cs index 09c603d..6016b12 100644 --- a/test/Monads.UnitTests/ResultTests/ResultImplicitConversionsTests.cs +++ b/test/Monads.UnitTests/ResultTests/ResultImplicitConversionsTests.cs @@ -2,20 +2,20 @@ namespace Bogoware.Monads.UnitTests.ResultTests; public class ResultImplicitConversionsTests { - private Result GetSuccess() => new("success"); - private Result GetFailure() => new LogicError("success"); - - [Fact] - public void Implicit_conversion_from_success() - { - Result actual = GetSuccess(); - actual.IsSuccess.Should().BeTrue(); - } - - [Fact] - public void Implicit_conversion_from_failure() - { - Result actual = GetFailure(); - actual.IsFailure.Should().BeTrue(); - } + private Result GetSuccess() => new("success"); + private Result GetFailure() => new LogicError("success"); + + [Fact] + public void Implicit_conversion_from_success() + { + Result actual = GetSuccess(); + actual.IsSuccess.Should().BeTrue(); + } + + [Fact] + public void Implicit_conversion_from_failure() + { + Result actual = GetFailure(); + actual.IsFailure.Should().BeTrue(); + } } \ No newline at end of file diff --git a/test/Monads.UnitTests/ResultTests/ResultLinqTests.cs b/test/Monads.UnitTests/ResultTests/ResultLinqTests.cs index c993ef7..e9723b2 100644 --- a/test/Monads.UnitTests/ResultTests/ResultLinqTests.cs +++ b/test/Monads.UnitTests/ResultTests/ResultLinqTests.cs @@ -2,60 +2,60 @@ namespace Bogoware.Monads.UnitTests.ResultTests; public class ResultLinqTests { - [Fact] - public void Select_value_from_Success() - { - var success1 = Result.Success(new Value(1)); - var success2 = Result.Success(new Value(1)); - var values = - from value1 in success1 - from value2 in success2 - select value1.Val + value2.Val; - - values.Should().BeEquivalentTo(new List { 2 }); - } - - [Fact] - public void Select_value_from_Failure() - { - var success = Result.Success(new Value(1)); - var failure = Result.Failure("something wet wrong"); - var values = - from value1 in success - from value2 in failure - select value1.Val + value2.Val; - - values.Should().BeEmpty(); - } - - [Fact] - public void Aggregate_values() - { - var results = new List> - { - Result.Success(new Value(1)), - Result.Success(new Value(2)), - Result.Failure("something went wrong"), - Result.Success(new Value(3)), - Result.Success(new Value(4)), - }; - - // style 1: filter over monads - var values = - from result in results - where result.Satisfy(v => v.Val % 2 == 0) - from v in result - select v.Val; - - values.Sum().Should().Be(6); - - // style 1: filter in pure linq style - var values2 = - from result in results - from v in result - where v.Val % 2 == 0 - select v.Val; - - values2.Sum().Should().Be(6); - } + [Fact] + public void Select_value_from_Success() + { + var success1 = Result.Success(new Value(1)); + var success2 = Result.Success(new Value(1)); + var values = + from value1 in success1 + from value2 in success2 + select value1.Val + value2.Val; + + values.Should().BeEquivalentTo(new List { 2 }); + } + + [Fact] + public void Select_value_from_Failure() + { + var success = Result.Success(new Value(1)); + var failure = Result.Failure("something wet wrong"); + var values = + from value1 in success + from value2 in failure + select value1.Val + value2.Val; + + values.Should().BeEmpty(); + } + + [Fact] + public void Aggregate_values() + { + var results = new List> + { + Result.Success(new Value(1)), + Result.Success(new Value(2)), + Result.Failure("something went wrong"), + Result.Success(new Value(3)), + Result.Success(new Value(4)), + }; + + // style 1: filter over monads + var values = + from result in results + where result.Satisfy(v => v.Val % 2 == 0) + from v in result + select v.Val; + + values.Sum().Should().Be(6); + + // style 1: filter in pure linq style + var values2 = + from result in results + from v in result + where v.Val % 2 == 0 + select v.Val; + + values2.Sum().Should().Be(6); + } } \ No newline at end of file diff --git a/test/Monads.UnitTests/ResultTests/ResultMapErrorTests.cs b/test/Monads.UnitTests/ResultTests/ResultMapErrorTests.cs index 08b6504..b323560 100644 --- a/test/Monads.UnitTests/ResultTests/ResultMapErrorTests.cs +++ b/test/Monads.UnitTests/ResultTests/ResultMapErrorTests.cs @@ -4,82 +4,82 @@ namespace Bogoware.Monads.UnitTests.ResultTests; public class ResultMapErrorTests { - private static readonly Result _success = new(new Value(0)); - private static readonly Result _failed = new(new LogicError("Original error")); - - [Fact] - public void Success_mapError_constant() - { - Result actual = _success.MapError(new LogicError("New error")); - actual.IsSuccess.Should().BeTrue(); - } - - [Fact] - public void Failure_mapError_constant() - { - Result actual = _failed.MapError(new LogicError("New error")); - actual.IsFailure.Should().BeTrue(); - actual.GetErrorOrThrow().Message.Should().Be("New error"); - } - - [Fact] - public void Success_mapError_voidFunction() - { - Result actual = _success.MapError(() => new LogicError("New error")); - actual.IsSuccess.Should().BeTrue(); - } - - [Fact] - public void Failure_mapError_voidFunction() - { - Result actual = _failed.MapError(() => new LogicError("New error")); - actual.IsFailure.Should().BeTrue(); - actual.GetErrorOrThrow().Message.Should().Be("New error"); - } - - [Fact] - public async Task Success_mapError_asyncVoidFunction() - { - Result actual = await _success.MapError(() => Task.FromResult(new LogicError("New error"))); - actual.IsSuccess.Should().BeTrue(); - } - - [Fact] - public async Task Failure_mapError_asyncVoidFunction() - { - Result actual = await _failed.MapError(() => Task.FromResult(new LogicError("New error"))); - actual.IsFailure.Should().BeTrue(); - actual.GetErrorOrThrow().Message.Should().Be("New error"); - } - - - [Fact] - public void Success_mapError_function() - { - Result actual = _success.MapError(error => new LogicError($"New error")); - actual.IsSuccess.Should().BeTrue(); - } - - [Fact] - public void Failure_mapError_function() - { - Result actual = _failed.MapError(error => new LogicError($"New error")); - actual.IsFailure.Should().BeTrue(); - actual.GetErrorOrThrow().Message.Should().Be("New error"); - } - - [Fact] - public async Task Success_mapError_asyncFunction() - { - Result actual = await _success.MapError(error => Task.FromResult(new LogicError($"New error"))); - actual.IsSuccess.Should().BeTrue(); - } - - [Fact] - public async Task Failure_map_asyncFunction() - { - Result actual = await _failed.MapError(error => Task.FromResult(new LogicError($"New error"))); - actual.IsFailure.Should().BeTrue(); - actual.GetErrorOrThrow().Message.Should().Be("New error"); - } + private static readonly Result _success = new(new Value(0)); + private static readonly Result _failed = new(new LogicError("Original error")); + + [Fact] + public void Success_mapError_constant() + { + Result actual = _success.MapError(new LogicError("New error")); + actual.IsSuccess.Should().BeTrue(); + } + + [Fact] + public void Failure_mapError_constant() + { + Result actual = _failed.MapError(new LogicError("New error")); + actual.IsFailure.Should().BeTrue(); + actual.GetErrorOrThrow().Message.Should().Be("New error"); + } + + [Fact] + public void Success_mapError_voidFunction() + { + Result actual = _success.MapError(() => new LogicError("New error")); + actual.IsSuccess.Should().BeTrue(); + } + + [Fact] + public void Failure_mapError_voidFunction() + { + Result actual = _failed.MapError(() => new LogicError("New error")); + actual.IsFailure.Should().BeTrue(); + actual.GetErrorOrThrow().Message.Should().Be("New error"); + } + + [Fact] + public async Task Success_mapError_asyncVoidFunction() + { + Result actual = await _success.MapError(() => Task.FromResult(new LogicError("New error"))); + actual.IsSuccess.Should().BeTrue(); + } + + [Fact] + public async Task Failure_mapError_asyncVoidFunction() + { + Result actual = await _failed.MapError(() => Task.FromResult(new LogicError("New error"))); + actual.IsFailure.Should().BeTrue(); + actual.GetErrorOrThrow().Message.Should().Be("New error"); + } + + + [Fact] + public void Success_mapError_function() + { + Result actual = _success.MapError(error => new LogicError($"New error")); + actual.IsSuccess.Should().BeTrue(); + } + + [Fact] + public void Failure_mapError_function() + { + Result actual = _failed.MapError(error => new LogicError($"New error")); + actual.IsFailure.Should().BeTrue(); + actual.GetErrorOrThrow().Message.Should().Be("New error"); + } + + [Fact] + public async Task Success_mapError_asyncFunction() + { + Result actual = await _success.MapError(error => Task.FromResult(new LogicError($"New error"))); + actual.IsSuccess.Should().BeTrue(); + } + + [Fact] + public async Task Failure_map_asyncFunction() + { + Result actual = await _failed.MapError(error => Task.FromResult(new LogicError($"New error"))); + actual.IsFailure.Should().BeTrue(); + actual.GetErrorOrThrow().Message.Should().Be("New error"); + } } \ No newline at end of file diff --git a/test/Monads.UnitTests/ResultTests/ResultMapTests.cs b/test/Monads.UnitTests/ResultTests/ResultMapTests.cs index 07220fb..b65ccc9 100644 --- a/test/Monads.UnitTests/ResultTests/ResultMapTests.cs +++ b/test/Monads.UnitTests/ResultTests/ResultMapTests.cs @@ -4,113 +4,113 @@ namespace Bogoware.Monads.UnitTests.ResultTests; public class ResultMapTests { - private static readonly Result _success = new(new Value(0)); - private static readonly Result _failed = new(new LogicError("Something went wrong")); - - [Fact] - public void Success_map_constant() - { - Result actual = _success.Map("success"); - actual.IsSuccess.Should().BeTrue(); - } - - [Fact] - public void Failure_map_constant() - { - Result actual = _failed.Map("success"); - actual.IsFailure.Should().BeTrue(); - } - - [Fact] - public void Success_map_voidFunction() - { - Result actual = _success.Map(() => "success"); - actual.IsSuccess.Should().BeTrue(); - } - - [Fact] - public void Failure_map_voidFunction() - { - Result actual = _failed.Map(() => "success"); - actual.IsFailure.Should().BeTrue(); - } - - [Fact] - public async Task Success_map_asyncVoidFunction() - { - Result actual = await _success.Map(() => Task.FromResult("success")); - actual.IsSuccess.Should().BeTrue(); - } - - [Fact] - public async Task Failure_map_asyncVoidFunction() - { - Result actual = await _failed.Map(() => Task.FromResult("success")); - actual.IsFailure.Should().BeTrue(); - } - - - [Fact] - public void Success_map_function() - { - Result actual = _success.Map(success => $"success: {_success}"); - actual.IsSuccess.Should().BeTrue(); - } - - [Fact] - public void Failure_map_function() - { - Result actual = _failed.Map(success => $"success: {_success}"); - actual.IsFailure.Should().BeTrue(); - } - - [Fact] - public async Task Success_map_asyncFunction() - { - Result actual = await _success.Map(success => Task.FromResult($"success: {_success}")); - actual.IsSuccess.Should().BeTrue(); - } - - [Fact] - public async Task Failure_map_asyncFunction() - { - Result actual = await _failed.Map(success => Task.FromResult($"success: {_success}")); - actual.IsFailure.Should().BeTrue(); - } - - [Fact] - public void VoidFunctor_maps_success_to_ResultUnit() - { - void VoidFunctor(string arg) { } - Result sut = Result.Success("success"); - Result actual = sut.Map(VoidFunctor); - actual.IsSuccess.Should().BeTrue(); - } - - [Fact] - public async Task VoidFunctor_maps_success_to_TaskResultUnit() - { - Task VoidFunctor(string arg) { return Task.CompletedTask; } - Result sut = Result.Success("success"); - Result actual = await sut.Map(VoidFunctor); - actual.IsSuccess.Should().BeTrue(); - } - - [Fact] - public void VoidFunctor_maps_failure_to_ResultUnit() - { - void VoidFunctor(string arg) { } - Result sut = Result.Failure("failed"); - Result actual = sut.Map(VoidFunctor); - actual.IsFailure.Should().BeTrue(); - } - - [Fact] - public async Task VoidFunctor_maps_failure_to_TaskResultUnit() - { - Task VoidFunctor(string arg) { return Task.CompletedTask; } - Result sut = Result.Failure("failed"); - Result actual = await sut.Map(VoidFunctor); - actual.IsFailure.Should().BeTrue(); - } + private static readonly Result _success = new(new Value(0)); + private static readonly Result _failed = new(new LogicError("Something went wrong")); + + [Fact] + public void Success_map_constant() + { + Result actual = _success.Map("success"); + actual.IsSuccess.Should().BeTrue(); + } + + [Fact] + public void Failure_map_constant() + { + Result actual = _failed.Map("success"); + actual.IsFailure.Should().BeTrue(); + } + + [Fact] + public void Success_map_voidFunction() + { + Result actual = _success.Map(() => "success"); + actual.IsSuccess.Should().BeTrue(); + } + + [Fact] + public void Failure_map_voidFunction() + { + Result actual = _failed.Map(() => "success"); + actual.IsFailure.Should().BeTrue(); + } + + [Fact] + public async Task Success_map_asyncVoidFunction() + { + Result actual = await _success.Map(() => Task.FromResult("success")); + actual.IsSuccess.Should().BeTrue(); + } + + [Fact] + public async Task Failure_map_asyncVoidFunction() + { + Result actual = await _failed.Map(() => Task.FromResult("success")); + actual.IsFailure.Should().BeTrue(); + } + + + [Fact] + public void Success_map_function() + { + Result actual = _success.Map(success => $"success: {_success}"); + actual.IsSuccess.Should().BeTrue(); + } + + [Fact] + public void Failure_map_function() + { + Result actual = _failed.Map(success => $"success: {_success}"); + actual.IsFailure.Should().BeTrue(); + } + + [Fact] + public async Task Success_map_asyncFunction() + { + Result actual = await _success.Map(success => Task.FromResult($"success: {_success}")); + actual.IsSuccess.Should().BeTrue(); + } + + [Fact] + public async Task Failure_map_asyncFunction() + { + Result actual = await _failed.Map(success => Task.FromResult($"success: {_success}")); + actual.IsFailure.Should().BeTrue(); + } + + [Fact] + public void VoidFunctor_maps_success_to_ResultUnit() + { + void VoidFunctor(string arg) { } + Result sut = Result.Success("success"); + Result actual = sut.Map(VoidFunctor); + actual.IsSuccess.Should().BeTrue(); + } + + [Fact] + public async Task VoidFunctor_maps_success_to_TaskResultUnit() + { + Task VoidFunctor(string arg) { return Task.CompletedTask; } + Result sut = Result.Success("success"); + Result actual = await sut.Map(VoidFunctor); + actual.IsSuccess.Should().BeTrue(); + } + + [Fact] + public void VoidFunctor_maps_failure_to_ResultUnit() + { + void VoidFunctor(string arg) { } + Result sut = Result.Failure("failed"); + Result actual = sut.Map(VoidFunctor); + actual.IsFailure.Should().BeTrue(); + } + + [Fact] + public async Task VoidFunctor_maps_failure_to_TaskResultUnit() + { + Task VoidFunctor(string arg) { return Task.CompletedTask; } + Result sut = Result.Failure("failed"); + Result actual = await sut.Map(VoidFunctor); + actual.IsFailure.Should().BeTrue(); + } } \ No newline at end of file diff --git a/test/Monads.UnitTests/ResultTests/ResultMatchExtensionsTests.cs b/test/Monads.UnitTests/ResultTests/ResultMatchExtensionsTests.cs index f8b81f6..aaf4502 100644 --- a/test/Monads.UnitTests/ResultTests/ResultMatchExtensionsTests.cs +++ b/test/Monads.UnitTests/ResultTests/ResultMatchExtensionsTests.cs @@ -2,169 +2,169 @@ namespace Bogoware.Monads.UnitTests.ResultTests; public class ResultMatchExtensionsTests { - private static readonly Result _success = new(new Value(0)); - - private static readonly Result _failed = new(new LogicError("Something went wrong")); - - [Fact] - public void Success_matches_constant_constant() - { - _success.Match("success", "failure").Should().Be("success"); - } - - [Fact] - public void Failure_matches_constant_constant() - { - _failed.Match("success", "failure").Should().Be("failure"); - } - - [Fact] - public void Success_matches_voidFunction_constant() - { - _success.Match(() => "success", "failure").Should().Be("success"); - } - - [Fact] - public void Failure_matches_constant_voidFunction() - { - _failed.Match("success", () => "failure").Should().Be("failure"); - } - - [Fact] - public void Success_matches_voidFunction_voidFunction() - { - _success.Match(() => "success", () => "failure").Should().Be("success"); - } - - [Fact] - public void Failed_matches_voidFunction_voidFunction() - { - _failed.Match(() => "success", () => "failure").Should().Be("failure"); - } - - [Fact] - public async Task Success_matches_asyncVoidFunction_constant() - { - (await _success.Match(() => Task.FromResult("success"), "failure")).Should().Be("success"); - } - - [Fact] - public async Task Failed_matches_constant_asyncVoidFunction() - { - (await _success.Match("success", () => Task.FromResult("failure"))).Should().Be("success"); - } - - [Fact] - public async Task Success_matches_asyncVoidFunction_asyncVoidFunction() - { - (await _success.Match(() => Task.FromResult("success"), () => Task.FromResult("failure"))).Should().Be("success"); - } - - [Fact] - public void Success_matches_successFunction_constant() - { - var actual = _success.Match(success => $"success: {success.Val}", "failure"); - actual.Should().StartWith("success"); - } - - [Fact] - public void Failure_matches_successFunction_constant() - { - var actual = _failed.Match(success => $"success: {success.Val}", "failure"); - actual.Should().StartWith("failure"); - } - - [Fact] - public void Success_matches_successFunction_voidFunction() - { - var actual = _success.Match(success => $"success: {success.Val}", () => "failure"); - actual.Should().StartWith("success"); - } - - [Fact] - public void Failure_matches_successFunction_voidFunction() - { - var actual = _failed.Match(success => $"success: {success.Val}", () => "failure"); - actual.Should().StartWith("failure"); - } - - [Fact] - public async Task Success_matches_constant_asyncErrorFunction() - { - var actual = await _success.Match("success", error => Task.FromResult($"failure: {error.Message}")); - actual.Should().StartWith("success"); - } - - [Fact] - public async Task Failure_matches_constant_asyncErrorFunction() - { - var actual = await _failed.Match("success", error => Task.FromResult($"failure: {error.Message}")); - actual.Should().StartWith("failure"); - } - - [Fact] - public async Task Success_matches_voidSuccessFunction_asyncErrorFunction() - { - var actual = await _success.Match(() => "success", error => Task.FromResult($"failure: {error.Message}")); - actual.Should().StartWith("success"); - } - - [Fact] - public async Task Failure_matches_voidSuccessFunction_asyncErrorFunction() - { - var actual = await _failed.Match(() => "success", error => Task.FromResult($"failure: {error.Message}")); - actual.Should().StartWith("failure"); - } - - [Fact] - public async Task Success_matches_asyncSuccessFunction_constant() - { - var actual = await _success.Match(success => Task.FromResult($"success: {success.Val}"), "failure"); - actual.Should().StartWith("success"); - } - - [Fact] - public async Task Failure_matches_asyncSuccessFunction_constant() - { - var actual = await _failed.Match(success => Task.FromResult($"success: {success.Val}"), "failure"); - actual.Should().StartWith("failure"); - } - - [Fact] - public async Task Success_matches_asyncSuccessFunction_voidErrorFunction() - { - var actual = await _success.Match(success => Task.FromResult($"success: {success.Val}"), () => "failure"); - actual.Should().StartWith("success"); - } - - [Fact] - public async Task Failure_matches_asyncSuccessFunction_voidErrorFunction() - { - var actual = await _failed.Match(success => Task.FromResult($"success: {success.Val}"), () => "failure"); - actual.Should().StartWith("failure"); - } - - [Fact] - public void GetValue_with_constant() - { - var sut = Result.Failure(new LogicError("Something went wrong")); - var actual = sut.GetValue("success"); - actual.Should().Be("success"); - } - - [Fact] - public void GetValue_with_function() - { - var sut = Result.Failure(new LogicError("Something went wrong")); - var actual = sut.GetValue(() => "success"); - actual.Should().Be("success"); - } - - [Fact] - public async Task GetValue_with_asyncFunction() - { - var sut = Result.Failure(new LogicError("Something went wrong")); - var actual = await sut.GetValue(() => Task.FromResult("success")); - actual.Should().Be("success"); - } + private static readonly Result _success = new(new Value(0)); + + private static readonly Result _failed = new(new LogicError("Something went wrong")); + + [Fact] + public void Success_matches_constant_constant() + { + _success.Match("success", "failure").Should().Be("success"); + } + + [Fact] + public void Failure_matches_constant_constant() + { + _failed.Match("success", "failure").Should().Be("failure"); + } + + [Fact] + public void Success_matches_voidFunction_constant() + { + _success.Match(() => "success", "failure").Should().Be("success"); + } + + [Fact] + public void Failure_matches_constant_voidFunction() + { + _failed.Match("success", () => "failure").Should().Be("failure"); + } + + [Fact] + public void Success_matches_voidFunction_voidFunction() + { + _success.Match(() => "success", () => "failure").Should().Be("success"); + } + + [Fact] + public void Failed_matches_voidFunction_voidFunction() + { + _failed.Match(() => "success", () => "failure").Should().Be("failure"); + } + + [Fact] + public async Task Success_matches_asyncVoidFunction_constant() + { + (await _success.Match(() => Task.FromResult("success"), "failure")).Should().Be("success"); + } + + [Fact] + public async Task Failed_matches_constant_asyncVoidFunction() + { + (await _success.Match("success", () => Task.FromResult("failure"))).Should().Be("success"); + } + + [Fact] + public async Task Success_matches_asyncVoidFunction_asyncVoidFunction() + { + (await _success.Match(() => Task.FromResult("success"), () => Task.FromResult("failure"))).Should().Be("success"); + } + + [Fact] + public void Success_matches_successFunction_constant() + { + var actual = _success.Match(success => $"success: {success.Val}", "failure"); + actual.Should().StartWith("success"); + } + + [Fact] + public void Failure_matches_successFunction_constant() + { + var actual = _failed.Match(success => $"success: {success.Val}", "failure"); + actual.Should().StartWith("failure"); + } + + [Fact] + public void Success_matches_successFunction_voidFunction() + { + var actual = _success.Match(success => $"success: {success.Val}", () => "failure"); + actual.Should().StartWith("success"); + } + + [Fact] + public void Failure_matches_successFunction_voidFunction() + { + var actual = _failed.Match(success => $"success: {success.Val}", () => "failure"); + actual.Should().StartWith("failure"); + } + + [Fact] + public async Task Success_matches_constant_asyncErrorFunction() + { + var actual = await _success.Match("success", error => Task.FromResult($"failure: {error.Message}")); + actual.Should().StartWith("success"); + } + + [Fact] + public async Task Failure_matches_constant_asyncErrorFunction() + { + var actual = await _failed.Match("success", error => Task.FromResult($"failure: {error.Message}")); + actual.Should().StartWith("failure"); + } + + [Fact] + public async Task Success_matches_voidSuccessFunction_asyncErrorFunction() + { + var actual = await _success.Match(() => "success", error => Task.FromResult($"failure: {error.Message}")); + actual.Should().StartWith("success"); + } + + [Fact] + public async Task Failure_matches_voidSuccessFunction_asyncErrorFunction() + { + var actual = await _failed.Match(() => "success", error => Task.FromResult($"failure: {error.Message}")); + actual.Should().StartWith("failure"); + } + + [Fact] + public async Task Success_matches_asyncSuccessFunction_constant() + { + var actual = await _success.Match(success => Task.FromResult($"success: {success.Val}"), "failure"); + actual.Should().StartWith("success"); + } + + [Fact] + public async Task Failure_matches_asyncSuccessFunction_constant() + { + var actual = await _failed.Match(success => Task.FromResult($"success: {success.Val}"), "failure"); + actual.Should().StartWith("failure"); + } + + [Fact] + public async Task Success_matches_asyncSuccessFunction_voidErrorFunction() + { + var actual = await _success.Match(success => Task.FromResult($"success: {success.Val}"), () => "failure"); + actual.Should().StartWith("success"); + } + + [Fact] + public async Task Failure_matches_asyncSuccessFunction_voidErrorFunction() + { + var actual = await _failed.Match(success => Task.FromResult($"success: {success.Val}"), () => "failure"); + actual.Should().StartWith("failure"); + } + + [Fact] + public void GetValue_with_constant() + { + var sut = Result.Failure(new LogicError("Something went wrong")); + var actual = sut.GetValue("success"); + actual.Should().Be("success"); + } + + [Fact] + public void GetValue_with_function() + { + var sut = Result.Failure(new LogicError("Something went wrong")); + var actual = sut.GetValue(() => "success"); + actual.Should().Be("success"); + } + + [Fact] + public async Task GetValue_with_asyncFunction() + { + var sut = Result.Failure(new LogicError("Something went wrong")); + var actual = await sut.GetValue(() => Task.FromResult("success")); + actual.Should().Be("success"); + } } \ No newline at end of file diff --git a/test/Monads.UnitTests/ResultTests/ResultMatchTests.cs b/test/Monads.UnitTests/ResultTests/ResultMatchTests.cs index 760b181..58fcaee 100644 --- a/test/Monads.UnitTests/ResultTests/ResultMatchTests.cs +++ b/test/Monads.UnitTests/ResultTests/ResultMatchTests.cs @@ -2,62 +2,62 @@ namespace Bogoware.Monads.UnitTests.ResultTests; public class ResultMatchTests { - private static readonly Result _success = new(new Value(0)); - private static readonly Result _failed = new(new LogicError("Something went wrong")); - - [Fact] - public void Success_matches_valueFunction_errorFunction() - { - var actual = _success.Match(success => $"success: {success.Val}", error => $"failure: {error.Message}"); - actual.Should().StartWith("success:"); - } - - [Fact] - public void Failed_matches_valueFunction_errorFunction() - { - var actual = _failed.Match(success => $"success: {success.Val}", error => $"failure: {error.Message}"); - actual.Should().StartWith("failure:"); - } - - [Fact] - public async Task Success_matches_asyncValueFunction_errorFunction() - { - var actual = await _success.Match(success => Task.FromResult($"success: {success.Val}"), error => $"failure: {error.Message}"); - actual.Should().StartWith("success:"); - } - - [Fact] - public async Task Failure_matches_asyncValueFunction_errorFunction() - { - var actual = await _failed.Match(success => Task.FromResult($"success: {success.Val}"), error => $"failure: {error.Message}"); - actual.Should().StartWith("failure:"); - } - - [Fact] - public async Task Success_matches_valueFunction_asyncErrorFunction() - { - var actual = await _success.Match(success => $"success: {success.Val}", error => Task.FromResult( $"failure: {error.Message}")); - actual.Should().StartWith("success:"); - } - - [Fact] - public async Task Failure_matches_valueFunction_asyncErrorFunction() - { - var actual = await _failed.Match(success => $"success: {success.Val}", error => Task.FromResult( $"failure: {error.Message}")); - actual.Should().StartWith("failure:"); - } - - [Fact] - public async Task Success_matches_asyncValueFunction_asyncErrorFunction() - { - var actual = await _success.Match(success => Task.FromResult($"success: {success.Val}"), error => Task.FromResult( $"failure: {error.Message}")); - actual.Should().StartWith("success:"); - } - - [Fact] - public async Task Failure_matches_asyncValueFunction_asyncErrorFunction() - { - var actual = await _failed.Match(success => Task.FromResult($"success: {success.Val}"), error => Task.FromResult( $"failure: {error.Message}")); - actual.Should().StartWith("failure:"); - } + private static readonly Result _success = new(new Value(0)); + private static readonly Result _failed = new(new LogicError("Something went wrong")); + + [Fact] + public void Success_matches_valueFunction_errorFunction() + { + var actual = _success.Match(success => $"success: {success.Val}", error => $"failure: {error.Message}"); + actual.Should().StartWith("success:"); + } + + [Fact] + public void Failed_matches_valueFunction_errorFunction() + { + var actual = _failed.Match(success => $"success: {success.Val}", error => $"failure: {error.Message}"); + actual.Should().StartWith("failure:"); + } + + [Fact] + public async Task Success_matches_asyncValueFunction_errorFunction() + { + var actual = await _success.Match(success => Task.FromResult($"success: {success.Val}"), error => $"failure: {error.Message}"); + actual.Should().StartWith("success:"); + } + + [Fact] + public async Task Failure_matches_asyncValueFunction_errorFunction() + { + var actual = await _failed.Match(success => Task.FromResult($"success: {success.Val}"), error => $"failure: {error.Message}"); + actual.Should().StartWith("failure:"); + } + + [Fact] + public async Task Success_matches_valueFunction_asyncErrorFunction() + { + var actual = await _success.Match(success => $"success: {success.Val}", error => Task.FromResult($"failure: {error.Message}")); + actual.Should().StartWith("success:"); + } + + [Fact] + public async Task Failure_matches_valueFunction_asyncErrorFunction() + { + var actual = await _failed.Match(success => $"success: {success.Val}", error => Task.FromResult($"failure: {error.Message}")); + actual.Should().StartWith("failure:"); + } + + [Fact] + public async Task Success_matches_asyncValueFunction_asyncErrorFunction() + { + var actual = await _success.Match(success => Task.FromResult($"success: {success.Val}"), error => Task.FromResult($"failure: {error.Message}")); + actual.Should().StartWith("success:"); + } + + [Fact] + public async Task Failure_matches_asyncValueFunction_asyncErrorFunction() + { + var actual = await _failed.Match(success => Task.FromResult($"success: {success.Val}"), error => Task.FromResult($"failure: {error.Message}")); + actual.Should().StartWith("failure:"); + } } \ No newline at end of file diff --git a/test/Monads.UnitTests/ResultTests/ResultRecoverWithTests.cs b/test/Monads.UnitTests/ResultTests/ResultRecoverWithTests.cs index e2789f9..282dad1 100644 --- a/test/Monads.UnitTests/ResultTests/ResultRecoverWithTests.cs +++ b/test/Monads.UnitTests/ResultTests/ResultRecoverWithTests.cs @@ -4,76 +4,76 @@ namespace Bogoware.Monads.UnitTests.ResultTests; public class ResultRecoverWithTests { - private static readonly Result _success = new(new Value(0)); - private static readonly Result _failed = new(new LogicError("Something went wrong")); - - [Fact] - public void Success_recover_constant() - { - Result actual = _success.RecoverWith(new Value(1)); - actual.GetValueOrThrow().Val.Should().Be(0); - } - - [Fact] - public void Failure_recover_constant() - { - Result actual = _failed.RecoverWith(new Value(1)); - actual.GetValueOrThrow().Val.Should().Be(1); - } - - [Fact] - public void Success_recover_voidFunction() - { - Result actual = _success.RecoverWith(() => new(1)); - actual.GetValueOrThrow().Val.Should().Be(0); - } - - [Fact] - public void Failure_recover_voidFunction() - { - Result actual = _failed.RecoverWith(() => new(1)); - actual.GetValueOrThrow().Val.Should().Be(1); - } - - [Fact] - public async Task Success_recover_asyncVoidFunction() - { - Result actual = await _success.RecoverWith(() => Task.FromResult(new Value(1))); - actual.GetValueOrThrow().Val.Should().Be(0); - } - - [Fact] - public async Task Failure_recover_asyncVoidFunction() - { - Result actual = await _failed.RecoverWith(() => Task.FromResult(new Value(1))); - actual.GetValueOrThrow().Val.Should().Be(1); - } - - [Fact] - public void Success_recover_function() - { - Result actual = _success.RecoverWith(error => new(1)); - actual.GetValueOrThrow().Val.Should().Be(0); - } - - [Fact] - public void Failure_recover_function() - { - Result actual = _failed.RecoverWith(error => new(1)); - actual.GetValueOrThrow().Val.Should().Be(1); - } - - [Fact] - public async Task Success_recover_asyncFunction() - { - Result actual = await _success.RecoverWith(error => Task.FromResult(new(1))); - actual.GetValueOrThrow().Val.Should().Be(0); - } - - [Fact] - public async Task Failure_recover_asyncFunction() - { - Result actual = await _failed.RecoverWith(error => Task.FromResult(new(1))); - actual.GetValueOrThrow().Val.Should().Be(1); - } + private static readonly Result _success = new(new Value(0)); + private static readonly Result _failed = new(new LogicError("Something went wrong")); + + [Fact] + public void Success_recover_constant() + { + Result actual = _success.RecoverWith(new Value(1)); + actual.GetValueOrThrow().Val.Should().Be(0); + } + + [Fact] + public void Failure_recover_constant() + { + Result actual = _failed.RecoverWith(new Value(1)); + actual.GetValueOrThrow().Val.Should().Be(1); + } + + [Fact] + public void Success_recover_voidFunction() + { + Result actual = _success.RecoverWith(() => new(1)); + actual.GetValueOrThrow().Val.Should().Be(0); + } + + [Fact] + public void Failure_recover_voidFunction() + { + Result actual = _failed.RecoverWith(() => new(1)); + actual.GetValueOrThrow().Val.Should().Be(1); + } + + [Fact] + public async Task Success_recover_asyncVoidFunction() + { + Result actual = await _success.RecoverWith(() => Task.FromResult(new Value(1))); + actual.GetValueOrThrow().Val.Should().Be(0); + } + + [Fact] + public async Task Failure_recover_asyncVoidFunction() + { + Result actual = await _failed.RecoverWith(() => Task.FromResult(new Value(1))); + actual.GetValueOrThrow().Val.Should().Be(1); + } + + [Fact] + public void Success_recover_function() + { + Result actual = _success.RecoverWith(error => new(1)); + actual.GetValueOrThrow().Val.Should().Be(0); + } + + [Fact] + public void Failure_recover_function() + { + Result actual = _failed.RecoverWith(error => new(1)); + actual.GetValueOrThrow().Val.Should().Be(1); + } + + [Fact] + public async Task Success_recover_asyncFunction() + { + Result actual = await _success.RecoverWith(error => Task.FromResult(new(1))); + actual.GetValueOrThrow().Val.Should().Be(0); + } + + [Fact] + public async Task Failure_recover_asyncFunction() + { + Result actual = await _failed.RecoverWith(error => Task.FromResult(new(1))); + actual.GetValueOrThrow().Val.Should().Be(1); + } } \ No newline at end of file diff --git a/test/Monads.UnitTests/ResultTests/ResultTests.cs b/test/Monads.UnitTests/ResultTests/ResultTests.cs index fd2de53..b3e7d09 100644 --- a/test/Monads.UnitTests/ResultTests/ResultTests.cs +++ b/test/Monads.UnitTests/ResultTests/ResultTests.cs @@ -2,82 +2,82 @@ namespace Bogoware.Monads.UnitTests.ResultTests; public class ResultTests { - [Fact] - public void TryAction_should_return_a_successfulUnitResultRuntime() - { - void Action() - { - } + [Fact] + public void TryAction_should_return_a_successfulUnitResultRuntime() + { + void Action() + { + } - var result = Result.Execute(Action); - result.IsSuccess.Should().BeTrue(); - } + var result = Result.Execute(Action); + result.IsSuccess.Should().BeTrue(); + } - [Fact] - public void TryAction_should_return_a_failedUnitResultRuntime() - { - void Action() => throw new(); - var result = Result.Execute(Action); - result.IsFailure.Should().BeTrue(); - } - - [Fact] - public async Task TryActionAsync_should_return_a_successfulUnitResultRuntime() - { - Task Action() => Task.FromResult(Result.Unit); - var result = await Result.Execute(Action); - result.IsSuccess.Should().BeTrue(); - } + [Fact] + public void TryAction_should_return_a_failedUnitResultRuntime() + { + void Action() => throw new(); + var result = Result.Execute(Action); + result.IsFailure.Should().BeTrue(); + } - [Fact] - public async Task TryActionAsync_should_return_a_failedUnitResultRuntime() - { - Task Action() => Task.FromException(new()); - var result = await Result.Execute(Action); - result.IsFailure.Should().BeTrue(); - } - - [Fact] - public void TryAction_should_return_a_successfulResultRuntime() - { - Value Action() - { - return new(0); - } + [Fact] + public async Task TryActionAsync_should_return_a_successfulUnitResultRuntime() + { + Task Action() => Task.FromResult(Result.Unit); + var result = await Result.Execute(Action); + result.IsSuccess.Should().BeTrue(); + } - var result = Result.Execute(Action); - result.IsSuccess.Should().BeTrue(); - } + [Fact] + public async Task TryActionAsync_should_return_a_failedUnitResultRuntime() + { + Task Action() => Task.FromException(new()); + var result = await Result.Execute(Action); + result.IsFailure.Should().BeTrue(); + } - [Fact] - public void TryAction_should_return_a_failedResultRuntime() - { - Value Action() - { - throw new NotImplementedException(); - } - var result = Result.Execute(Action); - result.IsFailure.Should().BeTrue(); - } - - [Fact] - public async Task TryActionAsync_should_return_a_successfulResultRuntime() - { - Task Action() => Task.FromResult(new Value(0)); + [Fact] + public void TryAction_should_return_a_successfulResultRuntime() + { + Value Action() + { + return new(0); + } - var result = await Result.Execute(Action); - result.IsSuccess.Should().BeTrue(); - } + var result = Result.Execute(Action); + result.IsSuccess.Should().BeTrue(); + } - [Fact] - public async Task TryActionAsync_should_return_a_failedResultRuntime() - { - Task Action() - { - throw new NotImplementedException(); - } - - var result = await Result.Execute(Action); - result.IsFailure.Should().BeTrue(); - } + [Fact] + public void TryAction_should_return_a_failedResultRuntime() + { + Value Action() + { + throw new NotImplementedException(); + } + var result = Result.Execute(Action); + result.IsFailure.Should().BeTrue(); + } + + [Fact] + public async Task TryActionAsync_should_return_a_successfulResultRuntime() + { + Task Action() => Task.FromResult(new Value(0)); + + var result = await Result.Execute(Action); + result.IsSuccess.Should().BeTrue(); + } + + [Fact] + public async Task TryActionAsync_should_return_a_failedResultRuntime() + { + Task Action() + { + throw new NotImplementedException(); + } + + var result = await Result.Execute(Action); + result.IsFailure.Should().BeTrue(); + } } \ No newline at end of file diff --git a/test/Monads.UnitTests/ResultTests/ResultThrowIfFailureTests.cs b/test/Monads.UnitTests/ResultTests/ResultThrowIfFailureTests.cs index cd0ef5c..a7739f3 100644 --- a/test/Monads.UnitTests/ResultTests/ResultThrowIfFailureTests.cs +++ b/test/Monads.UnitTests/ResultTests/ResultThrowIfFailureTests.cs @@ -2,73 +2,73 @@ namespace Bogoware.Monads.UnitTests.ResultTests; public class ResultThrowIfFailureTests { - [Fact] - public void ResultThrowIfFailure_WhenResultIsFailure_ThrowsResultFailedException() - { - // Arrange - var result = Result.Failure("error"); + [Fact] + public void ResultThrowIfFailure_WhenResultIsFailure_ThrowsResultFailedException() + { + // Arrange + var result = Result.Failure("error"); - // Act - var act = () => result.ThrowIfFailure(); + // Act + var act = () => result.ThrowIfFailure(); - // Assert - act.Should().Throw(); - } - - [Fact] - public void ResultThrowIfFailure_WhenResultIsSuccess_ReturnsResult() - { - // Arrange - var result = Result.Success("value"); + // Assert + act.Should().Throw(); + } - // Act - var act = () => result.ThrowIfFailure(); + [Fact] + public void ResultThrowIfFailure_WhenResultIsSuccess_ReturnsResult() + { + // Arrange + var result = Result.Success("value"); - // Assert - act.Should().NotThrow(); - } - - [Fact] - public async Task ResultThrowIfFailureAsync_WhenResultIsFailure_ThrowsResultFailedException() - { - // Arrange - var result = Task.FromResult(Result.Failure("error")); + // Act + var act = () => result.ThrowIfFailure(); - // Act - var act = () => result.ThrowIfFailure(); + // Assert + act.Should().NotThrow(); + } - // Assert - await act.Should().ThrowAsync(); - } - - [Fact] - public async Task ResultThrowIfFailureAsync_WhenResultIsSuccess_ReturnsResult() - { - // Arrange - var result = Task.FromResult(Result.Success("value")); + [Fact] + public async Task ResultThrowIfFailureAsync_WhenResultIsFailure_ThrowsResultFailedException() + { + // Arrange + var result = Task.FromResult(Result.Failure("error")); - // Act - var act = () => result.ThrowIfFailure(); + // Act + var act = () => result.ThrowIfFailure(); - // Assert - await act.Should().NotThrowAsync(); - } - - [Fact] - public async Task ResultThrowIfFailureAsync_WhenResultIsFailure_ThrowsResultFailedException_useCase() - { - // Arrange - var result = Task.FromResult(Result.Failure("error")); + // Assert + await act.Should().ThrowAsync(); + } - try - { - await result - .ExecuteIfFailure(() => { }) - .ThrowIfFailure(); - } - catch (ResultFailedException) - { - - } - } + [Fact] + public async Task ResultThrowIfFailureAsync_WhenResultIsSuccess_ReturnsResult() + { + // Arrange + var result = Task.FromResult(Result.Success("value")); + + // Act + var act = () => result.ThrowIfFailure(); + + // Assert + await act.Should().NotThrowAsync(); + } + + [Fact] + public async Task ResultThrowIfFailureAsync_WhenResultIsFailure_ThrowsResultFailedException_useCase() + { + // Arrange + var result = Task.FromResult(Result.Failure("error")); + + try + { + await result + .ExecuteIfFailure(() => { }) + .ThrowIfFailure(); + } + catch (ResultFailedException) + { + + } + } } \ No newline at end of file diff --git a/test/Monads.UnitTests/ResultTests/ResultValueTypeTests.cs b/test/Monads.UnitTests/ResultTests/ResultValueTypeTests.cs index d1b1c90..e9a079e 100644 --- a/test/Monads.UnitTests/ResultTests/ResultValueTypeTests.cs +++ b/test/Monads.UnitTests/ResultTests/ResultValueTypeTests.cs @@ -9,7 +9,7 @@ public void Result_with_value_type_should_be_successful() result.IsSuccess.Should().BeTrue(); result.GetValueOrThrow().Should().Be(1); } - + [Fact] public void Result_with_value_type_should_be_failed() { diff --git a/test/Monads.UnitTests/UnitTests.cs b/test/Monads.UnitTests/UnitTests.cs index afdb3f4..31a5e4d 100644 --- a/test/Monads.UnitTests/UnitTests.cs +++ b/test/Monads.UnitTests/UnitTests.cs @@ -2,31 +2,31 @@ namespace Bogoware.Monads.UnitTests; public class UnitTests { - [Fact] - public void Singleton() - { - var unit1 = Unit.Instance; - var unit2 = Unit.Instance; - unit1.Should().BeSameAs(unit2); - } - - [Fact] - public void Equals_success() - { - var unit1 = Unit.Instance; - var unit2 = Unit.Instance; - unit1.Equals(unit2).Should().BeTrue(); - } - - [Fact] - public void GetHashcode_test() - { - Unit.Instance.GetHashCode().Should().Be(0); - } - - [Fact] - public void ToString_test() - { - Unit.Instance.ToString().Should().Be("Unit"); - } + [Fact] + public void Singleton() + { + var unit1 = Unit.Instance; + var unit2 = Unit.Instance; + unit1.Should().BeSameAs(unit2); + } + + [Fact] + public void Equals_success() + { + var unit1 = Unit.Instance; + var unit2 = Unit.Instance; + unit1.Equals(unit2).Should().BeTrue(); + } + + [Fact] + public void GetHashcode_test() + { + Unit.Instance.GetHashCode().Should().Be(0); + } + + [Fact] + public void ToString_test() + { + Unit.Instance.ToString().Should().Be("Unit"); + } } \ No newline at end of file