public void ClientRetriesConnectionInStreamingModeWithNonFatalError() { var failThenSucceedHandler = Handlers.Sequential(Error503Response, ValidStreamingResponse); using (var streamServer = HttpServer.Start(failThenSucceedHandler)) { var config = BasicConfig() .DataSource(Components.StreamingDataSource()) .ServiceEndpoints(Components.ServiceEndpoints().Streaming(streamServer.Uri)) .StartWaitTime(TimeSpan.FromSeconds(5)) .Build(); using (var client = new LdClient(config)) { Assert.True(client.Initialized); Assert.Equal(DataSourceState.Valid, client.DataSourceStatusProvider.Status.State); var value = client.BoolVariation(AlwaysTrueFlag.Key, BasicUser, false); Assert.True(value); var request1 = streamServer.Recorder.RequireRequest(); var request2 = streamServer.Recorder.RequireRequest(); Assert.Equal(BasicSdkKey, request1.Headers.Get("Authorization")); Assert.Equal(BasicSdkKey, request2.Headers.Get("Authorization")); Assert.NotEmpty(LogCapture.GetMessages().Where( m => m.Level == Logging.LogLevel.Warn && m.Text.Contains("error 503") && m.Text.Contains("will retry"))); Assert.Empty(LogCapture.GetMessages().Where(m => m.Level == Logging.LogLevel.Error)); } } }
public static void LogMessageRegex(LogCapture logCapture, bool shouldHave, LogLevel level, string pattern) { if (logCapture.HasMessageWithRegex(level, pattern) != shouldHave) { ThrowLogMatchException(logCapture, shouldHave, level, pattern, true); } }
public static void LogMessageText(LogCapture logCapture, bool shouldHave, LogLevel level, string text) { if (logCapture.HasMessageWithText(level, text) != shouldHave) { ThrowLogMatchException(logCapture, shouldHave, level, text, true); } }
/// <summary> /// Initializes a new instance of the <see cref="TestExecutionContext"/> class. /// </summary> /// <param name="other">An existing instance of TestExecutionContext.</param> public TestExecutionContext(TestExecutionContext other) { this.prior = other; this.CurrentTest = other.CurrentTest; this.CurrentResult = other.CurrentResult; this.TestObject = other.TestObject; this.WorkDirectory = other.WorkDirectory; this.listener = other.listener; this.StopOnError = other.StopOnError; this.TestCaseTimeout = other.TestCaseTimeout; #if !NETCF this.currentCulture = CultureInfo.CurrentCulture; this.currentUICulture = CultureInfo.CurrentUICulture; #endif #if !NETCF && !SILVERLIGHT this.outWriter = other.outWriter; this.errorWriter = other.errorWriter; this.traceWriter = other.traceWriter; this.tracing = other.tracing; this.currentDirectory = Environment.CurrentDirectory; this.currentPrincipal = Thread.CurrentPrincipal; this.logCapture = other.logCapture; #endif #if !NUNITLITE this.Dispatcher = other.Dispatcher; this.ParallelScope = other.ParallelScope; #endif }
protected BaseTest(ILogAdapter extraLogging) { LogCapture = Logs.Capture(); TestLogging = Logs.ToMultiple(extraLogging, LogCapture); TestLogger = TestLogging.Logger(""); BasicContext = new LdClientContext(new BasicConfiguration(Configuration.Default(BasicSdkKey), TestLogger), Configuration.Default("")); BasicTaskExecutor = new TaskExecutor("test-sender", TestLogger); // The following line prevents intermittent test failures that happen only in .NET // Framework, where background tasks (including calls to Task.Delay) are very excessively // slow to start-- on the order of many seconds. The issue appears to be a long-standing // one that is described here, where the very low default setting of ThreadPool.SetMinThreads // causes new worker tasks to be severely throttled: // http://joeduffyblog.com/2006/07/08/clr-thread-pool-injection-stuttering-problems/ // // We've seen experimentally that this setting defaults to 2 when running the tests in .NET // Framework, versus at least 12 when running them in .NET Core. // // It is theoretically possible for something similar to happen in a real application, but // since that would affect all tasks in the application, we assume that developers would // need to tune this parameter in any case, not only because of our SDK. ThreadPool.SetMinThreads(100, 100); }
public void ClientFailsToStartInStreamingModeWith401Error() { using (var streamServer = HttpServer.Start(Error401Response)) { var config = BasicConfig() .DataSource(Components.StreamingDataSource()) .ServiceEndpoints(Components.ServiceEndpoints().Streaming(streamServer.Uri)) .StartWaitTime(TimeSpan.FromSeconds(5)) .Build(); using (var client = new LdClient(config)) { Assert.False(client.Initialized); Assert.Equal(DataSourceState.Off, client.DataSourceStatusProvider.Status.State); var value = client.BoolVariation(AlwaysTrueFlag.Key, BasicUser, false); Assert.False(value); var request = streamServer.Recorder.RequireRequest(); Assert.Equal(BasicSdkKey, request.Headers.Get("Authorization")); Assert.NotEmpty(LogCapture.GetMessages().Where( m => m.Level == Logging.LogLevel.Error && m.Text.Contains("error 401") && m.Text.Contains("giving up permanently"))); } } }
public static void Enable(bool captureLogs = true) { if (captureLogs) { LogCapture.Initialize(); } VerifierSettings.ModifySerialization(settings => { settings.IgnoreMember <TestableInvokeHandlerContext>(x => x.MessageHeaders); settings.IgnoreMember <TestableInvokeHandlerContext>(x => x.Headers); settings.IgnoreMember <TestableInvokeHandlerContext>(x => x.MessageId); settings.IgnoreMember <TestableInvokeHandlerContext>(x => x.MessageHandler); settings.IgnoreMember <TestableInvokeHandlerContext>(x => x.MessageBeingHandled); settings.IgnoreMember <TestableInvokeHandlerContext>(x => x.MessageMetadata); settings.IgnoreMember <IMessageProcessingContext>(x => x.ReplyToAddress); settings.IgnoreMember <TestableEndpointInstance>(x => x.EndpointStopped); settings.IgnoreMember <TestableOutgoingLogicalMessageContext>(x => x.RoutingStrategies); settings.IgnoreMember <TestableOutgoingPhysicalMessageContext>(x => x.RoutingStrategies); settings.IgnoreMember <TestableRoutingContext>(x => x.RoutingStrategies); settings.IgnoreInstance <ContextBag>(x => !ContextBagHelper.HasContent(x)); settings.IgnoreMembersWithType <IBuilder>(); settings.AddExtraSettings(serializerSettings => { var converters = serializerSettings.Converters; converters.Add(new ContextBagConverter()); converters.Add(new SendOptionsConverter()); converters.Add(new ExtendableOptionsConverter()); converters.Add(new UnsubscriptionConverter()); converters.Add(new TimeoutMessageConverter()); converters.Add(new MessageToHandlerMapConverter()); converters.Add(new SubscriptionConverter()); converters.Add(new OutgoingMessageConverter()); }); }); }
private static void ThrowLogMatchException(LogCapture logCapture, bool shouldHave, LogLevel level, string text, bool isRegex) => throw new AssertActualExpectedException(shouldHave, !shouldHave, string.Format("Expected log {0} the {1} \"{2}\" at level {3}\n\nActual log output follows:\n{4}", shouldHave ? "to have" : "not to have", isRegex ? "pattern" : "exact message", text, level, logCapture.ToString()));
public TaskExecutorTest(ITestOutputHelper testOutput) { logCapture = Logs.Capture(); testLogger = Logs.ToMultiple( logCapture, Logs.ToMethod(testOutput.WriteLine) ).Logger(""); executor = new TaskExecutor(MyEventSender, testLogger); }
public void VerifyLogMessage(LogCapture logCapture) { var level = Recoverable ? LogLevel.Warn : LogLevel.Error; var message = (IOException is null) ? "HTTP error " + StatusCode + ".*" + (Recoverable ? "will retry" : "giving up") : IOException.Message; AssertHelpers.LogMessageRegex(logCapture, true, level, message); }
public void ClientStartupMessage() { var config = BasicConfig().Build(); using (var client = new LdClient(config)) { AssertLogMessage(true, LogLevel.Info, "Starting LaunchDarkly client " + AssemblyVersions.GetAssemblyVersionStringForType(typeof(LdClient))); Assert.All(LogCapture.GetMessages(), m => m.LoggerName.StartsWith(LogNames.DefaultBase)); } }
static LibLogTests() { var moduleWeaver = new ModuleWeaver(); assembly = moduleWeaver.ExecuteTestRun( assemblyPath: "AssemblyToProcess.dll", ignoreCodes: new[] { "0x80131869", "0x80131252", "0x80131B2C" }).Assembly; logProvider = new LogCapture(); LogProvider.SetCurrentLogProvider(logProvider); }
public void CanCustomizeBaseLoggerName() { var customLoggerName = "abcdef"; var config = BasicConfig() .Logging(Components.Logging(TestLogging).BaseLoggerName(customLoggerName)) .Build(); using (var client = new LdClient(config)) { Assert.All(LogCapture.GetMessages(), m => m.LoggerName.StartsWith(customLoggerName)); } }
public LibLogTests() { AppDomainAssemblyFinder.Attach(); beforeAssemblyPath = Path.GetFullPath(Path.Combine(TestContext.CurrentContext.TestDirectory, @"..\..\..\LibLogAssemblyToProcess\bin\Debug\LibLogAssemblyToProcess.dll")); #if (!DEBUG) beforeAssemblyPath = beforeAssemblyPath.Replace("Debug", "Release"); #endif afterAssemblyPath = WeaverHelper.Weave(beforeAssemblyPath); assembly = Assembly.LoadFile(afterAssemblyPath); logProvider = new LogCapture(); LogProvider.SetCurrentLogProvider(logProvider); }
/// <summary> /// Default constructor - does not use the Xunit test output buffer. /// </summary> public BaseTest() { _logCapture = Logs.Capture(); _testLogging = _logCapture; _testLogger = _testLogging.Logger(""); // The following line prevents intermittent test failures that can happen due to the low // default setting of ThreadPool.SetMinThreads causing new worker tasks to be severely // throttled: http://joeduffyblog.com/2006/07/08/clr-thread-pool-injection-stuttering-problems/ // This makes it difficult to test things such as timeouts. We believe it not to be a real // issue in non-test scenarios, since the tests are starting and stopping an unusually large // number of async tasks in a way that regular use of EventSource would not do. ThreadPool.SetMinThreads(100, 100); }
public LibLogTests() { AppDomainAssemblyFinder.Attach(); beforeAssemblyPath = Path.GetFullPath(@"..\..\..\LibLogAssemblyToProcess\bin\Debug\LibLogAssemblyToProcess.dll"); #if (!DEBUG) beforeAssemblyPath = beforeAssemblyPath.Replace("Debug", "Release"); #endif afterAssemblyPath = WeaverHelper.Weave(beforeAssemblyPath); assembly = Assembly.LoadFile(afterAssemblyPath); logProvider = new LogCapture(); LogProvider.SetCurrentLogProvider(logProvider); }
public void CustomPollingDataSourceBaseUri() { using (var client = new LdClient( BasicConfig() .DataSource(Components.PollingDataSource()) .Http(Components.HttpConfiguration().MessageHandler(_stubHandler)) .ServiceEndpoints(Components.ServiceEndpoints().Polling(CustomUri)) .Build())) { var req = _stubHandler.Requests.ExpectValue(); Assert.Equal(CustomUri, BaseUriOf(req.RequestUri)); Assert.False(LogCapture.HasMessageWithRegex(LogLevel.Error, "You have set custom ServiceEndpoints without specifying")); } }
public void OutageTimeoutLogging() { var outageTimeout = TimeSpan.FromMilliseconds(100); var updates = new DataSourceUpdatesImpl( store, dataStoreStatusProvider, BasicTaskExecutor, TestLogger, outageTimeout ); // simulate an outage updates.UpdateStatus(DataSourceState.Interrupted, DataSourceStatus.ErrorInfo.FromHttpError(500)); // but recover from it immediately updates.UpdateStatus(DataSourceState.Valid, null); // wait until the timeout would have elapsed - no special message should be logged Thread.Sleep(outageTimeout.Add(TimeSpan.FromMilliseconds(50))); // simulate another outage updates.UpdateStatus(DataSourceState.Interrupted, DataSourceStatus.ErrorInfo.FromHttpError(501)); updates.UpdateStatus(DataSourceState.Interrupted, DataSourceStatus.ErrorInfo.FromHttpError(502)); updates.UpdateStatus(DataSourceState.Interrupted, DataSourceStatus.ErrorInfo.FromException(new IOException("x"))); updates.UpdateStatus(DataSourceState.Interrupted, DataSourceStatus.ErrorInfo.FromHttpError(501)); Thread.Sleep(outageTimeout); AssertEventually(TimeSpan.FromSeconds(1), TimeSpan.FromMilliseconds(50), () => { var messages = LogCapture.GetMessages().Where(m => m.Level == LogLevel.Error).ToList(); if (messages.Count == 1) { var m = messages[0]; if (m.LoggerName == ".DataSource" && m.Text.Contains("NETWORK_ERROR (1 time)") && m.Text.Contains("ERROR_RESPONSE(501) (2 times)") && m.Text.Contains("ERROR_RESPONSE(502) (1 time)")) { return(true); } } return(false); } ); }
public void ClientStartsInStreamingMode() { using (var streamServer = HttpServer.Start(ValidStreamingResponse)) { var config = BasicConfig() .DataSource(Components.StreamingDataSource()) .ServiceEndpoints(Components.ServiceEndpoints().Streaming(streamServer.Uri)) .StartWaitTime(TimeSpan.FromSeconds(5)) .Build(); using (var client = new LdClient(config)) { VerifyClientStartedAndHasExpectedData(client, streamServer); Assert.Empty(LogCapture.GetMessages().Where(m => m.Level == Logging.LogLevel.Warn)); Assert.Empty(LogCapture.GetMessages().Where(m => m.Level == Logging.LogLevel.Error)); } } }
/// <summary> /// Initializes a new instance of the <see cref="TestExecutionContext"/> class. /// </summary> public TestExecutionContext() { this.prior = null; this.TestCaseTimeout = 0; #if !NETCF this.currentCulture = CultureInfo.CurrentCulture; this.currentUICulture = CultureInfo.CurrentUICulture; #endif #if !NETCF && !SILVERLIGHT this.outWriter = Console.Out; this.errorWriter = Console.Error; this.traceWriter = null; this.tracing = false; this.currentDirectory = Environment.CurrentDirectory; this.currentPrincipal = Thread.CurrentPrincipal; this.logCapture = new Log4NetCapture(); #endif }
public void ClientStartsInPollingMode() { using (var pollServer = HttpServer.Start(ValidPollingResponse)) { var config = BasicConfig() .DataSource(Components.PollingDataSource()) .ServiceEndpoints(Components.ServiceEndpoints().Polling(pollServer.Uri)) .StartWaitTime(TimeSpan.FromSeconds(5)) .Build(); using (var client = new LdClient(config)) { VerifyClientStartedAndHasExpectedData(client, pollServer); Assert.NotEmpty(LogCapture.GetMessages().Where( m => m.Level == Logging.LogLevel.Warn && m.Text.Contains("You should only disable the streaming API if instructed to do so"))); Assert.Empty(LogCapture.GetMessages().Where(m => m.Level == Logging.LogLevel.Error)); } } }
internal static void VerifyCapturedOutput(LogLevel outputLevel, LogLevel enableLevel, string logName, LogCapture capture) { var messages = capture.GetMessages(); var strings = capture.GetMessageStrings(); if (enableLevel > outputLevel) { Assert.Empty(messages); Assert.Empty(strings); } else { var expectedMessages = new List <LogCapture.Message> { new LogCapture.Message(logName, outputLevel, SimpleMessage), new LogCapture.Message(logName, outputLevel, MessageFormat1Result), new LogCapture.Message(logName, outputLevel, MessageFormat2Result), new LogCapture.Message(logName, outputLevel, MessageFormat3Result) }; var prefix = string.IsNullOrEmpty(logName) ? outputLevel.Uppercase() + ": " : "[" + logName + "] " + outputLevel.Uppercase() + ": "; var expectedStrings = new List <string> { prefix + SimpleMessage, prefix + MessageFormat1Result, prefix + MessageFormat2Result, prefix + MessageFormat3Result }; Assert.Equal(expectedMessages, messages); Assert.Equal(expectedStrings, strings); } }
public void Warn(string message) { LogCapture.Add(new LogMessage(LogLevel.Warn, message)); }
public void Warn(string message, Exception exception) { LogCapture.Add(new LogMessage(LogLevel.Warn, message, exception)); }
public void Error(string message) { LogCapture.Add(new LogMessage(LogLevel.Error, message)); }
public void Error(string message, Exception exception) { LogCapture.Add(new LogMessage(LogLevel.Error, message, exception)); }
public void ErrorFormat(string format, params object[] args) { LogCapture.Add(new LogMessage(LogLevel.Error, format, args)); }
public void Fatal(string message) { LogCapture.Add(new LogMessage(LogLevel.Fatal, message)); }
public void Fatal(string message, Exception exception) { LogCapture.Add(new LogMessage(LogLevel.Fatal, message, exception)); }
public void FatalFormat(string format, params object[] args) { LogCapture.Add(new LogMessage(LogLevel.Fatal, format, args)); }
public void Info(string message, Exception exception) { LogCapture.Add(new LogMessage(LogLevel.Info, message, exception)); }