// Returns true if the expected result is right
 // Returns false if the expected result is wrong
 public bool PosTest1()
 {
     bool retVal = true;
     TestLibrary.TestFramework.BeginScenario("PosTest1: Create a new instance of NotImplementedException.");
     try
     {
         string expectValue = "HELLO";
         ArgumentException notFoundException = new ArgumentException();
         NotImplementedException myException = new NotImplementedException(expectValue, notFoundException);
         if (myException == null)
         {
             TestLibrary.TestFramework.LogError("001.1", "NotImplementedException instance can not create correctly.");
             retVal = false;
         }
         if (myException.Message != expectValue)
         {
             TestLibrary.TestFramework.LogError("001.2", "the Message should return " + expectValue);
             retVal = false;
         }
         if (!(myException.InnerException is ArgumentException))
         {
             TestLibrary.TestFramework.LogError("001.3", "the InnerException should return ArgumentException.");
             retVal = false;
         }
     }
     catch (Exception e)
     {
         TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e);
         retVal = false;
     }
     return retVal;
 }
 // Returns true if the expected result is right
 // Returns false if the expected result is wrong
 public bool PosTest2()
 {
     bool retVal = true;
     TestLibrary.TestFramework.BeginScenario("PosTest2: the parameter string is null.");
     try
     {
         string expectValue = null;
         ArgumentException dpoExpection = new ArgumentException();
         NotImplementedException myException = new NotImplementedException(expectValue, dpoExpection);
         if (myException == null)
         {
             TestLibrary.TestFramework.LogError("002.1", "NotImplementedException instance can not create correctly.");
             retVal = false;
         }
         if (myException.Message == expectValue)
         {
             TestLibrary.TestFramework.LogError("002.2", "the Message should return the default value.");
             retVal = false;
         }
         if (!(myException.InnerException is ArgumentException))
         {
             TestLibrary.TestFramework.LogError("002.3", "the InnerException should return NotImplementedException.");
             retVal = false;
         }
     }
     catch (Exception e)
     {
         TestLibrary.TestFramework.LogError("002.0", "Unexpected exception: " + e);
         retVal = false;
     }
     return retVal;
 }
Ejemplo n.º 3
0
        public void AggregateException()
        {
            var inner1 = new DivideByZeroException("inner #1");
            var inner2 = new NotImplementedException("inner #2");
            var inner3 = new XunitException("this is crazy");
            var outer = new AggregateException(inner1, inner2, inner3);

            var result = ExceptionUtility.GetMessage(outer);

            Assert.Equal("System.AggregateException : One or more errors occurred." + Environment.NewLine
                       + "---- System.DivideByZeroException : inner #1" + Environment.NewLine
                       + "---- System.NotImplementedException : inner #2" + Environment.NewLine
                       + "---- this is crazy", result);
        }
Ejemplo n.º 4
0
        public void ShouldFilterAssertionLibraryImplementationDetails()
        {
            var primaryException    = GetNestedException();
            var secondaryExceptionA = new NotImplementedException();
            var secondaryExceptionB = GetSecondaryNestedException();

            assertionLibrary
            .Namespace("Fixie.Tests.Results")
            .Namespace("System");

            var exceptionInfo = new ExceptionInfo(new[] { primaryException, secondaryExceptionA, secondaryExceptionB }, assertionLibrary);

            exceptionInfo.DisplayName.ShouldEqual("");
            exceptionInfo.Type.ShouldEqual("System.NullReferenceException");
            exceptionInfo.Message.ShouldEqual("Null reference!");
            exceptionInfo.StackTrace
            .Split(new[] { Environment.NewLine }, StringSplitOptions.None)
            .Select(x => Regex.Replace(x, @":line \d+", ":line #"))     //Avoid brittle assertion introduced by stack trace line numbers.
            .ShouldEqual(
                "Null reference!",
                "",
                "",
                "------- Inner Exception: System.DivideByZeroException -------",
                "Divide by zero!",
                "",
                "",
                "===== Secondary Exception: System.NotImplementedException =====",
                "The method or operation is not implemented.",
                "",
                "",
                "===== Secondary Exception: System.ArgumentException =====",
                "Argument!",
                "",
                "",
                "------- Inner Exception: System.ApplicationException -------",
                "Application!",
                "",
                "",
                "------- Inner Exception: System.NotImplementedException -------",
                "Not implemented!",
                "");

            exceptionInfo.InnerException.ShouldBeNull();
        }
