public void Try_NoParams_ThrowsException()
        {
            // ----------------------- Arrange -----------------------
            var attempt = divFuncNoParam.Try();

            // -----------------------   Act   -----------------------
            // -----------------------  Assert -----------------------
            Assert.Throws <DivideByZeroException>(() => attempt.Invoke());
        }
        public void Try_FourParam_ThrowsExceptionOnError()
        {
            // ----------------------- Arrange -----------------------
            var attempt = divFuncFourParam.Try();

            // -----------------------   Act   -----------------------
            // -----------------------  Assert -----------------------
            Assert.AreEqual(1, attempt.Invoke(8, 4, 2, 1));
            Assert.Throws <DivideByZeroException>(() => attempt.Invoke(4, 2, 1, 0));
        }
        public void TryFuncThrowsIfActionIsNull()
        {
            Func <string>            function     = null;
            Func <Exception, string> errorHandler = ex => ex.Message;

            Assert.Throws <ArgumentNullException>(() => function.Try(errorHandler));
        }
        public void TryFuncThrowsIfErrorHandlerIsNull()
        {
            Func <string>            function     = () => "foo";
            Func <Exception, string> errorHandler = null;

            Assert.Throws <ArgumentNullException>(() => function.Try(errorHandler));
        }
Пример #5
0
        public void Try_as_extension_method_creating_a_new_function()
        {
            Func <int, int> f = a => a + 2;
            var             v = f.Try()(5);

            Assert.AreEqual(v, 7);
        }
Пример #6
0
 internal Tree(ObjectStorage storage ,string id, long size, Func<byte[]> loader, Tree parent = null, string name = null, string mode = null)
     : base(id, parent, name, mode)
 {
     this.Size = size;
     this._storage = storage;
     this._loader = loader.Try(n => new Lazy<byte[]>(loader));
 }
Пример #7
0
 /// <seealso cref="TryExtensions.TryCatch{TResult, TException}" />
 public static Try <TResult> TryCatch <TResult, TException1, TException2, TException3>(this Func <TResult> func,
                                                                                       Func <TException1, TResult> catcher1, Func <TException2, TResult> catcher2, Func <TException3, TResult> catcher3)
     where TException1 : Exception
     where TException2 : Exception
     where TException3 : Exception
 {
     try
     {
         return(new Success <TResult>(func()));
     }
     catch (TException1 e)
     {
         // recurse into `Try` -- see comment in `TryCatch(func, catcher)` for why this is necessary
         return(catcher1.Try(e));
     }
     catch (TException2 e)
     {
         // recurse into `Try` -- see comment in `TryCatch(func, catcher)` for why this is necessary
         return(catcher2.Try(e));
     }
     catch (TException3 e)
     {
         // recurse into `Try` -- see comment in `TryCatch(func, catcher)` for why this is necessary
         return(catcher3.Try(e));
     }
     catch (Exception e)
     {
         return(new Failure <TResult>(e));
     }
 }
Пример #8
0
 /// <seealso cref="TryExtensions.TryCatch{TResult, TException}" />
 public static Try <TResult> TryCatch <TResult, TException1, TException2, TException3, TException4>(
     this Func <TResult> func, Func <TException1, TResult> catcher1, Func <TException2, TResult> catcher2, Func <TException3, TResult> catcher3, Func <TException4, TResult> catcher4)
     where TException1 : Exception
     where TException2 : Exception
     where TException3 : Exception
     where TException4 : Exception
 {
     try
     {
         return(new Try <TResult>(func()));
     }
     catch (TException1 e)
     {
         return(catcher1.Try(e));
     }
     catch (TException2 e)
     {
         return(catcher2.Try(e));
     }
     catch (TException3 e)
     {
         return(catcher3.Try(e));
     }
     catch (TException4 e)
     {
         return(catcher4.Try(e));
     }
     catch (Exception e)
     {
         return(new Try <TResult>(e));
     }
 }
Пример #9
0
        public void Try_as_extension_method_applying_function()
        {
            Func <int, int> f = a => a + 2;
            var             v = f.Try(5);

            Assert.AreEqual(v, 7);
        }
Пример #10
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="serviceType"></param>
 /// <param name="instanceHandler"></param>
 /// <param name="key"></param>
 /// <returns></returns>
 public static object TryResolve(Type serviceType, Func <object> instanceHandler, string key = null)
 {
     if (Container.IsRegisted(serviceType, key))
     {
         return(Provider.Resolve(serviceType, key));
     }
     return(instanceHandler.Try());
 }
