public async Task Should_stop_if_deserialization_failed() { sut.ActivateAsync(consumerName, store).Wait(); sut.Activate(eventConsumer); var ex = new InvalidOperationException(); A.CallTo(() => formatter.Parse(eventData, true)) .Throws(ex); var @event = new StoredEvent(Guid.NewGuid().ToString(), 123, eventData); await OnEventAsync(eventSubscription, @event); sut.Dispose(); state.ShouldBeEquivalentTo(new EventConsumerState { IsStopped = true, Position = initialPosition, Error = ex.ToString() }); A.CallTo(() => eventConsumer.On(envelope)) .MustNotHaveHappened(); A.CallTo(() => persistence.WriteSnapshotAsync(A <EventConsumerState> .Ignored)) .MustHaveHappened(Repeated.Exactly.Once); A.CallTo(() => eventSubscription.StopAsync()) .MustHaveHappened(Repeated.Exactly.Once); }
public async Task Should_stop_if_deserialization_failed() { var ex = new InvalidOperationException(); A.CallTo(() => formatter.ParseIfKnown(A <StoredEvent> .That.Matches(x => x.Data == eventData))) .Throws(ex); await sut.ActivateAsync(consumerName); await sut.ActivateAsync(); await OnEventAsync(eventSubscription, storedEvent); await sut.CompleteAsync(); AssetGrainState(isStopped: true, position: initialPosition, error: ex.ToString()); A.CallTo(() => eventConsumer.On(envelope)) .MustNotHaveHappened(); A.CallTo(() => grainState.WriteAsync()) .MustHaveHappenedOnceExactly(); A.CallTo(() => eventSubscription.Unsubscribe()) .MustHaveHappenedOnceExactly(); }
public async Task Should_stop_if_handling_failed() { var ex = new InvalidOperationException(); A.CallTo(() => eventConsumer.On(envelope)) .Throws(ex); var @event = new StoredEvent("Stream", Guid.NewGuid().ToString(), 123, eventData); await sut.OnActivateAsync(consumerName); await sut.ActivateAsync(); await OnEventAsync(eventSubscription, @event); state.Should().BeEquivalentTo(new EventConsumerState { IsStopped = true, Position = initialPosition, Error = ex.ToString() }); A.CallTo(() => eventConsumer.On(envelope)) .MustHaveHappened(); A.CallTo(() => persistence.WriteSnapshotAsync(A <EventConsumerState> .Ignored)) .MustHaveHappened(Repeated.Exactly.Once); A.CallTo(() => eventSubscription.StopAsync()) .MustHaveHappened(Repeated.Exactly.Once); }
public async Task Should_stop_if_resetting_failed() { var ex = new InvalidOperationException(); A.CallTo(() => eventConsumer.ClearAsync()) .Throws(ex); await sut.ActivateAsync(consumerName); await sut.ActivateAsync(); await sut.ResetAsync(); await sut.CompleteAsync(); AssetGrainState(new EventConsumerState { IsStopped = true, Position = initialPosition, Error = ex.ToString() }); A.CallTo(() => grainState.WriteAsync()) .MustHaveHappenedOnceExactly(); A.CallTo(() => eventSubscription.Unsubscribe()) .MustHaveHappenedOnceExactly(); }
public async Task Should_stop_if_handling_failed() { sut.Activate(eventConsumer); var ex = new InvalidOperationException(); A.CallTo(() => eventConsumer.On(envelope)) .Throws(ex); var @event = new StoredEvent(Guid.NewGuid().ToString(), 123, eventData); await OnEventAsync(eventSubscription, @event); sut.Dispose(); state.ShouldBeEquivalentTo(new EventConsumerState { IsStopped = true, Position = initialPosition, Error = ex.ToString() }); A.CallTo(() => eventConsumer.On(envelope)) .MustHaveHappened(); A.CallTo(() => stateHolder.WriteAsync()) .MustHaveHappened(Repeated.Exactly.Once); A.CallTo(() => eventSubscription.StopAsync()) .MustHaveHappened(Repeated.Exactly.Once); }
public void GettingExceptionResponseProducesEvents() { var exception = new InvalidOperationException(); MockTransport mockTransport = CreateMockTransport(_ => { throw exception; }); var pipeline = new HttpPipeline(mockTransport, new[] { new LoggingPolicy(logContent: true, int.MaxValue, _sanitizer, "Test-SDK") }); string requestId = null; Assert.ThrowsAsync <InvalidOperationException>(async() => await SendRequestAsync(pipeline, request => { request.Method = RequestMethod.Get; request.Uri.Reset(new Uri("http://example.com")); request.Headers.Add("User-Agent", "agent"); requestId = request.ClientRequestId; })); EventWrittenEventArgs e = _listener.SingleEventById(ExceptionResponseEvent); Assert.AreEqual(EventLevel.Informational, e.Level); Assert.AreEqual(requestId, e.GetProperty <string>("requestId")); Assert.AreEqual(exception.ToString().Split(Environment.NewLine.ToCharArray())[0], e.GetProperty <string>("exception").Split(Environment.NewLine.ToCharArray())[0]); }
public async Task Should_stop_if_handling_failed() { var ex = new InvalidOperationException(); A.CallTo(() => eventConsumer.On(envelope)) .Throws(ex); var @event = new StoredEvent("Stream", Guid.NewGuid().ToString(), 123, eventData); await sut.ActivateAsync(consumerName); await sut.ActivateAsync(); await OnEventAsync(eventSubscription, @event); AssetGrainState(new EventConsumerState { IsStopped = true, Position = initialPosition, Error = ex.ToString() }); A.CallTo(() => eventConsumer.On(envelope)) .MustHaveHappened(); A.CallTo(() => grainState.WriteAsync()) .MustHaveHappened(1, Times.Exactly); A.CallTo(() => eventSubscription.StopAsync()) .MustHaveHappened(1, Times.Exactly); }
public void MessageWithExceptionTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${message:withException=true}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); Logger logger = LogManager.GetLogger("A"); logger.Debug("a"); AssertDebugLastMessage("debug", "a"); var ex = new InvalidOperationException("Exception message."); logger.DebugException("Foo", ex); #if !SILVERLIGHT && !NET_CF string newline = Environment.NewLine; #else string newline = "\r\n"; #endif AssertDebugLastMessage("debug", "Foo" + newline + ex.ToString()); }
public static void Peer_Certificate_Correctly_Installed() { #if FULLXUNIT_NOTSUPPORTED bool peer_Certificate_Installed = Peer_Certificate_Installed(); if (!peer_Certificate_Installed) { Console.WriteLine("---- Test SKIPPED --------------"); Console.WriteLine("Attempting to run the test in ToF, a ConditionalFact evaluated as FALSE."); Console.WriteLine("Peer_Certificate_Installed evaluated as {0}", peer_Certificate_Installed); return; } #endif // *** SETUP *** \\ InvalidOperationException exception = null; // *** EXECUTE *** \\ try { ValidateCertificate(ServiceUtilHelper.PeerCertificate, StoreName.TrustedPeople, StoreLocation.CurrentUser); } catch (InvalidOperationException e) { exception = e; } // *** VALIDATE *** \\ // Validate rather than allowing an exception to propagate // to be clear the exception was anticipated. Assert.True(exception == null, exception == null ? String.Empty : exception.ToString()); }
public void Error_During_Generation_Has_Exception_In_Description() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new InvalidOperationException("generate error"); var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); // Since translated description strings can have punctuation that differs based on locale, simply ensure the // exception message is contains in the diagnostic description. Assert.Contains(exception.ToString(), generatorDiagnostics.Single().Descriptor.Description.ToString()); }
internal static bool SetOnce(ref ISubscription subscription, ISubscription next, bool crash = true) { if (next == null) { throw new ArgumentNullException(nameof(next)); } ISubscription current = Interlocked.CompareExchange(ref subscription, next, null); if (current == null) { return(true); } next?.Cancel(); if (current != Cancelled) { var e = new InvalidOperationException("ISubscription already set!"); if (crash) { throw e; } else { System.Diagnostics.Debug.WriteLine(e.ToString()); } } return(false); }
public void LogsExceptionWhenSetupPlayedWithException() { var resolved = new object(); this._uriModuleItemResolver.Resolve(null, null).ReturnsForAnyArgs(resolved); Action <ResolveSetupPlayer> playerSender = null; this._resolveSetupFactory .Create <object>(Arg.Do <ResolveSetupArgs>(a => playerSender = a.PlayerSender)) .ReturnsForAnyArgs(Substitute.For <IShellResolveSetup <object> >()); var uri = new Uri("tst://tab/module/item"); var resolveOpen = this.CreateTestObject(uri); resolveOpen.Setup <object>(); var exception = new InvalidOperationException(resolved.GetHashCode().ToString()); playerSender((pUri, pResolved) => { throw exception; }); resolveOpen.OpenOrThrow(); this._traceListener.Received(1).TraceEvent( Arg.Any <TraceEventCache>(), Arg.Any <string>(), TraceEventType.Error, Arg.Any <int>(), exception.ToString()); }
public void Error_During_Generation_Has_Exception_In_Description() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new InvalidOperationException("generate error"); var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception); GeneratorDriver driver = new CSharpGeneratorDriver(parseOptions, ImmutableArray.Create <ISourceGenerator>(generator), CompilerAnalyzerConfigOptionsProvider.Empty, ImmutableArray <AdditionalText> .Empty); driver.RunFullGeneration(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); Assert.EndsWith(exception.ToString() + "'.", generatorDiagnostics.Single().Descriptor.Description.ToString()); }
public async Task Should_stop_if_handling_failed() { var ex = new InvalidOperationException(); A.CallTo(() => eventConsumer.On(envelope)) .Throws(ex); await sut.ActivateAsync(consumerName); await sut.ActivateAsync(); await OnEventAsync(eventSubscription, storedEvent); await sut.CompleteAsync(); AssetGrainState(isStopped: true, position: initialPosition, error: ex.ToString()); A.CallTo(() => eventConsumer.On(envelope)) .MustHaveHappened(); A.CallTo(() => grainState.WriteAsync()) .MustHaveHappenedOnceExactly(); A.CallTo(() => eventSubscription.Unsubscribe()) .MustHaveHappenedOnceExactly(); }
public void Error_During_Generation_Has_Exception_In_Description() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new InvalidOperationException("generate error"); var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); Assert.EndsWith(exception.ToString() + "'.", generatorDiagnostics.Single().Descriptor.Description.ToString()); }
static void ValidateException(InvalidOperationException ex, Type classType, Type invalidMemberType, string invalidMemberName) { string exAsStr = ex.ToString(); Assert.Contains(invalidMemberType.ToString(), exAsStr); Assert.Contains(invalidMemberName, exAsStr); Assert.Contains(classType.ToString(), exAsStr); }
private static void CauseInvalidOperationException(Action action) { InvalidOperationException ex = Assert.Throws <InvalidOperationException>(action); string exAsStr = ex.ToString(); Assert.Contains("JsonSerializerOptions", exAsStr); Assert.Contains("JsonSerializerContext", exAsStr); }
public void WhenExceptionMessageHasOnlyException_ThenMessageContainsExceptionMessageAndStacktrace() { var exception = new InvalidOperationException("Foo"); var traceEvent = new ExceptionTraceEvent(TraceEventType.Error, 0, exception); Assert.Contains("Foo", traceEvent.MessageOrFormat); Assert.Contains(exception.ToString(), traceEvent.MessageOrFormat); }
public void PropertyWithBindingAccessNone_ValueNotReadableOrWritable() { const string propertyName = "Foo"; var controller = new PropertyAccessController(BindingState.Bound); var accessor = new PropertyAccessor <int>(controller, propertyName, BindingAccess.None); InvalidOperationException e = Assert.Throws <InvalidOperationException>(() => accessor.Value = 5); this.testOutputHelper.WriteLine(e.ToString()); Assert.Contains(propertyName, e.Message); e = Assert.Throws <InvalidOperationException>(() => { int x = accessor.Value; }); this.testOutputHelper.WriteLine(e.ToString()); Assert.Contains(propertyName, e.Message); Assert.False(accessor.HasBeenModified); }
public virtual async Task NonPublicProperty_WithJsonInclude_Invalid(Type type) { InvalidOperationException ex = await Assert.ThrowsAsync <InvalidOperationException>(async() => await Serializer.DeserializeWrapper("{}", type)); string exAsStr = ex.ToString(); Assert.Contains("MyString", exAsStr); Assert.Contains(type.ToString(), exAsStr); Assert.Contains("JsonIncludeAttribute", exAsStr); ex = await Assert.ThrowsAsync <InvalidOperationException>(async() => await Serializer.SerializeWrapper(Activator.CreateInstance(type), type)); exAsStr = ex.ToString(); Assert.Contains("MyString", exAsStr); Assert.Contains(type.ToString(), exAsStr); Assert.Contains("JsonIncludeAttribute", exAsStr); }
// the log was removed from the observer //[Fact] public void SignalObserverLogsSignalOnError() { var exception = new InvalidOperationException("This should not have occurred!"); this.observer.OnError(exception); this.AssertLog(this.FullNodeLogger, LogLevel.Error, exception.ToString()); }
public void AddWithAnInvalidLocation() { LocationModel model = new LocationModel { Location = "Invalid.Location" }; InvalidOperationException exception = Assert.Throws <InvalidOperationException>(() => Repository.Add(model)); Assert.That(exception.ToString(), Is.StringContaining("Location 'Invalid.Location' is not valid.")); }
public async Task ExtensionDataProperty_CannotBindTo_CtorParam() { InvalidOperationException ex = await Assert.ThrowsAsync <InvalidOperationException>(() => JsonSerializerWrapperForString.DeserializeWrapper <Class_ExtData_CtorParam>("{}")); string exStr = ex.ToString(); // System.InvalidOperationException: 'The extension data property 'ExtensionData' on type 'System.Text.Json.Serialization.Tests.ConstructorTests+Class_ExtData_CtorParam' cannot bind with a parameter in the deserialization constructor.' Assert.Contains("ExtensionData", exStr); Assert.Contains("System.Text.Json.Serialization.Tests.ConstructorTests+Class_ExtData_CtorParam", exStr); }
public void ExtensionDataProperty_CannotBindTo_CtorParam() { InvalidOperationException ex = Assert.Throws <InvalidOperationException>(() => Serializer.Deserialize <Class_ExtData_CtorParam>("{}")); string exStr = ex.ToString(); Assert.Contains("System.Collections.Generic.Dictionary`2[System.String,System.Text.Json.JsonElement] ExtensionData", exStr); Assert.Contains("System.Text.Json.Serialization.Tests.ConstructorTests+Class_ExtData_CtorParam", exStr); Assert.Contains("(System.Collections.Generic.Dictionary`2[System.String,System.Text.Json.JsonElement])", exStr); }
public void SerializeOpenGeneric_NullableOfT() { Type openNullableType = typeof(Nullable <>); object obj = Activator.CreateInstance(openNullableType.MakeGenericType(typeof(int))); InvalidOperationException ex = Assert.Throws <InvalidOperationException>(() => Serializer.Serialize(obj, openNullableType)); Assert.Contains(openNullableType.ToString(), ex.ToString()); }
public void GetTypeInfoCalledDuringPolymorphicSerialization() { CustomContext context = new(new JsonSerializerOptions()); // Empty array is fine since we don't need metadata for children. Assert.Equal("[]", JsonSerializer.Serialize(Array.Empty <object>(), context.ObjectArray)); Assert.Equal("[]", JsonSerializer.Serialize(Array.Empty <object>(), typeof(object[]), context)); // GetTypeInfo method called to get metadata for element run-time type. object[] objArr = new object[] { new MyStruct() }; InvalidOperationException ex = Assert.Throws <InvalidOperationException>(() => JsonSerializer.Serialize(objArr, context.ObjectArray)); Assert.Contains(ExceptionMessageFromCustomContext, ex.ToString()); ex = Assert.Throws <InvalidOperationException>(() => JsonSerializer.Serialize(objArr, typeof(object[]), context)); Assert.Contains(ExceptionMessageFromCustomContext, ex.ToString()); }
public void WhenExceptionMessageHasMessageFormat_ThenMessageContainsFormattedMessageAndExceptionMessageAndStacktrace() { var exception = new InvalidOperationException("Foo"); var traceEvent = new ExceptionTraceEvent(TraceEventType.Error, 0, exception, "Hello {0}", "World"); Assert.Contains("Hello World", traceEvent.MessageOrFormat); Assert.Contains("Foo", traceEvent.MessageOrFormat); Assert.Contains(exception.ToString(), traceEvent.MessageOrFormat); }
public void NonJsonServicesExceptionGetsInternalErrorCode() { var ex = new InvalidOperationException(); var err = new ExceptionTranslator().Translate(ex); Assert.NotNull(err); Assert.AreEqual(InternalErrorException.ErrorCode, err.Code); Assert.AreEqual(ex.Message, err.Message); Assert.AreEqual(ex.ToString(), err.Data); }
public void WhenAddingMessageAndThrowsShouldLogError() { var message = new Message(new Uri("http://www.google.com"), string.Empty); var exception = new InvalidOperationException("Error"); this.PersistentStore.Setup(s => s.Add(message)).Throws(exception); this.StoreService.Put(message); this.PersistentStore.Verify(r => r.Add(message), Times.AtLeast(1)); this.Logger.Verify(l => l.Err("StoreService.ThreadStart. Error {0}", exception.ToString()), Times.AtLeast(1)); }
public void ReplaceReferenceIncorrectType() { EqualSpecification equal = new EqualSpecification( "k1", SpecificationValue.Ref("{p1}")); ValueReferenceVisitor visitor = new ValueReferenceVisitor( new Dictionary <string, object> { { "{p1}", SpecificationValue.Ref("{p2}") }, { "{p2}", TimeSpan.FromDays(1) }, }); InvalidOperationException exc = Assert.Throws <InvalidOperationException>(() => visitor.Visit(equal)); Assert.Contains("Unable to resolve", exc.Message); Assert.Contains("{p1}", exc.ToString()); Assert.Contains("{p2}", exc.ToString()); }
public void Trace_Verbose_Writes_Correct_Message_To_TraceListeners_With_All_Fields_Set(TraceLevel level) { // Arrange SystemDiagnosticsTraceWriter writer = CreateTraceWriter(); writer.MinimumLevel = level; writer.IsVerbose = true; HttpRequestMessage request = new HttpRequestMessage { RequestUri = new Uri("http://localhost"), Method = HttpMethod.Get }; InvalidOperationException exception = new InvalidOperationException("TestException"); // Act writer.Trace(request, "TestCategory", level, (tr) => { tr.Message = "TestMessage"; tr.Operation = "TestOperation"; tr.Operator = "TestOperator"; tr.Status = HttpStatusCode.Accepted; tr.Exception = exception; }); // Assert string expected = String.Format("Level={0}, Kind=Trace, Category='TestCategory', Id={1}, Message='TestMessage', Operation=TestOperator.TestOperation, Status=202 (Accepted), Exception={2}", level.ToString(), request.GetCorrelationId().ToString(), exception.ToString()); string actual = ((TestTraceListener)writer.TraceSource.Listeners[0]).Messages[0].Trim(); string timePrefix = "] "; actual = actual.Substring(actual.IndexOf(timePrefix) + timePrefix.Length); Assert.Equal(expected, actual); }