Ejemplo n.º 5
0
        public void WatchedDirectoryProcessAvailableImagesWhenImageIsInBaseDirectoryAndModeIsUploadAndClearShouldThrowNotImplementedException()
        {
            // Arrange
            var testBundle     = new WatchedDirectoryTestBundle();
            var watchDirectory = new WatchDirectory {
                FileExtensions = "abc", Mode = OperationMode.UploadAndClear
            };
            var mockWatchedFileRepository = new Mock <IWatchedFileRepository>();
            var mockWatchedFile           = new Mock <IWatchedFile>();
            var mockLog = new Mock <ILog>();
            NotImplementedException thrownException = null;
            var mockServer = new Mock <ImageServer>();

            testBundle.MockDirectoryScanner.Setup(x => x.GetAvailableImages(mockWatchedFileRepository.Object, null, It.IsAny <IList <string> >(), false, null))
            .Returns(new List <IWatchedFile> {
                mockWatchedFile.Object
            });

            testBundle.MockLogProvider.Setup(x => x.GetLogger(It.IsAny <Type>())).Returns(mockLog.Object);

            mockWatchedFile.Setup(x => x.IsInBaseDirectory(null)).Returns(true);

            testBundle.WatchedDirectory.Configure(watchDirectory);

            // Act
            try
            {
                testBundle.WatchedDirectory.ProcessAvailableImages(mockWatchedFileRepository.Object, mockServer.Object);
            }
            catch (NotImplementedException ex)
            {
                thrownException = ex;
            }

            // Assert
            mockWatchedFileRepository.Verify(x => x.LoadFileForPath(It.IsAny <string>()), Times.Never);
            mockWatchedFileRepository.Verify(x => x.CreateNew(), Times.Never);
            mockWatchedFileRepository.Verify(x => x.Save(mockWatchedFile.Object), Times.Never);
            mockWatchedFile.VerifySet(x => x.UploadSuccessful = false, Times.Never);
            mockWatchedFile.Verify(x => x.SendToServer(mockServer.Object), Times.Never);
            mockWatchedFile.Verify(x => x.SortFile(), Times.Never);
            mockWatchedFile.Verify(x => x.RemoveFromDisk(), Times.Never);
            Assert.IsNotNull(thrownException);
        }
Ejemplo n.º 6
0
        private static void HandleResult(JpegLSError result, StringBuilder errorMessage)
        {
            Exception exception;

            switch (result)
            {
            case JpegLSError.None:
                return;

            case JpegLSError.TooMuchCompressedData:
            case JpegLSError.InvalidJlsParameters:
            case JpegLSError.InvalidCompressedData:
            case JpegLSError.CompressedBufferTooSmall:
            case JpegLSError.ImageTypeNotSupported:
            case JpegLSError.UnsupportedBitDepthForTransform:
            case JpegLSError.UnsupportedColorTransform:
            case JpegLSError.UnsupportedEncoding:
            case JpegLSError.UnknownJpegMarker:
            case JpegLSError.MissingJpegMarkerStart:
            case JpegLSError.UnspecifiedFailure:
                exception = new InvalidDataException(errorMessage.ToString());
                break;

            case JpegLSError.UncompressedBufferTooSmall:
            case JpegLSError.ParameterValueNotSupported:
                exception = new ArgumentException(errorMessage.ToString());
                break;

            case JpegLSError.UnexpectedFailure:
                exception = new InvalidOperationException("Unexpected failure. The state of the implementation may be invalid.");
                break;

            default:
                exception = new NotImplementedException(string.Format(CultureInfo.InvariantCulture,
                                                                      "The native codec has returned an unexpected result value: {0}", result));
                break;
            }

            var data = exception.Data;

            Contract.Assume(data != null);
            data.Add("JpegLSError", result);
            throw exception;
        }
Ejemplo n.º 7
0
        public void TestAllOpCodesInEngine()
        {
            var            opCodeFields       = typeof(OpCodes).GetFields(BindingFlags.Public | BindingFlags.Static);
            ILOpCodeValues parseResult        = ILOpCodeValues.Nop;
            var            notCovered         = new List <ILOpCodeValues>(Enum.GetValues(typeof(ILOpCodeValues)).Cast <ILOpCodeValues>());
            var            notImplementedList = new List <Exception>();

            foreach (var field in opCodeFields)
            {
                var opCode = (OpCode)field.GetValue(null);

                var name   = field.Name;
                var lookup = Enum.TryParse(name, out parseResult);
                if (parseResult == ILOpCodeValues.Break)
                {
                    continue;
                }

                if (bool.Parse(bool.TrueString) || notCovered.Contains(parseResult))
                {
                    ILOpCodeValues[] used   = null;
                    Exception        caught = null;
                    try
                    {
                        used = RunTestForOpCode(opCode);
                        Assert.IsNotNull(used, $"OpCode test {opCode} failed to return used opcodes");
                        notCovered.RemoveAll(x => used.Contains(x));
                    }
                    catch (NotImplementedException niex)
                    {
                        var listEx = new NotImplementedException($"Test {opCode} is not implemented", niex);
                        notImplementedList.Add(listEx);
                    }
                    catch (Exception ex)
                    {
                        caught = ex;
                    }
                    Assert.IsNull(caught, $"Error executing Test {opCode}: {caught}");
                }
            }
            Assert.IsTrue(notImplementedList.Count > 0, "Test failed to throw missing test exception");
            throw notImplementedList[0];
        }
