public void TestCreateMatroshika() { var value = new InvalidOperationException( Guid.NewGuid().ToString(), new Exception() ); var result = ExceptionDispatchInfo.CreateMatroshika( value ); Assert.That( result, Is.Not.Null ); Assert.That( result, Is.TypeOf( value.GetType() ) ); Assert.That( result.Message, Is.EqualTo( value.Message ) ); Assert.That( result.InnerException, Is.SameAs( value ) ); }
public void SerializesProperties() { var exception = new InvalidOperationException("Some message") { HelpLink = "http://example.com" }; var errors = new ErrorSerializer().Serialize(new ApiError(exception))["errors"][0]; Assert.Equal(exception.Message, errors.Value<string>("title")); Assert.Equal(exception.HelpLink, errors["links"].Value<string>("about")); Assert.Equal(exception.GetType().FullName, errors.Value<string>("code")); Assert.Equal(exception.ToString(), errors.Value<string>("detail")); }
public void Invoke_WithExceptionAndInnerException_ThrowsInnerException( Mock<Common.IServiceLocator> serviceLocator, Mock<IRepository<Post>> repository, int postId, string message, InvalidOperationException innerException) { // Given var exception = new Exception(message, innerException); serviceLocator.Setup(s => s.GetInstance<IRepository<Post>>()).Returns(repository.Object); repository.Setup(s => s.Find(It.IsAny<Expression<Func<Post, bool>>>())).Throws(exception); var sut = new SetPostCommand(); ServiceLocator.SetCurrentInstance(serviceLocator.Object); // When sut.Id = postId; // Then Assert.Throws(innerException.GetType(), () => sut.Invoke<Post>().Any()); }
public void Should_report_failed_specification_end_to_TeamCity_with_exception() { Exception exception = new InvalidOperationException(); using (Mocks.Record()) { _messageProvider.TestStarted(null); LastCall.IgnoreArguments(); _messageProvider.TestFailed(null, null, null, null); LastCall.Constraints(Is.Anything(), Is.Equal(exception.Message), Is.Null(), Is.Equal(exception.GetType().FullName)); _messageProvider.TestFinished(null); LastCall.IgnoreArguments(); } _sut.OnContextStart(_contextInfo); using (Mocks.Playback()) { _sut.OnSpecificationStart(_specificationInfo); _sut.OnSpecificationEnd(_specificationInfo, Result.Failure(exception)); } }
public void Invoke_WithException_ThrowsSameException( Mock<Common.IServiceLocator> serviceLocator, Mock<IRepository<Post>> repository, InvalidOperationException exception) { // Given serviceLocator.Setup(s => s.GetInstance<IRepository<Post>>()).Returns(repository.Object); repository.Setup(s => s.Find(It.IsAny<string[]>())).Throws(exception); var sut = new GetPostCommand(); ServiceLocator.SetCurrentInstance(serviceLocator.Object); // Then Assert.Throws(exception.GetType(), () => sut.Invoke<Post>().Any()); }
// ------------------------------------------------------------------- // Get ValuePattern.Value property // ------------------------------------------------------------------- private void TS_Value(ValuePattern valuePattern, CheckType checkType) { bool isPassword = m_le.Current.IsPassword; string value = ""; try { value = valuePattern.Current.Value; } catch (Exception actualException) { InvalidOperationException ex = new InvalidOperationException(); if (Library.IsCriticalException(actualException)) throw; TestException(ex.GetType(), actualException, "TS_Value", checkType); } Comment("ValuePattern.Value = " + value); m_TestStep++; }
public void TestRemoveFromSelectionMethod51701(TestCaseAttribute testCase) { HeaderComment(testCase); InvalidOperationException ex = new InvalidOperationException("Unused, just need an instance for GetType() below"); RemoveFromSelectionHelper(ex.GetType()); }
public void TestRangeFromChildMethod20302(TestCaseAttribute testCase) { HeaderComment(testCase); InvalidOperationException ex = new InvalidOperationException("Unused, just need an instance for GetType() below"); RangeFromChildHelper(SampleText.String1, false, AutoElementType.SameAsPattern, ex.GetType()); }
/// <summary> /// expect packet from transport.<para/> /// the transport must be a TcpServer, UdpClient or UdpServer. /// </summary> /// <param name="filter"> /// a Filter delegate that specifies the endpoint to receive data.<para/> /// if null, receive data from any endpoint. /// </param> /// <param name="timeout"> /// a TimeSpan object that indicates the timeout to expect event. /// </param> /// <param name="removeEvent"> /// a bool value that indicates whether need to remove the event from buffer. /// </param> /// <param name="remoteEndPoint"> /// an object that specifies the remote endpoint expected packet. /// </param> /// <param name="localEndPoint"> /// an object that indicates the local endpoint received packet at. /// </param> /// <returns> /// a UdpReceivedBytes object that specifies the received udp packet.<para/> /// never return null, if no packets, throw exception. /// </returns> /// <exception cref="InvalidOperationException"> /// thrown when the received udp packet is invalid /// </exception> /// <exception cref="InvalidOperationException"> /// thrown when exception arrived when expect bytes from udp client. /// </exception> private UdpReceivedBytes GetUdpBytes( Filter<UdpReceivedBytes> filter, TimeSpan timeout, bool removeEvent, out object remoteEndPoint, out object localEndPoint) { UdpReceivedBytes bytes = null; if (filter == null) { bytes = this.buffer.Dequeue(timeout); } else { bytes = this.buffer.Dequeue(timeout, filter); } if (bytes == null) { throw new InvalidOperationException("the received udp packet is invalid"); } remoteEndPoint = bytes.RemoteEndPoint; localEndPoint = bytes.LocalEndPoint; // exception event arrived if (bytes.Packet == null) { if (!removeEvent) { this.buffer.Enqueue(bytes); } InvalidOperationException exc = new InvalidOperationException("exception arrived when expect bytes from udp client."); // identify this exception. exc.Data.Add(exc.GetType().Name, true); throw exc; } return bytes; }
/// <summary>operation with exception</summary> /// <param name="e">exception object</param> /// <param name="response">response object</param> private void HandleOperationException(InvalidOperationException e, IODataResponseMessage response) { Debug.Assert(this.entryIndex >= 0 && this.entryIndex < this.ChangedEntries.Count(), string.Format(System.Globalization.CultureInfo.InvariantCulture, "this.entryIndex = '{0}', this.ChangedEntries.Count = '{1}'", this.entryIndex, this.ChangedEntries.Count())); Descriptor current = this.ChangedEntries[this.entryIndex]; HeaderCollection headers = null; HttpStatusCode statusCode = HttpStatusCode.InternalServerError; Version responseVersion = null; if (null != response) { headers = new HeaderCollection(response); statusCode = (HttpStatusCode)response.StatusCode; this.HandleOperationResponseHeaders(statusCode, headers); e = BaseSaveResult.HandleResponse( this.RequestInfo, statusCode, response.GetHeader(XmlConstants.HttpODataVersion), response.GetStream, false/*throwOnFailure*/, out responseVersion); } else { headers = new HeaderCollection(); headers.SetHeader(XmlConstants.HttpContentType, XmlConstants.MimeTextPlain); // In V2 we used to merge individual responses from a call to SaveChanges() into a single batch response payload and then process that. // When we encounter an exception at this point in V2, we used to write the exception to the batch response payload and later on when we // process through the batch response, we create a DataServiceClientException for each failed operation. // For backcompat reason, we will always convert the exception type to DataServiceClientException here. Debug.Assert(e != null, "e != null"); if (e.GetType() != typeof(DataServiceClientException)) { e = new DataServiceClientException(e.Message, e); } } // For error scenarios, we never invoke the ReadingEntity event. this.cachedResponses.Add(new CachedResponse(current, headers, statusCode, responseVersion, null, e)); this.perRequest = null; this.CheckContinueOnError(); }
public void write_log_exception() { var ex = new InvalidOperationException("Fake Exception"); //Act Logger.ErrorException(UniqueMessage, ex); //Assert var logItem = Db.Fetch<Log>().Single(); VerifyLog(logItem, LogLevel.Error); logItem.Message.Should().Be(UniqueMessage + ": " + ex.Message); logItem.ExceptionType.Should().Be(ex.GetType().ToString()); logItem.Exception.Should().Be(ex.ToString()); ExceptionVerification.ExpectedErrors(1); }
/// <summary> /// get packet from packet cache or decode from buffer. /// </summary> /// <param name="timeout"> /// a TimeSpan object that specifies the timeout /// </param> /// <param name="removeEvent"> /// a bool value that indicates whether need to remove the event from buffer. /// </param> /// <param name="remoteEndPoint"> /// an object that specifies the remote endpoint. /// </param> /// <returns> /// a StackPacket object that contains the decoded packet. /// </returns> private StackPacket GetPacket(TimeSpan timeout, bool removeEvent, out object remoteEndPoint) { // get the packet in packet list. IPEndPointStackPacket packet = Utility.GetOne<IPEndPointStackPacket>(this.packetCache, null); if (packet != null) { remoteEndPoint = packet.RemoteEndPoint; return packet.Packet; } UdpReceivedBytes bytes = this.buffer.Dequeue(timeout); remoteEndPoint = bytes.RemoteEndPoint; // exception event arrived if (bytes.Packet == null) { if (!removeEvent) { this.buffer.Enqueue(bytes); } InvalidOperationException exc = new InvalidOperationException("exception arrived when expect packet from udp."); // identify this exception. exc.Data.Add(exc.GetType().Name, true); throw exc; } // decode packets using data in buffer. int consumedLength = 0; int expectedLength = 0; StackPacket[] packets = this.decoder(remoteEndPoint, bytes.Packet, out consumedLength, out expectedLength); // if no packet, drop the recieved data and continue. if (packets == null || packets.Length == 0) { throw new InvalidOperationException("udp client failed to decode udp packet"); } // if packet arrived, add to packet list, and return the first. foreach (StackPacket item in packets) { this.packetCache.Enqueue( new IPEndPointStackPacket(item, bytes.RemoteEndPoint, bytes.LocalEndPoint)); } // set timeout to zero. when packet is decoded, must not wait. return GetPacket(new TimeSpan(), removeEvent, out remoteEndPoint); }
public void Invoke_WithExceptionAndInnerException_ThrowsInnerException( Mock<Common.IServiceLocator> serviceLocator, Mock<IRepository<Post>> repository, string title, string message, InvalidOperationException innerException) { // Given var exception = new Exception(message, innerException); serviceLocator.Setup(s => s.GetInstance<IRepository<Post>>()).Returns(repository.Object); repository.Setup(s => s.Save(It.IsAny<Post>())).Throws(exception); var sut = new NewPostCommand(); ServiceLocator.SetCurrentInstance(serviceLocator.Object); sut.Title = title; // Then Assert.Throws(innerException.GetType(), () => sut.Invoke<Post>().Any()); }
private void HandleOperationException(InvalidOperationException e, HttpWebResponse response) { Func<Stream> getResponseStream = null; Descriptor descriptor = base.ChangedEntries[base.entryIndex]; Dictionary<string, string> headers = null; HttpStatusCode internalServerError = HttpStatusCode.InternalServerError; Version parsedResponseVersion = null; if (response != null) { headers = WebUtil.WrapResponseHeaders(response); base.HandleOperationResponseHeaders(response.StatusCode, headers); if (getResponseStream == null) { getResponseStream = () => WebUtil.GetResponseStream(response, (DataServiceContext) this.Source); } e = BaseSaveResult.HandleResponse(base.RequestInfo, response.StatusCode, response.Headers["DataServiceVersion"], getResponseStream, false, out parsedResponseVersion); internalServerError = response.StatusCode; } else { headers = new Dictionary<string, string>(StringComparer.Ordinal); headers.Add("Content-Type", "text/plain"); if (e.GetType() != typeof(DataServiceClientException)) { e = new DataServiceClientException(e.Message, e); } } this.cachedResponses.Add(new CachedResponse(descriptor, headers, internalServerError, parsedResponseVersion, null, e)); base.perRequest = null; this.CheckContinueOnError(); }
public void BuildThrowsAnyExeptionNotCatched( InvalidOperationException exception, [Frozen] ICommand<BuildParameters> buildCommand, [Greedy] TfsBuilderController sut, BuildParameters parameters) { parameters.PayLoad = "dummy"; Mock.Get(buildCommand).Setup(x => x.Execute(parameters)).Throws(exception); Assert.Throws(exception.GetType(), () => sut.Build(parameters)); }
/// <summary> /// Handles InvalidOperationException generated from Open or OpenAsync calls. /// For any other type of Exception, it simply returns /// </summary> private void HandleInvalidOperationException(InvalidOperationException e, int startMilliseconds, int endMilliseconds, bool async) { int elapsedMilliseconds = unchecked(endMilliseconds - startMilliseconds); // unchecked to handle overflow of Environment.TickCount // Since InvalidOperationExceptions due to timeout can be caused by issues // (e.g. network hiccup, server unavailable, etc) we need a heuristic to guess whether or not this exception // should have happened or not. bool wasTimeoutFromPool = (e.GetType() == typeof(InvalidOperationException)) && (e.Message.StartsWith("Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool")); bool wasTooEarly = (elapsedMilliseconds < ((DbConnection.ConnectionTimeout - 5) * 1000)); if (wasTimeoutFromPool && wasTooEarly) { if (async) Interlocked.Increment(ref s_fastTimeoutCountOpenAsync); else Interlocked.Increment(ref s_fastTimeoutCountOpen); } }