Пример #11
0
        public void OperationSucceeds()
        {
            Func <string> caller = () => SampleService.OpSuccess(true);
            var           result = caller.Try <string, Exception>();

            Assert.IsType <Success <string, Exception> >(result);
            Assert.True(result is Success <string, Exception> converted && converted.Content == true.ToString());
        }
Пример #12
0
        public void OperationFails()
        {
            Func <string> caller = SampleService.OpThrowEx;
            var           result = caller.Try <string, Exception>();

            Assert.IsType <Error <string, Exception> >(result);
            Assert.True(result is Error <string, Exception> converted && converted.Content.Message == "OpThrowEx");
        }
Пример #13
0
 /// <summary>
 ///
 /// </summary>
 /// <typeparam name="TService"></typeparam>
 /// <param name="instanceHandler"></param>
 /// <param name="key"></param>
 /// <returns></returns>
 public static TService TryResolve <TService>(Func <TService> instanceHandler, string key = null)
     where TService : class
 {
     if (Container.IsRegisted <TService>(key))
     {
         return(Provider.Resolve <TService>(key));
     }
     return(instanceHandler.Try());
 }
Пример #14
0
        /// <summary>
        /// If a <see cref="Invariant.Try{TResult}"/> is a failure whose inner Exception
        /// if of type <typeparamref name="TException"/> , catch the result and turn that into a <see cref="Invariant.Try{TResult}"/>
        /// with the value of <paramref name="catcher"/> (if it succeeds).
        /// </summary>
        /// <remarks>
        /// - If our `Try` is successful, this method simply returns the same `Try` object.
        /// - If our `Try` is failed, with an exception that is not a sub-type of `TException`, this method simply returns
        ///   the same failed `Try` object.
        /// - If our `Try` is failed, with an exception that *is* `TException`, this method returns either:
        ///   (a) a successful `Try` object with the value of <paramref name="catcher"/> applied to the exception, if
        ///       the function is evaluated successfully, or
        ///   (b) a new failed `Try` object, with the new exception thrown during the evaluation of <paramref name="catcher"/>.
        /// </remarks>
        public Try <TResult> Catch <TException>(Func <TException, TResult> catcher)
            where TException : Exception
        {
            TException te = _exception as TException;

            if (te == null)
            {
                return(this);
            }
            return(catcher.Try(te));
        }
Пример #15
0
 /// <summary>
 /// Returns a Try of the result of <paramref name="onSuccess"/> if this Try(T) is successful. Otherwise
 /// returns a Try of the result of <paramref name="onFailure"/> applied to the thrown Exception.
 /// </summary>
 /// <remarks>
 /// An exception being thrown in <paramref name="onSuccess"/> or <paramref name="onFailure"/> will result
 /// in the Try being returned resolving to a Failure(<typeparam name="TResult2" />).
 /// </remarks>
 public Try <TResult2> Then <TResult2>(Func <TResult, TResult2> onSuccess, Func <Exception, TResult2> onFailure)
 {
     if (_exception != null)
     {
         return(onFailure.Try(_exception));
     }
     else
     {
         return(onSuccess.Try(_success));
     }
 }
Пример #16
0
 /// <summary>
 /// Returns a Try of the result of <paramref name="onSuccess"/> if this Try(T) is successful. Otherwise
 /// returns the same Failure(T).
 /// </summary>
 /// <remarks>
 /// An exception being thrown in <paramref name="onSuccess"/> will result in the Try(<typeparam name="TResult2"/>)
 /// being returned resolving to a Failure(<typeparam name="TResult2" />).
 /// </remarks>
 public Try <TResult2> Then <TResult2>(Func <TResult, TResult2> onSuccess)
 {
     if (_exception != null)
     {
         return(new Try <TResult2>(_exception));
     }
     else
     {
         return(onSuccess.Try(_success));
     }
 }
        public void TryFuncInvokesErrorHandlerIfUnSuccessful()
        {
            const string expected = "bar";

            Func <string>            function     = () => { throw new Exception(); };
            Func <Exception, string> errorHandler = ex => "bar";

            string result = function.Try(errorHandler);

            Assert.AreEqual(expected, result);
        }
        public void TryFuncInvokesUnsafeFuncIfSuccessful()
        {
            const string expected = "foo";

            Func <string>            function     = () => "foo";
            Func <Exception, string> errorHandler = ex => "bar";

            string result = function.Try(errorHandler);

            Assert.AreEqual(expected, result);
        }
Пример #19
0
        private static void HandleConstraintResult([NotNull] ConstraintResult result, [CanBeNull] Func <string> messageProvider)
        {
            if (result.IsSuccess == false)
            {
                var mParts = new[] {
                    messageProvider?.Try().OrDefault(),
                    result.Description
                };

                Assert.Ignore(mParts.NonNull().JoinLines());
            }
        }