Ejemplo n.º 8
0
        public async Task Controller_ShouldNotify_IfProcessingFails_EvenOnLeaseLost()
        {
            Mock.Get(this.partitionProcessor)
            .Reset();

            Mock <PartitionSupervisor> supervisor = new Mock <PartitionSupervisor>();

            Exception exception = new NotImplementedException();

            ManualResetEvent manualResetEvent = new ManualResetEvent(false);

            // Fail on Release
            Mock.Get(this.leaseManager)
            .Setup(manager => manager.ReleaseAsync(this.lease))
            .ThrowsAsync(new Exceptions.LeaseLostException());

            supervisor
            .Setup(s => s.RunAsync(It.IsAny <CancellationToken>()))
            .Callback((CancellationToken ct) =>
            {
                manualResetEvent.Set();
                throw exception;
            });

            Mock.Get(this.partitionSupervisorFactory)
            .Setup(f => f.Create(this.lease))
            .Returns(supervisor.Object);

            await this.sut.AddOrUpdateLeaseAsync(this.lease).ConfigureAwait(false);

            bool timeout = manualResetEvent.WaitOne(100);

            Assert.IsTrue(timeout, "Partition supervisor not started");

            this.healthMonitor
            .Verify(m => m.NotifyErrorAsync(this.lease.CurrentLeaseToken, exception), Times.Once);

            Mock.Get(this.leaseManager)
            .Verify(manager => manager.ReleaseAsync(this.lease), Times.Once);

            this.healthMonitor
            .Verify(m => m.NotifyLeaseReleaseAsync(this.lease.CurrentLeaseToken), Times.Once);
        }
Ejemplo n.º 9
0
        protected override void beforeEach()
        {
            theSettings  = new ApplicationSettings();
            theSource    = MockFor <IApplicationSource>();
            theException = new NotImplementedException();

            Services.PartialMockTheClassUnderTest();
            ClassUnderTest.Expect(x => x.StartApplication(theSource, theSettings, null))
            .Constraints(Is.Same(theSource), Is.Same(theSettings), Is.TypeOf <ManualResetEvent>())
            .Throw(theException);

            MockFor <IApplicationSourceFinder>().Stub(x => x.FindSource(null, null))
            .Constraints(Is.Same(theSettings),
                         Is.TypeOf <ApplicationStartResponse>())
            .Return(theSource);


            theResponse = ClassUnderTest.StartApplication(theSettings, new ManualResetEvent(true));
        }
        private Task HandleExceptionAsync(HttpContext context, Exception exception, IHostingEnvironment env)
        {
            var code    = HttpStatusCode.InternalServerError;
            var message = exception.Message;

            code = exception switch
            {
                NotImplementedException _ => HttpStatusCode.NotImplemented,
                                        _ => code
            };

            _logger.LogError("Error occured while processing request: {error}", message);


            context.Response.ContentType = "application/json";
            context.Response.StatusCode  = (int)code;
            return(Task.CompletedTask);
        }
    }
Ejemplo n.º 11
0
        static void Main(string[] args)
        {
            int x = 0;

            try
            {
                int y = 100 / x;
            }
            //catch (Exception e)  //會印出anyway,  it's OK+  123456
            catch (NullReferenceException e)  //印出anyway,  it's OK
            {
                Console.WriteLine(e.Message);
            }
            catch (DivideByZeroException e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                Console.WriteLine("anyway, it's OK");
            }
            Console.WriteLine("123456");
            //throw new NullReferenceException();

            var ae   = new ArgumentException();           //參數異常
            var ane  = new ArgumentNullException();       //參數為空
            var aore = new ArgumentOutOfRangeException(); //參數超出範圍
            var dne  = new DirectoryNotFoundException();  //路徑異常
            var fne  = new FileNotFoundException();       //檔案找不到
            var ioe  = new InvalidOperationException();   //運算錯誤
            var nie  = new NotImplementedException();     //未實現異常

            if (true)
            {
            }
            try
            {
                throw new Exception();
            }
            catch (Exception e)
            {
            }
        }
Ejemplo n.º 12
0
        public void Should_rethrow_aggregate_exception_with_multiple_exceptions_from_inside_delegate__pessimistic()
        {
            var policy = Policy.Timeout(TimeSpan.FromSeconds(10), TimeoutStrategy.Pessimistic);
            var msg    = "Aggregate Exception thrown from the delegate";

            Exception          innerException1    = new NotImplementedException();
            Exception          innerException2    = new DivideByZeroException();
            AggregateException aggregateException = new AggregateException(msg, innerException1, innerException2);
            Action             action             = () => { throw aggregateException; };

            // Whether executing the delegate directly, or through the policy, exception behavior should be the same.
            action.ShouldThrow <AggregateException>()
            .WithMessage(aggregateException.Message)
            .And.InnerExceptions.Should().BeEquivalentTo <Exception>(new[] { innerException1, innerException2 });

            policy.Invoking(p => p.Execute(action)).ShouldThrow <AggregateException>()
            .WithMessage(aggregateException.Message)
            .And.InnerExceptions.Should().BeEquivalentTo <Exception>(new[] { innerException1, innerException2 });
        }
Ejemplo n.º 13
0
        public void ReferenceApplicationEventSourceExtensionsTest()
        {
            List <EventEntry>       _lastEvents  = new List <EventEntry>();
            ObservableEventListener _listener    = new ObservableEventListener();
            IDisposable             subscription = _listener.Subscribe(x => { _lastEvents.Add(x); });

            using (SinkSubscription <ObservableEventListener> _sinkSubscription = new SinkSubscription <ObservableEventListener>(subscription, _listener))
            {
                Assert.IsNotNull(_sinkSubscription.Sink);

                ReferenceApplicationEventSource _log = ReferenceApplicationEventSource.Log;
                _sinkSubscription.Sink.EnableEvents(_log, EventLevel.LogAlways, EventKeywords.All);

                Assert.AreEqual <int>(0, _lastEvents.Count);
                NotImplementedException _ex = new NotImplementedException("testing exception", new NotImplementedException());
                _log.LogException(_ex);
                Assert.AreEqual <int>(2, _lastEvents.Count);

                //_lastEvent content
                Assert.AreEqual <int>(1, _lastEvents[0].EventId);
                Assert.AreEqual <Guid>(Guid.Empty, _lastEvents[0].ActivityId);
                string _message = "Application Failure: An exception has benn caught: of type NotImplementedException capturing the message: testing exception";
                Assert.AreEqual <string>(_message, _lastEvents[0].FormattedMessage);
                //schema
                EventSchema _Schema = _lastEvents[0].Schema;
                Assert.AreEqual <string>("InfrastructureInfo", _Schema.EventName);
                Assert.AreEqual <int>(1, _Schema.Id);
                //Assert.IsTrue((_Schema.Keywords & SemanticEventSource.Keywords.Diagnostic2) > 0);
                //Assert.AreEqual<string>("PackageContent", _Schema.KeywordsDescription);
                Assert.AreEqual <EventLevel>(EventLevel.Error, _Schema.Level);
                Assert.AreEqual <string>("Info", _Schema.OpcodeName);
                Assert.AreEqual <EventOpcode>(EventOpcode.Info, _Schema.Opcode);
                Assert.AreEqual <Guid>(new Guid("D8637D00-5EAD-4538-9286-8C6DE346D8C8"), _Schema.ProviderId);
                Assert.AreEqual <string>("UAOOI-Networking-ReferenceApplication-Diagnostic", _Schema.ProviderName);
                Assert.AreEqual <string>("Infrastructure", _Schema.TaskName);
                Assert.AreEqual <EventTask>(Tasks.Infrastructure, _Schema.Task);
                Assert.AreEqual <int>(0, _Schema.Version);

                //Payload
                Assert.AreEqual <string>("System.Collections.ObjectModel.ReadOnlyCollection`1[System.Object]", _lastEvents[0].Payload.ToString(), _lastEvents[0].Payload.ToString());
                Assert.AreEqual <int>(1, _lastEvents[0].Payload.Count);
            }
        }
        protected override void beforeEach()
        {
            logs        = Services.RecordLogging();
            correlation = new BehaviorCorrelation(new FakeNode());
            Services.Inject(correlation);
            Services.Inject <IExceptionHandlingObserver>(new ExceptionHandlingObserver());

            exception = new NotImplementedException();
            inner     = MockFor <IActionBehavior>();
            inner.Expect(x => x.InvokePartial()).Throw(exception);
            MockFor <IDebugDetector>().Stub(x => x.IsDebugCall()).Return(true);

            ClassUnderTest.Inner = inner;

            Exception <NotImplementedException> .ShouldBeThrownBy(() =>
            {
                ClassUnderTest.InvokePartial();
            });
        }