Пример #20
0
        public static void Run(IEnumerable<string> commandLineArguments, IEnumerable<ArgInfo> defs, Action<int, int> action)
        {
            var parseToInt = new Func<string, int>(Int32.Parse);

            var valuesResult =
                from dict in commandLineArguments.ParseArgs(defs)
                from values in
                    from x in
                        from v in dict["x"].ToResult(ClaError.NewValueMissing("x"))
                        from vParsed in parseToInt.Try(v, ClaError.NewCannotParseValue("x"))
                        select vParsed
                    join y in
                        from v in dict["y"].ToResult(ClaError.NewValueMissing("y"))
                        from vParsed in parseToInt.Try(v, ClaError.NewCannotParseValue("y"))
                        select vParsed on 1 equals 1
                    select new { X = x, Y = y }
                select values;

            valuesResult.Match(
                ifSuccess: (v, list) => action(v.X, v.Y),
                ifFailure: list => list.Select(x => x.SPrintClaError()).ToList().ForEach(Console.WriteLine));
        }
Пример #21
0
        /// <summary>
        /// If a <see cref="Covariant.Try{TResult}"/> is a <see cref="Failre{TResult}"/> whose inner Exception
        /// if of type <typeparamref name="TException"/> , catch the result and turn that into a <see cref="Covariant.Try{TResult}"/>
        /// with the value of <paramref name="catcher"/> (if it succeeds).
        /// </summary>
        /// <remarks>
        /// - If our `Try` is successful, this method simply returns the same `Try` object.
        /// - If our `Try` is failed, with an exception that is not a sub-type of `TException`, this method simply returns
        ///   the same failed `Try` object.
        /// - If our `Try` is failed, with an exception that *is* `TException`, this method returns either:
        ///   (a) a successful `Try` object with the value of <paramref name="catcher"/> applied to the exception, if
        ///       the function is evaluated successfully, or
        ///   (b) a new failed `Try` object, with the new exception thrown during the evaluation of <paramref name="catcher"/>.
        /// </remarks>
        public static Try <TResult> Catch <TResult, TException>(this Try <TResult> tryer, Func <TException, TResult> catcher)
            where TException : Exception
        {
            // C# 7:
            // if (tryer is Failure<TResult> f && f.Exception is TException e)
            var e = (tryer as Failure <TResult>)?.Exception as TException;

            if (e != null)
            {
                return(catcher.Try(e));
            }

            return(tryer);
        }
Пример #22
0
 /// <summary>
 /// Executes a function <paramref name="func" />, catching the any exception of type `TException` thrown and turning
 /// that into a successful argument. If another `Exception` of unknown type was thrown, the result will continue to
 /// be a `Failure`.
 /// </summary>
 public static Try <TResult> TryCatch <TResult, TException>(this Func <TResult> func, Func <TException, TResult> catcher)
     where TException : Exception
 {
     try
     {
         return(new Try <TResult>(func()));
     }
     catch (TException e)
     {
         return(catcher.Try(e));
     }
     catch (Exception e)
     {
         return(new Try <TResult>(e));
     }
 }
Пример #23
0
        public void OuterFailsInnerNothing()
        {
            // when outer doesn't support Try, so you have to wrap
            Func <InnerService> outerCall = () => new OuterService().GetInnerThrowEx();
            var result1 = outerCall.Try <InnerService, Exception>()
                          .Map(inner => inner.GetBoolSuccess(true));

            Assert.IsType <Error <bool, Exception> >(result1);
            Assert.True(result1 is Error <bool, Exception> converted1 && converted1.Content.Message == "GetInnerThrowEx");

            // when outer does support Try, so you don't need to wrap
            var result2 = new OuterService()
                          .GetInnerReturnExWrapped()
                          .Map(inner => inner.GetBoolSuccess(true));

            Assert.IsType <Error <bool, Exception> >(result2);
            Assert.True(result2 is Error <bool, Exception> converted2 && converted2.Content.Message == "GetInnerReturnExWrapped");
        }
Пример #24
0
        public void OuterSucceedsInnerSucceeds()
        {
            // when inner doesnt support Try
            Func <InnerService> outerCall1 = () => new OuterService().GetInnerSuccess();
            var result1 = outerCall1.Try <InnerService, Exception>()
                          .Map(inner => inner.GetBoolSuccess(true));

            Assert.IsType <Success <bool, Exception> >(result1);
            Assert.True(result1 is Success <bool, Exception> converted1 && converted1.Content);

            // when inner doesnt support Try
            Func <InnerService> outerCall2 = () => new OuterService().GetInnerSuccess();
            var result2 = outerCall2.Try <InnerService, Exception>()
                          .FlatMap(inner => inner.GetBoolSuccessWrapped(true));

            Assert.IsType <Success <bool, Exception> >(result2);
            Assert.True(result2 is Success <bool, Exception> converted2 && converted2.Content);
        }