Ejemplo n.º 15
0
        [TestMethod] public void StaticDelegateToXml_Testing()
        {
            {             // Should Succeed
                Func <int, string, object, decimal> functionToSerialize = StaticMethod;
                string serialization = Serialization.StaticDelegateToXml(functionToSerialize);
                Assert.IsFalse(string.IsNullOrWhiteSpace(serialization));
            }
            {             // Should Fail (Non-Static)
                Action nonStaticDelegate = NonStaticMethod;
                Assert.ThrowsException <NotSupportedException>(() => Serialization.StaticDelegateToXml(nonStaticDelegate));
            }
            {             // Should Fail (Local Function)
                Exception notImplemented = new NotImplementedException();
                void LocalFunctionToSerializeFail() => throw notImplemented;

                Action nonStaticDelegate = LocalFunctionToSerializeFail;
                Assert.ThrowsException <NotSupportedException>(() => Serialization.StaticDelegateToXml(nonStaticDelegate));
            }
            {             // Should Fail (Static Local Function)
Ejemplo n.º 16
0
        public void Should_rethrow_aggregate_exception_with_multiple_exceptions_from_inside_delegate__pessimistic()
        {
            var policy = Policy.Timeout <ResultPrimitive>(TimeSpan.FromSeconds(10), TimeoutStrategy.Pessimistic);
            var msg    = "Aggregate Exception thrown from the delegate";

            Exception              innerException1    = new NotImplementedException();
            Exception              innerException2    = new DivideByZeroException();
            AggregateException     aggregateException = new AggregateException(msg, innerException1, innerException2);
            Func <ResultPrimitive> func = () => { Helper_ThrowException(aggregateException); return(ResultPrimitive.WhateverButTooLate); };

            // Whether executing the delegate directly, or through the policy, exception behavior should be the same.
            func.Should().Throw <AggregateException>()
            .WithMessage(aggregateException.Message)
            .And.InnerExceptions.Should().BeEquivalentTo <Exception>(new[] { innerException1, innerException2 });

            policy.Invoking(p => p.Execute(func)).Should().Throw <AggregateException>()
            .WithMessage(aggregateException.Message)
            .And.InnerExceptions.Should().BeEquivalentTo <Exception>(new[] { innerException1, innerException2 });
        }
Ejemplo n.º 17
0
        public async Task TryCheckpoint_OnUnknownException()
        {
            NotImplementedException cosmosException = new NotImplementedException();
            string          leaseToken      = Guid.NewGuid().ToString();
            string          continuation    = Guid.NewGuid().ToString();
            ResponseMessage responseMessage = new ResponseMessage(HttpStatusCode.OK);

            responseMessage.Headers.ContinuationToken = continuation;
            Mock <PartitionCheckpointer> checkpointer = new Mock <PartitionCheckpointer>();

            checkpointer.Setup(c => c.CheckpointPartitionAsync(It.Is <string>(s => s == continuation))).ThrowsAsync(cosmosException);
            ChangeFeedObserverContextCore changeFeedObserverContextCore = new ChangeFeedObserverContextCore(leaseToken, responseMessage, checkpointer.Object);

            (bool isSuccess, Exception exception) = await changeFeedObserverContextCore.TryCheckpointAsync();

            Assert.IsFalse(isSuccess);
            Assert.IsNotNull(exception);
            Assert.ReferenceEquals(cosmosException, exception);
        }
Ejemplo n.º 18
0
        public void when_serializing_exception_notice_result_should_not_be_empty()
        {
            var       client    = new RollbarClient();
            Exception exception = new NotImplementedException();

            var notice = client.NoticeBuilder.CreateExceptionNotice(exception);

            notice.Server.Host    = "miker";
            notice.Request.Url    = "http://localhost/hej";
            notice.Request.Method = "GET";
            notice.Request.Headers.Add("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31");
            notice.Request.UserIp  = "67.90.39.34";
            notice.Person.Id       = "123";
            notice.Person.Username = Environment.UserName;

            var serialized = client.Serialize(notice);

            Assert.IsNotNullOrEmpty(serialized);
        }
Ejemplo n.º 19
0
        public void ExceptionHelper_TryAddException_Aggregated()
        {
            var ex1 = new InvalidOperationException();
            var ex2 = new NotImplementedException();

            errors = new AggregateException(ex1, ex2);

            var ex3 = new InvalidCastException();

            Assert.True(ExceptionHelper.TryAddException(ref errors, ex3));

            Assert.True(errors is AggregateException);
            var x = errors as AggregateException;

            Assert.Equal(3, x.InnerExceptions.Count);
            Assert.True(x.InnerExceptions[0] is InvalidOperationException);
            Assert.True(x.InnerExceptions[1] is NotImplementedException);
            Assert.True(x.InnerExceptions[2] is InvalidCastException);
        }
Ejemplo n.º 20
0
        public void SendError()
        {
            var errors  = new List <Tuple <Exception, string> >();
            var myError = new NotImplementedException();

            Run <Guid>(
                afterSend: fs => { throw myError; },
                act: (logger) =>
            {
                logger.ErrorLogger = (ex, msg) => errors.Add(Tuple.Create(ex, msg));

                for (int i = 0; i < 10; i++)
                {
                    var g = Guid.NewGuid();
                    logger.Write(ref g);
                }
            },
                assert: (files, dir) =>
            {
                Assert.Equal(1, errors.Count);
                Assert.ReferenceEquals(errors[0].Item1, myError);
            });

            int afterSendCount = 0;

            // do it again without custom error logger
            Run <Guid>(
                afterSend: fs => { afterSendCount++; throw myError; },
                act: (logger) =>
            {
                for (int i = 0; i < 10; i++)
                {
                    var g = Guid.NewGuid();
                    logger.Write(ref g);
                }
            },
                assert: (files, dir) =>
            {
                Assert.Equal(1, errors.Count);
                Assert.Equal(1, afterSendCount);
            });
        }
Ejemplo n.º 21
0
        private async Task SendResponseAsync(
            IFileSystemEntry entry,
            MediaContext mediaContext,
            Stream stream,
            TimeSpan maxAge)
        {
            mediaContext.ComprehendRequestHeaders(entry.LastModifiedUtc, entry.ContentLength);

            switch (mediaContext.GetPreconditionState())
            {
            case MediaContext.PreconditionState.Unspecified:
            case MediaContext.PreconditionState.ShouldProcess:
                if (mediaContext.IsHeadRequest())
                {
                    await mediaContext.SendStatusAsync(ResponseConstants.Status200Ok, entry.ContentType, maxAge);

                    return;
                }

                this.logger.LogFileServed(mediaContext.GetDisplayUrl(), entry.Name);
                await mediaContext.SendAsync(stream, entry.ContentType, maxAge);

                return;

            case MediaContext.PreconditionState.NotModified:
                this.logger.LogFileNotModified(mediaContext.GetDisplayUrl());
                await mediaContext.SendStatusAsync(ResponseConstants.Status304NotModified, entry.ContentType, maxAge);

                return;

            case MediaContext.PreconditionState.PreconditionFailed:
                this.logger.LogFilePreconditionFailed(mediaContext.GetDisplayUrl());
                await mediaContext.SendStatusAsync(ResponseConstants.Status412PreconditionFailed, entry.ContentType, maxAge);

                return;

            default:
                var exception = new NotImplementedException(mediaContext.GetPreconditionState().ToString());
                Debug.Fail(exception.ToString());
                throw exception;
            }
        }
Ejemplo n.º 22
0
        public void ExecuteAsync_IfFilterChangesException_ThrowsUpdatedException()
        {
            // Arrange
            Exception expectedException = new NotImplementedException();

            using (HttpRequestMessage request = CreateRequest())
            {
                HttpActionContext context = CreateActionContext(request);

                Mock <IExceptionFilter> filterMock = new Mock <IExceptionFilter>();
                filterMock
                .Setup(f => f.ExecuteExceptionFilterAsync(It.IsAny <HttpActionExecutedContext>(),
                                                          It.IsAny <CancellationToken>()))
                .Callback <HttpActionExecutedContext, CancellationToken>((c, t) =>
                {
                    c.Exception = expectedException;
                })
                .Returns(() => Task.FromResult <object>(null));
                IExceptionFilter   filter  = filterMock.Object;
                IExceptionFilter[] filters = new IExceptionFilter[] { filter };

                IExceptionLogger  exceptionLogger  = CreateStubExceptionLogger();
                IExceptionHandler exceptionHandler = CreateStubExceptionHandler();

                IHttpActionResult innerResult = CreateStubActionResult(
                    CreateFaultedTask <HttpResponseMessage>(CreateException()));

                IHttpActionResult product = CreateProductUnderTest(context, filters, exceptionLogger, exceptionHandler,
                                                                   innerResult);

                // Act
                Task <HttpResponseMessage> task = product.ExecuteAsync(CancellationToken.None);

                // Assert
                Assert.NotNull(task);
                task.WaitUntilCompleted();
                Assert.Equal(TaskStatus.Faulted, task.Status);
                Assert.NotNull(task.Exception);
                Exception exception = task.Exception.GetBaseException();
                Assert.Same(expectedException, exception);
            }
        }
Ejemplo n.º 23
0
        protected override void beforeEach()
        {
            logs = new RecordingRequestTrace();
            Services.Inject <IRequestTrace>(logs);

            correlation = new BehaviorCorrelation(new FakeNode());
            Services.Inject(correlation);
            Services.Inject <IExceptionHandlingObserver>(new ExceptionHandlingObserver());

            exception = new NotImplementedException();
            inner     = MockFor <IActionBehavior>();
            inner.Expect(x => x.Invoke()).Throw(exception);

            ClassUnderTest.Inner = inner;

            Exception <NotImplementedException> .ShouldBeThrownBy(() =>
            {
                ClassUnderTest.Invoke();
            });
        }
        public void SetUp()
        {
            good = Expression.Constant("I am good");

            genericEx    = new NotImplementedException();
            throwGeneral = Expression.Block(Expression.Throw(Expression.Constant(genericEx)),
                                            Expression.Constant("bar"));

            smEx    = new StructureMapException("you stink!");
            throwSM = Expression.Block(Expression.Throw(Expression.Constant(smEx)),
                                       Expression.Constant("bar"));

            var gateway = new StubbedGateway();

            Expression <Action> goodExpr = () => gateway.DoSomething();

            goodVoid  = Expression.Block(goodExpr.Body);
            badVoid   = Expression.Block(Expression.Throw(Expression.Constant(genericEx)));
            badSmVoid = Expression.Block(Expression.Throw(Expression.Constant(smEx)));
        }
Ejemplo n.º 25
0
        public void TestConstructor__UnknownPassSpecifier()
        {
            IPatch patch = Substitute.For <IPatch>();

            UrlDir.UrlConfig urlConfig     = UrlBuilder.CreateConfig("abc/def", new ConfigNode("NODE"));
            IPassSpecifier   passSpecifier = Substitute.For <IPassSpecifier>();

            passSpecifier.Descriptor.Returns(":SOMEPASS");
            patch.PassSpecifier.Returns(passSpecifier);
            IPatchProgress progress = Substitute.For <IPatchProgress>();

            NotImplementedException ex = Assert.Throws <NotImplementedException>(delegate
            {
                new PatchList(new string[0], new[] { patch }, progress);
            });

            Assert.Equal("Don't know what to do with pass specifier: :SOMEPASS", ex.Message);

            progress.DidNotReceive().PatchAdded();
        }
        public void StreamWrapper_ShouldThrowNotImplementedException_WhenWriteCalled()
        {
            // Arrange
            var stremMock     = new Mock <IStream>();
            var streamWrapper = new StreamWrapper(stremMock.Object);
            NotImplementedException exception = null;

            // Act
            try
            {
                streamWrapper.Write(new byte[5], 0, 0);
            }
            catch (NotImplementedException ex)
            {
                exception = ex;
            }

            // Assert
            Assert.IsNotNull(exception);
        }
        public void RemoveSettingThrowsExceptionTest()
        {
            const string exceptionMessage = "Cannot remove a setting from this class.";

            ISettingProvider provider = new StaticSettingProvider(TestVersion, _testSetting);

            NotImplementedException thrownException = null;

            try
            {
                provider.RemoveSetting(TestVersion);
            }
            catch (NotImplementedException nie)
            {
                thrownException = nie;
            }

            Assert.IsNotNull(thrownException);
            Assert.AreEqual(exceptionMessage, thrownException.Message);
        }
Ejemplo n.º 28
0
        public void ExecuteAsync_RunsExceptionFilter_WhenAuthenticationFilterChallengeThrowsException()
        {
            // Arrange
            Exception     expectedException         = new NotImplementedException();
            ApiController controller                = new ExceptionlessController();
            Mock <IAuthenticationFilter> filterMock = new Mock <IAuthenticationFilter>();

            filterMock.Setup(f => f.AuthenticateAsync(It.IsAny <HttpAuthenticationContext>(),
                                                      It.IsAny <CancellationToken>())).Returns(() => Task.FromResult <object>(null));
            filterMock.Setup(f => f.ChallengeAsync(It.IsAny <HttpAuthenticationChallengeContext>(),
                                                   It.IsAny <CancellationToken>())).Callback(() =>
            {
                throw expectedException;
            });
            IAuthenticationFilter filter = filterMock.Object;

            // Act & Assert
            TestExceptionFilter(controller, expectedException, (configuration) =>
                                { configuration.Filters.Add(filter); });
        }
Ejemplo n.º 29
0
        public void StreamWrapper_ShouldThrowNotImplementedException_WhenSetLengthCalled()
        {
            // Arrange
            var stremMock     = new Mock <IStream>();
            var streamWrapper = new ReadonlyStream(stremMock.Object);
            NotImplementedException exception = null;

            // Act
            try
            {
                streamWrapper.SetLength(5);
            }
            catch (NotImplementedException ex)
            {
                exception = ex;
            }

            // Assert
            Assert.IsNotNull(exception);
        }
Ejemplo n.º 30
0
        protected override void beforeEach()
        {
            theLog = MockFor <IActivationLog>();

            theJobs = Services.CreateMockArrayFor <IPollingJob>(5);
            foreach (var pollingJob in theJobs)
            {
                pollingJob.Stub(_ => _.JobType).Return(typeof(AJob));
            }

            Services.Inject <IPollingJobs>(new PollingJobs(theJobs));

            ex1 = new NotImplementedException();
            ex2 = new NotSupportedException();

            theJobs[1].Expect(x => x.Start()).Throw(ex1);
            theJobs[2].Expect(x => x.Start()).Throw(ex2);

            ClassUnderTest.Activate(theLog, null);
        }
Ejemplo n.º 31
0
 // Returns true if the expected result is right
 // Returns false if the expected result is wrong
 public bool PosTest1()
 {
     bool retVal = true;
     TestLibrary.TestFramework.BeginScenario("PosTest1: Create a new instance of NotImplementedException.");
     try
     {
         NotImplementedException myException = new NotImplementedException();
         if (myException == null)
         {
             TestLibrary.TestFramework.LogError("001.1", "NotImplementedException instance can not create correctly.");
             retVal = false;
         }
     }
     catch (Exception e)
     {
         TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e);
         retVal = false;
     }
     return retVal;
 }
        public static HttpStatusCodeInfo Map(Exception exception)
        {
            var code = exception switch
            {
                UnauthorizedAccessException _ => HttpStatusCode.Unauthorized,
                NotImplementedException _ => HttpStatusCode.NotImplemented,
                InvalidOperationException _ => HttpStatusCode.Conflict,
                ArgumentException _ => HttpStatusCode.BadRequest,
                ValidationException _ => HttpStatusCode.BadRequest,
                MartenCommandException martenCommandException =>
                (martenCommandException.InnerException as PostgresException)?.SqlState ==
                PostgresErrorCodes.UniqueViolation
                    ? HttpStatusCode.Conflict
                    : HttpStatusCode.InternalServerError,
                _ => HttpStatusCode.InternalServerError
            };

            return(new HttpStatusCodeInfo(code, (exception.InnerException as PostgresException)?.Message ?? exception.Message));
        }
    }
Ejemplo n.º 33
0
        public void Should_rethrow_aggregate_exception_with_another_example_cause_of_multiple_exceptions_from_inside_delegate__pessimistic()
        {
            var policy = Policy.Timeout(TimeSpan.FromSeconds(10), TimeoutStrategy.Pessimistic);

            Exception innerException1 = new NotImplementedException();
            Exception innerException2 = new DivideByZeroException();
            Action    action          = () =>
            {
                Action action1 = () => { throw innerException1; };
                Action action2 = () => { throw innerException2; };
                Parallel.Invoke(action1, action2);
            };

            // Whether executing the delegate directly, or through the policy, exception behavior should be the same.
            action.ShouldThrow <AggregateException>()
            .And.InnerExceptions.Should().BeEquivalentTo <Exception>(new[] { innerException1, innerException2 });

            policy.Invoking(p => p.Execute(action)).ShouldThrow <AggregateException>()
            .And.InnerExceptions.Should().BeEquivalentTo <Exception>(new[] { innerException1, innerException2 });
        }
        public void ExecuteAsync_WhenFilterChangesException_ThrowsUpdatedException()
        {
            // Arrange
            Exception expectedException = new NotImplementedException();

            HttpActionContext context = CreateActionContext();

            Mock<IExceptionFilter> filterMock = new Mock<IExceptionFilter>();
            filterMock
                .Setup(f => f.ExecuteExceptionFilterAsync(It.IsAny<HttpActionExecutedContext>(),
                    It.IsAny<CancellationToken>()))
                .Callback<HttpActionExecutedContext, CancellationToken>((c, t) =>
                {
                    c.Exception = expectedException;
                })
                .Returns(() => Task.FromResult<object>(null));
            IExceptionFilter filter = filterMock.Object;
            IExceptionFilter[] filters = new IExceptionFilter[] { filter };

            TaskCompletionSource<HttpResponseMessage> taskSource = new TaskCompletionSource<HttpResponseMessage>();
            taskSource.SetException(new InvalidOperationException());
            IHttpActionResult innerResult = CreateStubActionResult(taskSource.Task);

            IHttpActionResult product = CreateProductUnderTest(context, filters, innerResult);

            // Act
            Task<HttpResponseMessage> task = product.ExecuteAsync(CancellationToken.None);

            // Assert
            Assert.NotNull(task);
            task.WaitUntilCompleted();
            Assert.Equal(TaskStatus.Faulted, task.Status);
            Assert.NotNull(task.Exception);
            Exception exception = task.Exception.GetBaseException();
            Assert.Same(expectedException, exception);
        }