Пример #25
0
 /// <summary>
 /// Executes a function <paramref name="func" />, catching the any exception of type `TException` thrown and turning
 /// that into a successful argument. If another `Exception` of unknown type was thrown, the result will continue to
 /// be a `Failure`.
 /// </summary>
 public static Try <TResult> TryCatch <TResult, TException>(this Func <TResult> func, Func <TException, TResult> catcher)
     where TException : Exception
 {
     try
     {
         return(new Success <TResult>(func()));
     }
     catch (TException e)
     {
         // recurse into the `Try` method with one fewer argument,
         // thus creating a new nested "try" here-- an exception
         // thrown during the evaluation of `catcher` should be
         // part of a `Failure<TResult>` being returned.
         return(catcher.Try(e));
     }
     catch (Exception e)
     {
         return(new Failure <TResult>(e));
     }
 }
Пример #26
0
        void Failure_Throws()
        {
            Func <string> lambda = () => { throw new TestException(); };
            Try <string>  fail   = lambda.Try();

            Assert.Throws <TestException>(() => fail.GetOrThrow());
            Assert.Equal("TestException :)", fail.Convert((s) => "success? " + s, (e) => "TestException :)"));

            Try <string> thend = fail.Then((succ) => succ);

            Assert.Throws <TestException>(() => thend.GetOrThrow());
            Assert.Equal("Fail", thend.Convert((s) => "succeeded", (e) => "Fail"));

            Try <string> successThen = fail.Then((succ) => "S", (e) => "F");

            Assert.Equal("F", successThen.GetOrThrow());

            Try <string> kindaFail = fail.Then((succ) => "S", (e) => { throw new TestException2(); });

            Assert.Throws <TestException2>(() => kindaFail.GetOrThrow());
        }
Пример #27
0
        void Success_Basic()
        {
            Func <string> lambda = () => "successful result.";
            Try <string>  succ   = lambda.Try();

            Assert.Equal("successful result.", succ.GetOrThrow());
            Assert.Equal("successful result..", succ.Convert((s) => s + ".", (e) => "boo"));
            Assert.Equal("successful result.", succ.Catch((Exception e) => "caught").GetOrThrow());
            Assert.Equal("successful result.!", succ.Then((s) => s + "!").GetOrThrow());

            Try <string> thend1 = succ.Then((s) => "S");

            Assert.Equal("S", thend1.GetOrThrow());

            Try <string> thend2 = succ.Then((s) => "S", (e) => "F");

            Assert.Equal("S", thend2.GetOrThrow());

            Try <string> failOnSuccess = succ.Then <string>((s) => { throw new TestException(); });

            Assert.Throws <TestException>(() => failOnSuccess.GetOrThrow());
        }
Пример #28
0
        public void OuterSucceedsInnerFails()
        {
            // when inner doesn't support Try
            Func <InnerService> outerCall1 = () => new OuterService().GetInnerSuccess();
            var result1 = outerCall1.Try <InnerService, Exception>()
                          .FlatMap(inner =>
            {
                Func <bool> innerCall1 = inner.GetBoolThrowEx;
                return(innerCall1.Try <bool, Exception>());
            });

            Assert.IsType <Error <bool, Exception> >(result1);
            Assert.True(result1 is Error <bool, Exception> converted1 && converted1.Content.Message == "GetBoolThrowEx");

            // when inner does support Try
            Func <InnerService> outerCall2 = () => new OuterService().GetInnerSuccess();
            var result2 = outerCall2.Try <InnerService, Exception>()
                          .FlatMap(inner => inner.GetBoolReturnExWrapped());

            Assert.IsType <Error <bool, Exception> >(result2);
            Assert.True(result2 is Error <bool, Exception> converted2 && converted2.Content.Message == "GetBoolReturnExWrapped");
        }
Пример #29
0
        public void PassedFailable_Func()
        {
            Func <int> func = Succeed;

            Validate.PassedFailable(func.Try());
        }
Пример #30
0
        public void FailedFailable_Func()
        {
            Func <int> func = Fail;

            Validate.FailedFailable(func.Try());
        }
Пример #31
0
        public static Try <int> Div(int numerator, int denominator)
        {
            Func <int> f = () => numerator / denominator;

            return(f.Try());
        }
Пример #32
0
 public Try <TResult2> Then <TResult2>(Func <TResult, TResult2> onSuccess, Func <Exception, TResult2> onFailure)
 => onFailure.Try(Exception);