Ejemplo n.º 35
0
        public void ExecuteAsync_RunsExceptionFilter_WhenAuthenticationFilterChallengeThrowsException()
        {
            // Arrange
            Exception expectedException = new NotImplementedException();
            ApiController controller = new ExceptionlessController();
            Mock<IAuthenticationFilter> filterMock = new Mock<IAuthenticationFilter>();
            filterMock.Setup(f => f.AuthenticateAsync(It.IsAny<HttpAuthenticationContext>(),
                It.IsAny<CancellationToken>())).Returns(() => Task.FromResult<object>(null));
            filterMock.Setup(f => f.ChallengeAsync(It.IsAny<HttpAuthenticationChallengeContext>(),
                It.IsAny<CancellationToken>())).Callback(() =>
                {
                    throw expectedException;
                });
            IAuthenticationFilter filter = filterMock.Object;

            // Act & Assert
            TestExceptionFilter(controller, expectedException, (configuration) =>
            { configuration.Filters.Add(filter); });
        }
Ejemplo n.º 36
0
        public void ExecuteAsync_RunsExceptionFilter_WhenAuthorizationFilterThrowsException()
        {
            // Arrange
            Exception expectedException = new NotImplementedException();
            ApiController controller = new ExceptionlessController();
            Mock<IAuthorizationFilter> filterMock = new Mock<IAuthorizationFilter>();
            filterMock.Setup(f => f.ExecuteAuthorizationFilterAsync(It.IsAny<HttpActionContext>(),
                It.IsAny<CancellationToken>(), It.IsAny<Func<Task<HttpResponseMessage>>>())).Callback(() =>
            {
                throw expectedException;
            });
            IAuthorizationFilter filter = filterMock.Object;

            // Act & Assert
            TestExceptionFilter(controller, expectedException, (configuration) =>
                { configuration.Filters.Add(filter); });
        }
Ejemplo n.º 37
0
        public void ExecuteAsync_RunsExceptionFilter_WhenActionThrowsException()
        {
            // Arrange
            Exception expectedException = new NotImplementedException();
            ApiController controller = new ExceptionController(expectedException);

            // Act & Assert
            TestExceptionFilter(controller, expectedException, configure: null);
        }
        public Task CopyResultToCompletionSource_WithInputValue_FaultedTask()
        {
            // Arrange
            var tcs = new TaskCompletionSource<int>();
            var expectedException = new NotImplementedException();

            return TaskHelpers.FromError<int>(expectedException)

            // Act
                              .CopyResultToCompletionSource(tcs)

            // Assert
                              .ContinueWith(task =>
                              {
                                  Assert.Equal(TaskStatus.RanToCompletion, task.Status); // Outer task always runs to completion
                                  Assert.Equal(TaskStatus.Faulted, tcs.Task.Status);
                                  Assert.Same(expectedException, tcs.Task.Exception.GetBaseException());
                              });
        }