public void Test_EventSourceCreatedEvents_AfterListener() { TestUtilities.CheckNoEventSourcesRunning("Start"); EventSource log = null; EventSource log2 = null; EventListenerListener el = null; try { using (var listener = new EventListenerListener()) { string esName = "EventSourceName_HopefullyUnique"; string esName2 = "EventSourceName_HopefullyUnique2"; bool esNameHit = false; bool esName2Hit = false; List <EventSource> eventSourceNotificationsReceived = new List <EventSource>(); listener.EventSourceCreated += (s, a) => { if (a.EventSource.Name.Equals(esName)) { esNameHit = true; } if (a.EventSource.Name.Equals(esName2)) { esName2Hit = true; } }; log = new EventSource(esName); log2 = new EventSource(esName2); Thread.Sleep(1000); Assert.True(esNameHit); Assert.True(esName2Hit); } } finally { if (log != null) { log.Dispose(); } if (log2 != null) { log2.Dispose(); } if (el != null) { el.Dispose(); } } TestUtilities.CheckNoEventSourcesRunning("Stop"); }
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))] // ActiveIssue: https://github.com/dotnet/corefx/issues/29754 public void Test_BadEventSource_MismatchedIds() { TestUtilities.CheckNoEventSourcesRunning("Start"); var onStartups = new bool[] { false, true }; var listenerGenerators = new List <Func <Listener> >(); listenerGenerators.Add(() => new EventListenerListener()); var settings = new EventSourceSettings[] { EventSourceSettings.Default, EventSourceSettings.EtwSelfDescribingEventFormat }; // For every interesting combination, run the test and see that we get a nice failure message. foreach (bool onStartup in onStartups) { foreach (Func <Listener> listenerGenerator in listenerGenerators) { foreach (EventSourceSettings setting in settings) { Test_Bad_EventSource_Startup(onStartup, listenerGenerator(), setting); } } } TestUtilities.CheckNoEventSourcesRunning("Stop"); }
public void Test_WriteEvent_ArgsCornerCases() { TestUtilities.CheckNoEventSourcesRunning("Start"); using (var log = new EventSourceTest()) { using (var el = new LoudListener(log)) { // coverage for EventSource.SendCommand() var options = new Dictionary <string, string>() { { "arg", "val" } }; EventSource.SendCommand(log, EventCommand.SendManifest, options); log.EventWith7Strings("s0", "s1", "s2", "s3", "s4", "s5", "s6"); Assert.Equal(26, LoudListener.t_lastEvent.EventId); Assert.Equal(7, LoudListener.t_lastEvent.Payload.Count); Assert.Equal("s0", (string)LoudListener.t_lastEvent.Payload[0]); Assert.Equal("s6", (string)LoudListener.t_lastEvent.Payload[6]); log.EventWith9Strings("s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8"); Assert.Equal(27, LoudListener.t_lastEvent.EventId); Assert.Equal(9, LoudListener.t_lastEvent.Payload.Count); Assert.Equal("s0", (string)LoudListener.t_lastEvent.Payload[0]); Assert.Equal("s8", (string)LoudListener.t_lastEvent.Payload[8]); Test_WriteEvent_ArgsCornerCases_TestEtw(log); } } TestUtilities.CheckNoEventSourcesRunning("Stop"); }
public void Test_BadEventSource_MismatchedIds() { #if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864. // We expect only one session to be on when running the test but if a ETW session was left // hanging, it will confuse the EventListener tests. EtwListener.EnsureStopped(); #endif // USE_ETW TestUtilities.CheckNoEventSourcesRunning("Start"); var onStartups = new bool[] { false, true }; var listenerGenerators = new Func <Listener>[] { () => new EventListenerListener(), #if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864. () => new EtwListener() #endif // USE_ETW }; var settings = new EventSourceSettings[] { EventSourceSettings.Default, EventSourceSettings.EtwSelfDescribingEventFormat }; // For every interesting combination, run the test and see that we get a nice failure message. foreach (bool onStartup in onStartups) { foreach (Func <Listener> listenerGenerator in listenerGenerators) { foreach (EventSourceSettings setting in settings) { Test_Bad_EventSource_Startup(onStartup, listenerGenerator(), setting); } } } TestUtilities.CheckNoEventSourcesRunning("Stop"); }
public void Test_EventSource_ShutdownManifest() { TestUtilities.CheckNoEventSourcesRunning("Start"); Debug.WriteLine("Logging more than 1MB of events..."); OverflowCircularBufferTest(); Debug.WriteLine("Success..."); TestUtilities.CheckNoEventSourcesRunning("Stop"); }
public void Test_EventSource_LowTrust() { TestUtilities.CheckNoEventSourcesRunning("Start"); Console.WriteLine("Running Array.CreateInstance() in low trust..."); RunLowTrustTest(); Console.WriteLine("Success..."); TestUtilities.CheckNoEventSourcesRunning("Stop"); }
public void Test_WriteEvent_ArgsCornerCases() { TestUtilities.CheckNoEventSourcesRunning("Start"); using (var log = new EventSourceTest()) { using (var el = new LoudListener()) { // coverage for EventSource.SendCommand() var options = new Dictionary <string, string>() { { "arg", "val" } }; EventSource.SendCommand(log, EventCommand.SendManifest, options); Guid guid = Guid.NewGuid(); #if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864. log.EventWithManyTypeArgs("Hello", 0, 0, 0, 'a', 0, 0, 0, 0, (float)10.0, (double)11.0, guid); Assert.Equal(25, LoudListener.LastEvent.EventId); Assert.Equal(12, LoudListener.LastEvent.Payload.Count); Assert.Equal("Hello", (string)LoudListener.LastEvent.Payload[0]); Assert.Equal(0, (long)LoudListener.LastEvent.Payload[1]); Assert.Equal((uint)0, (uint)LoudListener.LastEvent.Payload[2]); Assert.Equal((ulong)0, (ulong)LoudListener.LastEvent.Payload[3]); Assert.Equal('a', (char)LoudListener.LastEvent.Payload[4]); Assert.Equal((byte)0, (byte)LoudListener.LastEvent.Payload[5]); Assert.Equal((sbyte)0, (sbyte)LoudListener.LastEvent.Payload[6]); Assert.Equal((short)0, (short)LoudListener.LastEvent.Payload[7]); Assert.Equal((ushort)0, (ushort)LoudListener.LastEvent.Payload[8]); Assert.Equal((float)10.0, (float)LoudListener.LastEvent.Payload[9]); Assert.Equal((double)11.0, (double)LoudListener.LastEvent.Payload[10]); Assert.Equal(guid, (Guid)LoudListener.LastEvent.Payload[11]); #endif // USE_ETW log.EventWith7Strings("s0", "s1", "s2", "s3", "s4", "s5", "s6"); Assert.Equal(26, LoudListener.LastEvent.EventId); Assert.Equal(7, LoudListener.LastEvent.Payload.Count); Assert.Equal("s0", (string)LoudListener.LastEvent.Payload[0]); Assert.Equal("s6", (string)LoudListener.LastEvent.Payload[6]); log.EventWith9Strings("s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8"); Assert.Equal(27, LoudListener.LastEvent.EventId); Assert.Equal(9, LoudListener.LastEvent.Payload.Count); Assert.Equal("s0", (string)LoudListener.LastEvent.Payload[0]); Assert.Equal("s8", (string)LoudListener.LastEvent.Payload[8]); #if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864. log.EventWithWeirdArgs(IntPtr.Zero, true, MyLongEnum.LongVal1 /*, 9999999999999999999999999999m*/); Assert.Equal(30, LoudListener.LastEvent.EventId); Assert.Equal(3 /*4*/, LoudListener.LastEvent.Payload.Count); Assert.Equal(IntPtr.Zero, (IntPtr)LoudListener.LastEvent.Payload[0]); Assert.Equal(true, (bool)LoudListener.LastEvent.Payload[1]); Assert.Equal(MyLongEnum.LongVal1, (MyLongEnum)LoudListener.LastEvent.Payload[2]); // Assert.Equal(9999999999999999999999999999m, (decimal)LoudListener.LastEvent.Payload[3]); #endif // USE_ETW } } TestUtilities.CheckNoEventSourcesRunning("Stop"); }
public void Test_WriteEvent_TransferEvents() { TestUtilities.CheckNoEventSourcesRunning("Start"); using (var log = new EventSourceTest()) { using (var el = new LoudListener()) { Guid actid = Guid.NewGuid(); log.LogTaskScheduled(actid, "Hello from a test"); Assert.Equal(17, LoudListener.LastEvent.EventId); Assert.Equal(actid, LoudListener.LastEvent.RelatedActivityId); Assert.Equal(1, LoudListener.LastEvent.Payload.Count); Assert.Equal("Hello from a test", (string)LoudListener.LastEvent.Payload[0]); actid = Guid.NewGuid(); log.LogTaskScheduledBad(actid, "Hello again"); Assert.Equal(23, LoudListener.LastEvent.EventId); Assert.Equal(actid, LoudListener.LastEvent.RelatedActivityId); Assert.Equal(1, LoudListener.LastEvent.Payload.Count); Assert.Equal("Hello again", (string)LoudListener.LastEvent.Payload[0]); actid = Guid.NewGuid(); Guid guid = Guid.NewGuid(); log.EventWithXferManyTypeArgs(actid, 0, 0, 0, 'a', 0, 0, 0, 0, (float)10.0, (double)11.0, guid); Assert.Equal(29, LoudListener.LastEvent.EventId); Assert.Equal(actid, LoudListener.LastEvent.RelatedActivityId); Assert.Equal(11, LoudListener.LastEvent.Payload.Count); Assert.Equal(0, (long)LoudListener.LastEvent.Payload[0]); Assert.Equal((uint)0, (uint)LoudListener.LastEvent.Payload[1]); Assert.Equal((ulong)0, (ulong)LoudListener.LastEvent.Payload[2]); Assert.Equal('a', (char)LoudListener.LastEvent.Payload[3]); Assert.Equal((byte)0, (byte)LoudListener.LastEvent.Payload[4]); Assert.Equal((sbyte)0, (sbyte)LoudListener.LastEvent.Payload[5]); Assert.Equal((short)0, (short)LoudListener.LastEvent.Payload[6]); Assert.Equal((ushort)0, (ushort)LoudListener.LastEvent.Payload[7]); Assert.Equal((float)10.0, (float)LoudListener.LastEvent.Payload[8]); Assert.Equal((double)11.0, (double)LoudListener.LastEvent.Payload[9]); Assert.Equal(guid, (Guid)LoudListener.LastEvent.Payload[10]); actid = Guid.NewGuid(); log.EventWithXferWeirdArgs(actid, IntPtr.Zero, true, MyLongEnum.LongVal1 /*, 9999999999999999999999999999m*/); Assert.Equal(31, LoudListener.LastEvent.EventId); Assert.Equal(actid, LoudListener.LastEvent.RelatedActivityId); Assert.Equal(3 /*4*/, LoudListener.LastEvent.Payload.Count); Assert.Equal(IntPtr.Zero, (IntPtr)LoudListener.LastEvent.Payload[0]); Assert.Equal(true, (bool)LoudListener.LastEvent.Payload[1]); Assert.Equal(MyLongEnum.LongVal1, (MyLongEnum)LoudListener.LastEvent.Payload[2]); // Assert.Equal(9999999999999999999999999999m, (decimal)LoudListener.LastEvent.Payload[3]); actid = Guid.NewGuid(); Assert.Throws <EventSourceException>(() => log.LogTransferNoOpcode(actid)); } } TestUtilities.CheckNoEventSourcesRunning("Stop"); }
public void Test_WriteEvent_ToChannel_Coverage() { TestUtilities.CheckNoEventSourcesRunning("Start"); using (var log = new SimpleEventSource()) using (var el = new LoudListener(log)) { log.WriteIntToAdmin(10); } TestUtilities.CheckNoEventSourcesRunning("Stop"); }
public void Test_EventSource_Traits_Dynamic() { TestUtilities.CheckNoEventSourcesRunning("Start"); using (var mySource = new EventSource("DynamicEventSourceWithTraits", EventSourceSettings.Default, "MyTrait", "MyTraitValue", "ETW_GROUP", "{4f50731a-89cf-4782-b3e0-dce8c90476ba}")) { // By default we are self-describing. Assert.Equal(mySource.Settings, EventSourceSettings.EtwSelfDescribingEventFormat); Assert.Equal(mySource.GetTrait("MyTrait"), "MyTraitValue"); Assert.Equal(mySource.GetTrait("ETW_GROUP"), "{4f50731a-89cf-4782-b3e0-dce8c90476ba}"); } TestUtilities.CheckNoEventSourcesRunning("Stop"); }
public void Test_EventSource_Traits_Contract() { TestUtilities.CheckNoEventSourcesRunning("Start"); using (var mySource = new ContractEventSourceWithTraits()) { // By default we are self-describing. Assert.Equal(mySource.Settings, EventSourceSettings.EtwSelfDescribingEventFormat); Assert.Equal(mySource.GetTrait("MyTrait"), "MyTraitValue"); Assert.Equal(mySource.GetTrait("ETW_GROUP"), "{4f50731a-89cf-4782-b3e0-dce8c90476ba}"); Assert.Equal(mySource.GetTrait("ETW_2"), "#01 02 03 04"); Assert.Equal(mySource.GetTrait("ETW_3"), "@Hello"); } TestUtilities.CheckNoEventSourcesRunning("Stop"); }
[PlatformSpecific(TestPlatforms.Windows)] // non-Windows EventSources don't have lifetime public void Test_EventSource_Lifetime() { TestUtilities.CheckNoEventSourcesRunning("Start"); WeakReference wrProvider = new WeakReference(null); WeakReference wrEventSource = new WeakReference(null); // Need to call separate method (ExerciseEventSource) to reference the event source // in order to avoid the debug JIT lifetimes (extended to the end of the current method) ExerciseEventSource(wrProvider, wrEventSource); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); Assert.Equal(null, wrEventSource.Target); Assert.Equal(null, wrProvider.Target); TestUtilities.CheckNoEventSourcesRunning("Stop"); }
public void Test_WriteEvent_InvalidCalls() { TestUtilities.CheckNoEventSourcesRunning("Start"); using (var log = new InvalidCallsToWriteEventEventSource()) { using (var el = new LoudListener(log)) { log.WriteTooManyArgs("Hello"); Assert.Equal(2, LoudListener.t_lastEvent.EventId); Assert.Equal(1, LoudListener.t_lastEvent.Payload.Count); // Faked count (compat) Assert.Equal("Hello", LoudListener.t_lastEvent.Payload[0]); log.WriteTooFewArgs(10, 100); Assert.Equal(1, LoudListener.t_lastEvent.EventId); Assert.Equal(1, LoudListener.t_lastEvent.Payload.Count); // Real # of args passed to WriteEvent Assert.Equal(10, LoudListener.t_lastEvent.Payload[0]); } } TestUtilities.CheckNoEventSourcesRunning("Stop"); }
public void Test_EventListenerThrows_ExceptionIsNotRethrownToCaller(bool setThrowOnEventWriteErrorsFlag) { TestUtilities.CheckNoEventSourcesRunning("Start"); using (var log = new EventSourceTest(throwOnEventWriteErrors: setThrowOnEventWriteErrorsFlag)) { using (var listener = new EventListenerListener()) { listener.EventSourceSynchronousEnable(log); var thrownException = new Exception("Oops"); string outOfBandMessage = null; listener.EventWritten += (_, e) => { if (e.EventId == 0) { outOfBandMessage = e.Message; } throw thrownException; }; try { log.Event0(); Assert.False(setThrowOnEventWriteErrorsFlag); } catch (EventSourceException ex) { Assert.True(setThrowOnEventWriteErrorsFlag); Assert.Same(thrownException, ex.InnerException); } Assert.Contains(thrownException.Message, outOfBandMessage); } } TestUtilities.CheckNoEventSourcesRunning("Stop"); }
public void Test_BadEventSource_MismatchedIds() { #if USE_ETW // We expect only one session to be on when running the test but if a ETW session was left // hanging, it will confuse the EventListener tests. if (TestUtilities.IsProcessElevated) { EtwListener.EnsureStopped(); } #endif // USE_ETW TestUtilities.CheckNoEventSourcesRunning("Start"); var onStartups = new bool[] { false, true }; var listenerGenerators = new List <Func <Listener> >(); listenerGenerators.Add(() => new EventListenerListener()); #if USE_ETW if (TestUtilities.IsProcessElevated) { listenerGenerators.Add(() => new EtwListener()); } #endif // USE_ETW var settings = new EventSourceSettings[] { EventSourceSettings.Default, EventSourceSettings.EtwSelfDescribingEventFormat }; // For every interesting combination, run the test and see that we get a nice failure message. foreach (bool onStartup in onStartups) { foreach (Func <Listener> listenerGenerator in listenerGenerators) { foreach (EventSourceSettings setting in settings) { Test_Bad_EventSource_Startup(onStartup, listenerGenerator(), setting); } } } TestUtilities.CheckNoEventSourcesRunning("Stop"); }
public void Test_EventSource_LowTrustAppDomain() { TestUtilities.CheckNoEventSourcesRunning("Start"); var scenarios = new[] { new { Zone = SecurityZone.Internet, TrustEventSource = false, GrantUnmanagedCodePermission = false }, new { Zone = SecurityZone.Internet, TrustEventSource = false, GrantUnmanagedCodePermission = true }, new { Zone = SecurityZone.Internet, TrustEventSource = true, GrantUnmanagedCodePermission = false }, new { Zone = SecurityZone.Internet, TrustEventSource = true, GrantUnmanagedCodePermission = true }, new { Zone = SecurityZone.Intranet, TrustEventSource = false, GrantUnmanagedCodePermission = false }, new { Zone = SecurityZone.Intranet, TrustEventSource = false, GrantUnmanagedCodePermission = true }, new { Zone = SecurityZone.Intranet, TrustEventSource = true, GrantUnmanagedCodePermission = false }, new { Zone = SecurityZone.Intranet, TrustEventSource = true, GrantUnmanagedCodePermission = true }, new { Zone = SecurityZone.MyComputer, TrustEventSource = true, GrantUnmanagedCodePermission = true }, }; foreach (var scenario in scenarios) { RunScenario(scenario.Zone, scenario.TrustEventSource, scenario.GrantUnmanagedCodePermission); } TestUtilities.CheckNoEventSourcesRunning("Stop"); }
public void Test_WriteEvent_ZeroKwds() { TestUtilities.CheckNoEventSourcesRunning("Start"); using (var log = new EventSourceTest()) { using (var el = new LoudListener(log)) { // match any kwds == 0 el.EnableEvents(log, 0, 0); // Fire an event without a kwd: EventWithEscapingMessage // 1. Validate that the event fires when ETW event method called unconditionally log.EventWithEscapingMessage("Hello world!", 10); Assert.NotNull(LoudListener.t_lastEvent); Assert.Equal(2, LoudListener.t_lastEvent.Payload.Count); Assert.Equal("Hello world!", (string)LoudListener.t_lastEvent.Payload[0]); Assert.Equal(10, (int)LoudListener.t_lastEvent.Payload[1]); // reset LastEvent LoudListener.t_lastEvent = null; // 2. Validate that the event fires when ETW event method call is guarded by IsEnabled if (log.IsEnabled(EventLevel.Informational, 0)) { log.EventWithEscapingMessage("Goodbye skies!", 100); } Assert.NotNull(LoudListener.t_lastEvent); Assert.Equal(2, LoudListener.t_lastEvent.Payload.Count); Assert.Equal("Goodbye skies!", (string)LoudListener.t_lastEvent.Payload[0]); Assert.Equal(100, (int)LoudListener.t_lastEvent.Payload[1]); } } TestUtilities.CheckNoEventSourcesRunning("Stop"); }
public void Test_GenerateManifest_InvalidEventSources() { TestUtilities.CheckNoEventSourcesRunning("Start"); // specify AllowEventSourceOverride - this is needed for Sdt event sources and won't make a difference for Sdt ones var strictOptions = EventManifestOptions.Strict | EventManifestOptions.AllowEventSourceOverride; Assert.NotNull(EventSource.GenerateManifest(typeof(Sdt.UnsealedEventSource), string.Empty)); Exception e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.UnsealedEventSource), string.Empty, strictOptions)); AssertExceptionStringsEqual(() => GetResourceString("EventSource_TypeMustBeSealedOrAbstract"), e); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.UnsealedEventSource), string.Empty, strictOptions)); AssertExceptionStringsEqual(() => GetResourceString("EventSource_TypeMustBeSealedOrAbstract"), e); // starting with NuGet we allow non-void returning methods as long as they have the [Event] attribute Assert.NotNull(EventSource.GenerateManifest(typeof(Sdt.EventWithReturnEventSource), string.Empty)); Assert.NotNull(EventSource.GenerateManifest(typeof(Sdt.EventWithReturnEventSource), string.Empty, strictOptions)); Assert.NotNull(EventSource.GenerateManifest(typeof(Sdt.EventWithReturnEventSource), string.Empty, EventManifestOptions.AllowEventSourceOverride)); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.NegativeEventIdEventSource), string.Empty)); AssertExceptionStringsEqual(() => GetResourceString("EventSource_NeedPositiveId"), e); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.NegativeEventIdEventSource), string.Empty, strictOptions)); AssertExceptionStringsEqual(() => GetResourceString("EventSource_NeedPositiveId"), e); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.NegativeEventIdEventSource), string.Empty, EventManifestOptions.AllowEventSourceOverride)); AssertExceptionStringsEqual(() => GetResourceString("EventSource_NeedPositiveId"), e); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.OutOfRangeKwdEventSource), string.Empty, strictOptions)); AssertExceptionStringsEqual(() => string.Join(Environment.NewLine, GetResourceString("EventSource_IllegalKeywordsValue", "Kwd1", "0x100000000000"), GetResourceString("EventSource_KeywordCollision", "Session3", "Kwd1", "0x100000000000")), e); #if FEATURE_ADVANCED_MANAGED_ETW_CHANNELS e = AssertExtensions.Throws <ArgumentException>(GetResourceString("EventSource_MaxChannelExceeded"), () => EventSource.GenerateManifest(typeof(Sdt.TooManyChannelsEventSource), string.Empty)); #endif if (PlatformDetection.IsWindows) { e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.EventWithAdminChannelNoMessageEventSource), string.Empty, strictOptions)); AssertExceptionStringsEqual(() => GetResourceString("EventSource_EventWithAdminChannelMustHaveMessage", "WriteInteger", "Admin"), e); } e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.ReservedOpcodeEventSource), string.Empty, strictOptions)); AssertExceptionStringsEqual(() => string.Join(Environment.NewLine, GetResourceString("EventSource_IllegalOpcodeValue", "Op1", 3), GetResourceString("EventSource_EventMustHaveTaskIfNonDefaultOpcode", "WriteInteger", 1)), e); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.ReservedOpcodeEventSource), string.Empty, strictOptions)); AssertExceptionStringsEqual(() => string.Join(Environment.NewLine, GetResourceString("EventSource_IllegalOpcodeValue", "Op1", 3), GetResourceString("EventSource_EventMustHaveTaskIfNonDefaultOpcode", "WriteInteger", 1)), e); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.EnumKindMismatchEventSource), string.Empty)); AssertExceptionStringsEqual(() => GetResourceString("EventSource_UndefinedKeyword", "0x1", "WriteInteger"), e); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.EnumKindMismatchEventSource), string.Empty, strictOptions)); AssertExceptionStringsEqual(() => string.Join(Environment.NewLine, GetResourceString("EventSource_EnumKindMismatch", "EventKeywords", "Opcodes"), GetResourceString("EventSource_UndefinedKeyword", "0x1", "WriteInteger")), e); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.EnumKindMismatchEventSource), string.Empty, EventManifestOptions.AllowEventSourceOverride)); AssertExceptionStringsEqual(() => GetResourceString("EventSource_UndefinedKeyword", "0x1", "WriteInteger"), e); Assert.NotNull(EventSource.GenerateManifest(typeof(Sdt.MismatchIdEventSource), string.Empty)); // These tests require the IL to be present for inspection. e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.MismatchIdEventSource), string.Empty, strictOptions)); AssertExceptionStringsEqual(() => GetResourceString("EventSource_MismatchIdToWriteEvent", "WriteInteger", 10, 1), e); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.MismatchIdEventSource), string.Empty, strictOptions)); AssertExceptionStringsEqual(() => GetResourceString("EventSource_MismatchIdToWriteEvent", "WriteInteger", 10, 1), e); Assert.NotNull(EventSource.GenerateManifest(typeof(Sdt.EventIdReusedEventSource), string.Empty)); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.EventIdReusedEventSource), string.Empty, strictOptions)); AssertExceptionStringsEqual(() => string.Join(Environment.NewLine, GetResourceString("EventSource_EventIdReused", "WriteInteger2", 1), GetResourceString("EventSource_TaskOpcodePairReused", "WriteInteger2", 1, "WriteInteger1", 1)), e); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.EventIdReusedEventSource), string.Empty, strictOptions)); AssertExceptionStringsEqual(() => string.Join(Environment.NewLine, GetResourceString("EventSource_EventIdReused", "WriteInteger2", 1), GetResourceString("EventSource_TaskOpcodePairReused", "WriteInteger2", 1, "WriteInteger1", 1)), e); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.EventNameReusedEventSource), string.Empty, strictOptions)); AssertExceptionStringsEqual(() => GetResourceString("EventSource_EventNameReused", "WriteInteger"), e); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.EventNameReusedEventSource), string.Empty, strictOptions)); AssertExceptionStringsEqual(() => GetResourceString("EventSource_EventNameReused", "WriteInteger"), e); Assert.NotNull(EventSource.GenerateManifest(typeof(Sdt.TaskOpcodePairReusedEventSource), string.Empty)); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.TaskOpcodePairReusedEventSource), string.Empty, strictOptions)); AssertExceptionStringsEqual(() => GetResourceString("EventSource_TaskOpcodePairReused", "WriteInteger2", 2, "WriteInteger1", 1), e); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.TaskOpcodePairReusedEventSource), string.Empty, strictOptions)); AssertExceptionStringsEqual(() => GetResourceString("EventSource_TaskOpcodePairReused", "WriteInteger2", 2, "WriteInteger1", 1), e); Assert.NotNull(EventSource.GenerateManifest(typeof(Sdt.EventWithOpcodeNoTaskEventSource), string.Empty)); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.EventWithOpcodeNoTaskEventSource), string.Empty, strictOptions)); AssertExceptionStringsEqual(() => GetResourceString("EventSource_EventMustHaveTaskIfNonDefaultOpcode", "WriteInteger", 1), e); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.EventWithOpcodeNoTaskEventSource), string.Empty, strictOptions)); AssertExceptionStringsEqual(() => GetResourceString("EventSource_EventMustHaveTaskIfNonDefaultOpcode", "WriteInteger", 1), e); Assert.NotNull(EventSource.GenerateManifest(typeof(Sdt.EventWithInvalidMessageEventSource), string.Empty)); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.EventWithInvalidMessageEventSource), string.Empty, strictOptions)); AssertExceptionStringsEqual(() => GetResourceString("EventSource_UnsupportedMessageProperty", "WriteString", "Message = {0,12:G}"), e); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.AbstractWithKwdTaskOpcodeEventSource), string.Empty, strictOptions)); AssertExceptionStringsEqual(() => string.Join(Environment.NewLine, GetResourceString("EventSource_AbstractMustNotDeclareKTOC", "Keywords"), GetResourceString("EventSource_AbstractMustNotDeclareKTOC", "Tasks"), GetResourceString("EventSource_AbstractMustNotDeclareKTOC", "Opcodes")), e); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.AbstractWithKwdTaskOpcodeEventSource), string.Empty, strictOptions)); AssertExceptionStringsEqual(() => string.Join(Environment.NewLine, GetResourceString("EventSource_AbstractMustNotDeclareKTOC", "Keywords"), GetResourceString("EventSource_AbstractMustNotDeclareKTOC", "Tasks"), GetResourceString("EventSource_AbstractMustNotDeclareKTOC", "Opcodes")), e); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.AbstractWithEventsEventSource), string.Empty, strictOptions)); AssertExceptionStringsEqual(() => GetResourceString("EventSource_AbstractMustNotDeclareEventMethods", "WriteInteger", 1), e); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.AbstractWithEventsEventSource), string.Empty, strictOptions)); AssertExceptionStringsEqual(() => GetResourceString("EventSource_AbstractMustNotDeclareEventMethods", "WriteInteger", 1), e); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.ImplementsInterfaceEventSource), string.Empty, strictOptions)); AssertExceptionStringsEqual(() => GetResourceString("EventSource_EventMustNotBeExplicitImplementation", "SdtEventSources.ILogging.Error", 1), e); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.ImplementsInterfaceEventSource), string.Empty, strictOptions)); AssertExceptionStringsEqual(() => GetResourceString("EventSource_EventMustNotBeExplicitImplementation", "SdtEventSources.ILogging.Error", 1), e); TestUtilities.CheckNoEventSourcesRunning("Stop"); }
private void Test_Write_Metric(Listener listener) { TestUtilities.CheckNoEventSourcesRunning("Start"); using (var logger = new MyEventSource()) { var tests = new List <SubTest>(); /*************************************************************************/ tests.Add(new SubTest("EventCounter: Log 1 event, explicit poll at end", delegate() { listener.EnableTimer(logger, 1); // Set to poll every second, but we dont actually care because the test ends before that. logger.Request(5); listener.EnableTimer(logger, 0); }, delegate(List <Event> evts) { // There will be two events (request and error) for time 0 and 2 more at 1 second and 2 more when we shut it off. Assert.Equal(4, evts.Count); ValidateSingleEventCounter(evts[0], "Request", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); ValidateSingleEventCounter(evts[1], "Error", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); ValidateSingleEventCounter(evts[2], "Request", 1, 5, 0, 5, 5); ValidateSingleEventCounter(evts[3], "Error", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); })); /*************************************************************************/ tests.Add(new SubTest("EventCounter: Log 2 events, explicit poll at end", delegate() { listener.EnableTimer(logger, 1); // Set to poll every second, but we dont actually care because the test ends before that. logger.Request(5); logger.Request(10); listener.EnableTimer(logger, 0); // poll }, delegate(List <Event> evts) { Assert.Equal(4, evts.Count); ValidateSingleEventCounter(evts[0], "Request", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); ValidateSingleEventCounter(evts[1], "Error", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); ValidateSingleEventCounter(evts[2], "Request", 2, 7.5f, 2.5f, 5, 10); ValidateSingleEventCounter(evts[3], "Error", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); })); /*************************************************************************/ tests.Add(new SubTest("EventCounter: Log 3 events in two polling periods (explicit polling)", delegate() { listener.EnableTimer(logger, 0); /* Turn off (but also poll once) */ logger.Request(5); logger.Request(10); logger.Error(); listener.EnableTimer(logger, 0); /* Turn off (but also poll once) */ logger.Request(8); logger.Error(); logger.Error(); listener.EnableTimer(logger, 0); /* Turn off (but also poll once) */ }, delegate(List <Event> evts) { Assert.Equal(6, evts.Count); ValidateSingleEventCounter(evts[0], "Request", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); ValidateSingleEventCounter(evts[1], "Error", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); ValidateSingleEventCounter(evts[2], "Request", 2, 7.5f, 2.5f, 5, 10); ValidateSingleEventCounter(evts[3], "Error", 1, 1, 0, 1, 1); ValidateSingleEventCounter(evts[4], "Request", 1, 8, 0, 8, 8); ValidateSingleEventCounter(evts[5], "Error", 2, 1, 0, 1, 1); })); /*************************************************************************/ int num100msecTimerTicks = 0; tests.Add(new SubTest("EventCounter: Log multiple events in multiple periods", delegate() { // We have had problems with timer ticks not being called back 100% reliably. // However timers really don't have a strong guarantee (only that the happen eventually) // So what we do is create a timer callback that simply counts the number of callbacks. // This acts as a marker to show whether the timer callbacks are happening promptly. // If we don't get enough of these tick callbacks then we don't require EventCounter to // be sending periodic callbacks either. num100msecTimerTicks = 0; using (var timer = new System.Threading.Timer(delegate(object state) { num100msecTimerTicks++; EventTestHarness.LogWriteLine("Tick"); }, null, 100, 100)) { listener.EnableTimer(logger, .1); /* Poll every .1 s */ // logs at 0 seconds because of EnableTimer command Sleep(100); logger.Request(1); Sleep(100); logger.Request(2); logger.Error(); Sleep(100); logger.Request(4); Sleep(100); logger.Request(8); logger.Error(); Sleep(100); logger.Request(16); Sleep(220); listener.EnableTimer(logger, 0); } }, delegate(List <Event> evts) { int requestCount = 0; float requestSum = 0; float requestMin = float.MaxValue; float requestMax = float.MinValue; int errorCount = 0; float errorSum = 0; float errorMin = float.MaxValue; float errorMax = float.MinValue; float timeSum = 0; for (int j = 0; j < evts.Count; j += 2) { var requestPayload = ValidateEventHeaderAndGetPayload(evts[j]); Assert.Equal("Request", requestPayload["Name"]); var count = (int)requestPayload["Count"]; requestCount += count; if (count > 0) { requestSum += (float)requestPayload["Mean"] * count; } requestMin = Math.Min(requestMin, (float)requestPayload["Min"]); requestMax = Math.Max(requestMax, (float)requestPayload["Max"]); float requestIntervalSec = (float)requestPayload["IntervalSec"]; var errorPayload = ValidateEventHeaderAndGetPayload(evts[j + 1]); Assert.Equal("Error", errorPayload["Name"]); count = (int)errorPayload["Count"]; errorCount += count; if (count > 0) { errorSum += (float)errorPayload["Mean"] * count; } errorMin = Math.Min(errorMin, (float)errorPayload["Min"]); errorMax = Math.Max(errorMax, (float)errorPayload["Max"]); float errorIntervalSec = (float)requestPayload["IntervalSec"]; Assert.Equal(requestIntervalSec, errorIntervalSec); timeSum += requestIntervalSec; } EventTestHarness.LogWriteLine("Validating: Count={0} RequestSum={1:n3} TimeSum={2:n3} ", evts.Count, requestSum, timeSum); Assert.Equal(5, requestCount); Assert.Equal(31, requestSum); Assert.Equal(1, requestMin); Assert.Equal(16, requestMax); Assert.Equal(2, errorCount); Assert.Equal(2, errorSum); Assert.Equal(1, errorMin); Assert.Equal(1, errorMax); Assert.True(.4 < timeSum, $"FAILURE: .4 < {timeSum}"); // We should have at least 400 msec Assert.True(timeSum < 2, $"FAILURE: {timeSum} < 2"); // But well under 2 sec. // Do all the things that depend on the count of events last so we know everything else is sane Assert.True(4 <= evts.Count, "We expect two metrics at the beginning trigger and two at the end trigger. evts.Count = " + evts.Count); Assert.True(evts.Count % 2 == 0, "We expect two metrics for every trigger. evts.Count = " + evts.Count); ValidateSingleEventCounter(evts[0], "Request", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); ValidateSingleEventCounter(evts[1], "Error", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); // We should always get the unconditional callback at the start and end of the trace. Assert.True(4 <= evts.Count, $"FAILURE EventCounter Multi-event: 4 <= {evts.Count} ticks: {num100msecTimerTicks} thread: {Environment.CurrentManagedThreadId}"); // We expect the timer to have gone off at least twice, plus the explicit poll at the beginning and end. // Each one fires two events (one for requests, one for errors). so that is (2 + 2)*2 = 8 // We expect about 7 timer requests, but we don't get picky about the exact count // Putting in a generous buffer, we double 7 to say we don't expect more than 14 timer fires // so that is (2 + 14) * 2 = 32 if (num100msecTimerTicks > 3) // We seem to have problems with timer events going off 100% reliably. To avoid failures here we only check if in the 700 msec test we get at least 3 100 msec ticks. { Assert.True(8 <= evts.Count, $"FAILURE: 8 <= {evts.Count}"); } Assert.True(evts.Count <= 32, $"FAILURE: {evts.Count} <= 32"); })); /*************************************************************************/ tests.Add(new SubTest("EventCounter: Dispose()", delegate() { // Creating and destroying var myCounter = new EventCounter("counter for a transient object", logger); myCounter.WriteMetric(10); listener.EnableTimer(logger, 0); /* Turn off (but also poll once) */ myCounter.Dispose(); listener.EnableTimer(logger, 0); /* Turn off (but also poll once) */ }, delegate(List <Event> evts) { // The static counters (Request and Error), should not log any counts and stay at zero. // The new counter will exist for the first poll but will not exist for the second. Assert.Equal(5, evts.Count); ValidateSingleEventCounter(evts[0], "Request", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); ValidateSingleEventCounter(evts[1], "Error", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); ValidateSingleEventCounter(evts[2], "counter for a transient object", 1, 10, 0, 10, 10); ValidateSingleEventCounter(evts[3], "Request", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); ValidateSingleEventCounter(evts[4], "Error", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); })); /*************************************************************************/ EventTestHarness.RunTests(tests, listener, logger); } TestUtilities.CheckNoEventSourcesRunning("Stop"); }
/// <summary> /// Te /// </summary> /// <param name="listener"></param> private void Test_Write_T(Listener listener) { TestUtilities.CheckNoEventSourcesRunning("Start"); using (var logger = new EventSource("EventSourceName")) { var tests = new List <SubTest>(); /*************************************************************************/ tests.Add(new SubTest("Write/Basic/String", delegate() { logger.Write("Greeting", new { msg = "Hello, world!" }); }, delegate(Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("Greeting", evt.EventName); Assert.Equal("Hello, world!", evt.PayloadValue(0, "msg")); })); /*************************************************************************/ decimal myMoney = 300; tests.Add(new SubTest("Write/Basic/decimal", delegate() { logger.Write("Decimal", new { money = myMoney }); }, delegate(Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("Decimal", evt.EventName); var eventMoney = evt.PayloadValue(0, "money"); // TOD FIX ME - Fix TraceEvent to return decimal instead of double. //Assert.Equal((decimal)eventMoney, (decimal)300); })); /*************************************************************************/ DateTime now = DateTime.Now; tests.Add(new SubTest("Write/Basic/DateTime", delegate() { logger.Write("DateTime", new { nowTime = now }); }, delegate(Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("DateTime", evt.EventName); var eventNow = evt.PayloadValue(0, "nowTime"); Assert.Equal(eventNow, now); })); /*************************************************************************/ byte[] byteArray = { 0, 1, 2, 3 }; tests.Add(new SubTest("Write/Basic/byte[]", delegate() { logger.Write("Bytes", new { bytes = byteArray }); }, delegate(Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("Bytes", evt.EventName); var eventArray = evt.PayloadValue(0, "bytes"); Array.Equals(eventArray, byteArray); })); /*************************************************************************/ int?nullableInt = 12; tests.Add(new SubTest("Write/Basic/int?/12", delegate() { logger.Write("Int12", new { nInteger = nullableInt }); }, delegate(Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("Int12", evt.EventName); var payload = evt.PayloadValue(0, "nInteger"); Assert.Equal(nullableInt, TestUtilities.UnwrapNullable <int>(payload)); })); /*************************************************************************/ int?nullableInt2 = null; tests.Add(new SubTest("Write/Basic/int?/null", delegate() { logger.Write("IntNull", new { nInteger = nullableInt2 }); }, delegate(Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("IntNull", evt.EventName); var payload = evt.PayloadValue(0, "nInteger"); Assert.Equal(nullableInt2, TestUtilities.UnwrapNullable <int>(payload)); })); ///*************************************************************************/ DateTime?nullableDate = DateTime.Now; tests.Add(new SubTest("Write/Basic/DateTime?/Now", delegate() { logger.Write("DateTimeNow", new { nowTime = nullableDate }); }, delegate(Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("DateTimeNow", evt.EventName); var payload = evt.PayloadValue(0, "nowTime"); Assert.Equal(nullableDate, TestUtilities.UnwrapNullable <DateTime>(payload)); })); /*************************************************************************/ DateTime?nullableDate2 = null; tests.Add(new SubTest("Write/Basic/DateTime?/Null", delegate() { logger.Write("DateTimeNull", new { nowTime = nullableDate2 }); }, delegate(Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("DateTimeNull", evt.EventName); var payload = evt.PayloadValue(0, "nowTime"); Assert.Equal(nullableDate2, TestUtilities.UnwrapNullable <DateTime>(payload)); })); /*************************************************************************/ tests.Add(new SubTest("Write/Basic/PartBOnly", delegate() { // log just a PartB logger.Write("UserInfo", new EventSourceOptions { Keywords = EventKeywords.None }, new { _1 = new PartB_UserInfo { UserName = "******" } }); }, delegate(Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("UserInfo", evt.EventName); var structValue = evt.PayloadValue(0, "PartB_UserInfo"); var structValueAsDictionary = structValue as IDictionary <string, object>; Assert.NotNull(structValueAsDictionary); Assert.Equal("Someone Else", structValueAsDictionary["UserName"]); })); /*************************************************************************/ tests.Add(new SubTest("Write/Basic/PartBAndC", delegate() { // log a PartB and a PartC logger.Write("Duration", new EventSourceOptions { Keywords = EventKeywords.None }, new { _1 = new PartB_UserInfo { UserName = "******" }, msec = 10 }); }, delegate(Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("Duration", evt.EventName); var structValue = evt.PayloadValue(0, "PartB_UserInfo"); var structValueAsDictionary = structValue as IDictionary <string, object>; Assert.NotNull(structValueAsDictionary); Assert.Equal("Myself", structValueAsDictionary["UserName"]); Assert.Equal(10, evt.PayloadValue(1, "msec")); })); /*************************************************************************/ /*************************** ENUM TESTING *******************************/ /*************************************************************************/ /*************************************************************************/ GenerateEnumTest <Color>(ref tests, logger, Color.Green); GenerateEnumTest <ColorUInt32>(ref tests, logger, ColorUInt32.Green); GenerateEnumTest <ColorByte>(ref tests, logger, ColorByte.Green); GenerateEnumTest <ColorSByte>(ref tests, logger, ColorSByte.Green); GenerateEnumTest <ColorInt16>(ref tests, logger, ColorInt16.Green); GenerateEnumTest <ColorUInt16>(ref tests, logger, ColorUInt16.Green); GenerateEnumTest <ColorInt64>(ref tests, logger, ColorInt64.Green); GenerateEnumTest <ColorUInt64>(ref tests, logger, ColorUInt64.Green); /*************************************************************************/ /*************************** ARRAY TESTING *******************************/ /*************************************************************************/ /*************************************************************************/ GenerateArrayTest <bool>(ref tests, logger, new bool[] { false, true, false }); GenerateArrayTest <byte>(ref tests, logger, new byte[] { 1, 10, 100 }); GenerateArrayTest <sbyte>(ref tests, logger, new sbyte[] { 1, 10, 100 }); GenerateArrayTest <short>(ref tests, logger, new short[] { 1, 10, 100 }); GenerateArrayTest <ushort>(ref tests, logger, new ushort[] { 1, 10, 100 }); GenerateArrayTest <int>(ref tests, logger, new int[] { 1, 10, 100 }); GenerateArrayTest <uint>(ref tests, logger, new uint[] { 1, 10, 100 }); GenerateArrayTest <long>(ref tests, logger, new long[] { 1, 10, 100 }); GenerateArrayTest <ulong>(ref tests, logger, new ulong[] { 1, 10, 100 }); GenerateArrayTest <char>(ref tests, logger, new char[] { 'a', 'c', 'b' }); GenerateArrayTest <double>(ref tests, logger, new double[] { 1, 10, 100 }); GenerateArrayTest <float>(ref tests, logger, new float[] { 1, 10, 100 }); GenerateArrayTest <IntPtr>(ref tests, logger, new IntPtr[] { (IntPtr)1, (IntPtr)10, (IntPtr)100 }); GenerateArrayTest <UIntPtr>(ref tests, logger, new UIntPtr[] { (UIntPtr)1, (UIntPtr)10, (UIntPtr)100 }); GenerateArrayTest <Guid>(ref tests, logger, new Guid[] { Guid.Empty, new Guid("121a11ee-3bcb-49cc-b425-f4906fb14f72") }); /*************************************************************************/ /*********************** DICTIONARY TESTING ******************************/ /*************************************************************************/ var dict = new Dictionary <string, string>() { { "elem1", "10" }, { "elem2", "20" } }; var dictInt = new Dictionary <string, int>() { { "elem1", 10 }, { "elem2", 20 } }; /*************************************************************************/ tests.Add(new SubTest("Write/Dict/EventWithStringDict_C", delegate() { // log a dictionary logger.Write("EventWithStringDict_C", new { myDict = dict, s = "end" }); }, delegate(Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("EventWithStringDict_C", evt.EventName); var keyValues = evt.PayloadValue(0, "myDict"); IDictionary <string, object> vDict = GetDictionaryFromKeyValueArray(keyValues); Assert.Equal("10", vDict["elem1"]); Assert.Equal("20", vDict["elem2"]); Assert.Equal("end", evt.PayloadValue(1, "s")); })); /*************************************************************************/ tests.Add(new SubTest("Write/Dict/EventWithStringDict_BC", delegate() { // log a PartB and a dictionary as a PartC logger.Write("EventWithStringDict_BC", new { PartB_UserInfo = new { UserName = "******", LogTime = "Now" }, PartC_Dict = dict, s = "end" }); }, delegate(Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("EventWithStringDict_BC", evt.EventName); var structValue = evt.PayloadValue(0, "PartB_UserInfo"); var structValueAsDictionary = structValue as IDictionary <string, object>; Assert.NotNull(structValueAsDictionary); Assert.Equal("Me", structValueAsDictionary["UserName"]); Assert.Equal("Now", structValueAsDictionary["LogTime"]); var keyValues = evt.PayloadValue(1, "PartC_Dict"); var vDict = GetDictionaryFromKeyValueArray(keyValues); Assert.NotNull(dict); Assert.Equal("10", vDict["elem1"]); // string values. Assert.Equal("20", vDict["elem2"]); Assert.Equal("end", evt.PayloadValue(2, "s")); })); /*************************************************************************/ tests.Add(new SubTest("Write/Dict/EventWithIntDict_BC", delegate() { // log a Dict<string, int> as a PartC logger.Write("EventWithIntDict_BC", new { PartB_UserInfo = new { UserName = "******", LogTime = "Now" }, PartC_Dict = dictInt, s = "end" }); }, delegate(Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("EventWithIntDict_BC", evt.EventName); var structValue = evt.PayloadValue(0, "PartB_UserInfo"); var structValueAsDictionary = structValue as IDictionary <string, object>; Assert.NotNull(structValueAsDictionary); Assert.Equal("Me", structValueAsDictionary["UserName"]); Assert.Equal("Now", structValueAsDictionary["LogTime"]); var keyValues = evt.PayloadValue(1, "PartC_Dict"); var vDict = GetDictionaryFromKeyValueArray(keyValues); Assert.NotNull(vDict); Assert.Equal(10, vDict["elem1"]); // Notice they are integers, not strings. Assert.Equal(20, vDict["elem2"]); Assert.Equal("end", evt.PayloadValue(2, "s")); })); /*************************************************************************/ /**************************** Empty Event TESTING ************************/ /*************************************************************************/ tests.Add(new SubTest("Write/Basic/Message", delegate() { logger.Write("EmptyEvent"); }, delegate(Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("EmptyEvent", evt.EventName); })); /*************************************************************************/ /**************************** EventSourceOptions TESTING *****************/ /*************************************************************************/ EventSourceOptions options = new EventSourceOptions(); options.Level = EventLevel.LogAlways; options.Keywords = EventKeywords.All; options.Opcode = EventOpcode.Info; options.Tags = EventTags.None; tests.Add(new SubTest("Write/Basic/MessageOptions", delegate() { logger.Write("EmptyEvent", options); }, delegate(Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("EmptyEvent", evt.EventName); })); tests.Add(new SubTest("Write/Basic/WriteOfTWithOptios", delegate() { logger.Write("OptionsEvent", options, new { OptionsEvent = "test options!" }); }, delegate(Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("OptionsEvent", evt.EventName); Assert.Equal("test options!", evt.PayloadValue(0, "OptionsEvent")); })); tests.Add(new SubTest("Write/Basic/WriteOfTWithRefOptios", delegate() { var v = new { OptionsEvent = "test ref options!" }; logger.Write("RefOptionsEvent", ref options, ref v); }, delegate(Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("RefOptionsEvent", evt.EventName); Assert.Equal("test ref options!", evt.PayloadValue(0, "OptionsEvent")); })); tests.Add(new SubTest("Write/Basic/WriteOfTWithNullString", delegate() { string nullString = null; logger.Write("NullStringEvent", new { a = (string)null, b = nullString }); }, delegate(Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("NullStringEvent", evt.EventName); Assert.Equal("", evt.PayloadValue(0, "a")); Assert.Equal("", evt.PayloadValue(1, "b")); })); // This test only applies to ETW and will fail on EventListeners due to different behavior // for strings with embedded NULL characters. Test_Write_T_AddEtwTests(listener, tests, logger); Guid activityId = new Guid("00000000-0000-0000-0000-000000000001"); Guid relActivityId = new Guid("00000000-0000-0000-0000-000000000002"); tests.Add(new SubTest("Write/Basic/WriteOfTWithOptios", delegate() { var v = new { ActivityMsg = "test activity!" }; logger.Write("ActivityEvent", ref options, ref activityId, ref relActivityId, ref v); }, delegate(Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("ActivityEvent", evt.EventName); Assert.Equal("test activity!", evt.PayloadValue(0, "ActivityMsg")); })); // If you only wish to run one or several of the tests you can filter them here by // Uncommenting the following line. // tests = tests.FindAll(test => Regex.IsMatch(test.Name, "Write/Basic/EventII")); // Here is where we actually run tests. First test the ETW path EventTestHarness.RunTests(tests, listener, logger); } TestUtilities.CheckNoEventSourcesRunning("Stop"); }
private void Test_Write_Metric(Listener listener) { Console.WriteLine("Version of Runtime {0}", Environment.Version); Console.WriteLine("Version of OS {0}", Environment.OSVersion); TestUtilities.CheckNoEventSourcesRunning("Start"); using (var logger = new MyEventSource()) { var tests = new List <SubTest>(); /*************************************************************************/ tests.Add(new SubTest("Log 1 event, explicit poll at end", delegate() { listener.EnableTimer(logger, 1); // Set to poll every second, but we dont actually care because the test ends before that. logger.Request(5); listener.EnableTimer(logger, 0); }, delegate(List <Event> evts) { // There will be two events (request and error) for time 0 and 2 more at 1 second and 2 more when we shut it off. Assert.Equal(4, evts.Count); ValidateSingleEventCounter(evts[0], "Request", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); ValidateSingleEventCounter(evts[1], "Error", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); ValidateSingleEventCounter(evts[2], "Request", 1, 5, 0, 5, 5); ValidateSingleEventCounter(evts[3], "Error", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); })); /*************************************************************************/ tests.Add(new SubTest("Log 2 events, explicit poll at end", delegate() { listener.EnableTimer(logger, 1); // Set to poll every second, but we dont actually care because the test ends before that. logger.Request(5); logger.Request(10); listener.EnableTimer(logger, 0); // poll }, delegate(List <Event> evts) { Assert.Equal(4, evts.Count); ValidateSingleEventCounter(evts[0], "Request", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); ValidateSingleEventCounter(evts[1], "Error", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); ValidateSingleEventCounter(evts[2], "Request", 2, 7.5f, 2.5f, 5, 10); ValidateSingleEventCounter(evts[3], "Error", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); })); /*************************************************************************/ tests.Add(new SubTest("Log 3 events in two polling periods (explicit polling)", delegate() { listener.EnableTimer(logger, 0); /* Turn off (but also poll once) */ logger.Request(5); logger.Request(10); logger.Error(); listener.EnableTimer(logger, 0); /* Turn off (but also poll once) */ logger.Request(8); logger.Error(); logger.Error(); listener.EnableTimer(logger, 0); /* Turn off (but also poll once) */ }, delegate(List <Event> evts) { Assert.Equal(6, evts.Count); ValidateSingleEventCounter(evts[0], "Request", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); ValidateSingleEventCounter(evts[1], "Error", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); ValidateSingleEventCounter(evts[2], "Request", 2, 7.5f, 2.5f, 5, 10); ValidateSingleEventCounter(evts[3], "Error", 1, 1, 0, 1, 1); ValidateSingleEventCounter(evts[4], "Request", 1, 8, 0, 8, 8); ValidateSingleEventCounter(evts[5], "Error", 2, 1, 0, 1, 1); })); /*************************************************************************/ tests.Add(new SubTest("Log multiple events in", delegate() { listener.EnableTimer(logger, .1); /* Poll every .1 s */ // logs at 0 seconds because of EnableTimer command Sleep(100); logger.Request(1); Sleep(100); logger.Request(2); logger.Error(); Sleep(100); logger.Request(4); Sleep(100); logger.Error(); logger.Request(8); Sleep(100); logger.Request(16); Sleep(200); listener.EnableTimer(logger, 0); }, delegate(List <Event> evts) { int requestCount = 0; float requestSum = 0; float requestMin = float.MaxValue; float requestMax = float.MinValue; int errorCount = 0; float errorSum = 0; float errorMin = float.MaxValue; float errorMax = float.MinValue; float timeSum = 0; for (int j = 0; j < evts.Count; j += 2) { var requestPayload = ValidateEventHeaderAndGetPayload(evts[j]); Assert.Equal("Request", requestPayload["Name"]); var count = (int)requestPayload["Count"]; requestCount += count; if (count > 0) { requestSum += (float)requestPayload["Mean"] * count; } requestMin = Math.Min(requestMin, (float)requestPayload["Min"]); requestMax = Math.Max(requestMax, (float)requestPayload["Max"]); float requestIntevalSec = (float)requestPayload["IntervalSec"]; var errorPayload = ValidateEventHeaderAndGetPayload(evts[j + 1]); Assert.Equal("Error", errorPayload["Name"]); count = (int)errorPayload["Count"]; errorCount += count; if (count > 0) { errorSum += (float)errorPayload["Mean"] * count; } errorMin = Math.Min(errorMin, (float)errorPayload["Min"]); errorMax = Math.Max(errorMax, (float)errorPayload["Max"]); float errorIntevalSec = (float)requestPayload["IntervalSec"]; Assert.Equal(requestIntevalSec, errorIntevalSec); timeSum += requestIntevalSec; } Assert.Equal(requestCount, 5); Assert.Equal(requestSum, 31); Assert.Equal(requestMin, 1); Assert.Equal(requestMax, 16); Assert.Equal(errorCount, 2); Assert.Equal(errorSum, 2); Assert.Equal(errorMin, 1); Assert.Equal(errorMax, 1); Assert.True(.4 < timeSum, $"FAILURE: .4 < {timeSum}"); // We should have at least 400 msec Assert.True(timeSum < 2, $"FAILURE: {timeSum} < 2"); // But well under 2 sec. // Do all the things that depend on the count of events last so we know everything else is sane Assert.True(4 <= evts.Count, "We expect two metrices at the begining trigger and two at the end trigger. evts.Count = " + evts.Count); Assert.True(evts.Count % 2 == 0, "We expect two metrics for every trigger. evts.Count = " + evts.Count); ValidateSingleEventCounter(evts[0], "Request", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); ValidateSingleEventCounter(evts[1], "Error", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); // We expect the timer to have gone off at least twice, plus the explicit poll at the begining and end. // Each one fires two events (one for requests, one for errors). so that is (2 + 2)*2 = 8 // We expect about 5 timer requests, but we don't get picky about the exact count // We don't expect more than say 9 timer request so that is (2 + 9) * 2 = 22 Assert.True(8 <= evts.Count, $"FAILURE: 8 <= {evts.Count}"); Assert.True(evts.Count <= 22, $"FAILURE: {evts.Count} <= 22"); })); /*************************************************************************/ // TODO expose Dispose() method and activate this test. #if EventCounterDispose tests.Add(new SubTest("EventCounter.Dispose()", delegate() { // Creating and destroying var myCounter = new EventCounter("counter for a transient object", logger); myCounter.WriteMetric(10); listener.EnableTimer(logger, 0); /* Turn off (but also poll once) */ myCounter.Dispose(); listener.EnableTimer(logger, 0); /* Turn off (but also poll once) */ }, delegate(List <Event> evts) { Assert.Equal(5, evts.Count); ValidateSingleEventCounter(evts[0], "Request", 0, 0, 0, 0, 0); ValidateSingleEventCounter(evts[1], "Error", 0, 0, 0, 0, 0); ValidateSingleEventCounter(evts[2], "counter for a transient object", 1, 10, 0, 10, 10); ValidateSingleEventCounter(evts[3], "Request", 0, 0, 0, 0, 0); ValidateSingleEventCounter(evts[4], "Error", 0, 0, 0, 0, 0); })); #endif /*************************************************************************/ EventTestHarness.RunTests(tests, listener, logger); } TestUtilities.CheckNoEventSourcesRunning("Stop"); }
private void Test_Write_Metric(Listener listener) { TestUtilities.CheckNoEventSourcesRunning("Start"); using (var logger = new MyEventSource()) { var tests = new List <SubTest>(); /*************************************************************************/ tests.Add(new SubTest("Log 1 event", delegate() { listener.EnableTimer(logger, 1); /* Poll every 1 s */ logger.Request(37); Thread.Sleep(1500); // Sleep for 1.5 seconds listener.EnableTimer(logger, 0); }, delegate(List <Event> evts) { Assert.Equal(2, evts.Count); ValidateSingleEventCounter(evts[0], "Request", 1, 37, 0, 37, 37); })); /*************************************************************************/ tests.Add(new SubTest("Log 2 event in single period", delegate() { listener.EnableTimer(logger, 1); /* Poll every 1 s */ logger.Request(37); logger.Request(25); Thread.Sleep(1500); // Sleep for 1.5 seconds listener.EnableTimer(logger, 0); }, delegate(List <Event> evts) { Assert.Equal(2, evts.Count); ValidateSingleEventCounter(evts[0], "Request", 2, 31, 6, 25, 37); })); /*************************************************************************/ tests.Add(new SubTest("Log 2 event in two periods", delegate() { listener.EnableTimer(logger, 1); /* Poll every 1 s */ logger.Request(37); Thread.Sleep(1500); // Sleep for 1.5 seconds logger.Request(25); Thread.Sleep(1000); // Sleep for 1 seconds (at time = 2.5 second exactly two messages should be received) listener.EnableTimer(logger, 0); }, delegate(List <Event> evts) { Assert.Equal(4, evts.Count); ValidateSingleEventCounter(evts[0], "Request", 1, 37, 0, 37, 37); ValidateSingleEventCounter(evts[2], "Request", 1, 25, 0, 25, 25); })); /*************************************************************************/ tests.Add(new SubTest("Log 2 different events in a period", delegate() { listener.EnableTimer(logger, 1); /* Poll every 1 s */ logger.Request(25); logger.Error(); Thread.Sleep(1500); // Sleep for 1.5 seconds listener.EnableTimer(logger, 0); }, delegate(List <Event> evts) { Assert.Equal(2, evts.Count); ValidateSingleEventCounter(evts[0], "Request", 1, 25, 0, 25, 25); ValidateSingleEventCounter(evts[1], "Error", 1, 1, 0, 1, 1); })); /*************************************************************************/ EventTestHarness.RunTests(tests, listener, logger); } TestUtilities.CheckNoEventSourcesRunning("Stop"); }
public void Test_WriteEvent_ArgsBasicTypes() { TestUtilities.CheckNoEventSourcesRunning("Start"); using (var log = new EventSourceTest()) { using (var el = new LoudListener(log)) { var sources = EventSource.GetSources(); Assert.Contains(log, sources); Assert.NotNull(EventSource.GenerateManifest(typeof(SimpleEventSource), string.Empty, EventManifestOptions.OnlyIfNeededForRegistration)); Assert.Null(EventSource.GenerateManifest(typeof(EventSourceTest), string.Empty, EventManifestOptions.OnlyIfNeededForRegistration)); log.Event0(); Assert.Equal(1, LoudListener.t_lastEvent.EventId); Assert.Equal(0, LoudListener.t_lastEvent.Payload.Count); #region Validate "int" arguments log.EventI(10); Assert.Equal(2, LoudListener.t_lastEvent.EventId); Assert.Equal(1, LoudListener.t_lastEvent.Payload.Count); Assert.Equal(10, (int)LoudListener.t_lastEvent.Payload[0]); log.EventII(10, 11); Assert.Equal(3, LoudListener.t_lastEvent.EventId); Assert.Equal(2, LoudListener.t_lastEvent.Payload.Count); Assert.Equal(10, (int)LoudListener.t_lastEvent.Payload[0]); Assert.Equal(11, (int)LoudListener.t_lastEvent.Payload[1]); log.EventIII(10, 11, 12); Assert.Equal(4, LoudListener.t_lastEvent.EventId); Assert.Equal(3, LoudListener.t_lastEvent.Payload.Count); Assert.Equal(10, (int)LoudListener.t_lastEvent.Payload[0]); Assert.Equal(11, (int)LoudListener.t_lastEvent.Payload[1]); Assert.Equal(12, (int)LoudListener.t_lastEvent.Payload[2]); #endregion #region Validate "long" arguments log.EventL(10); Assert.Equal(5, LoudListener.t_lastEvent.EventId); Assert.Equal(1, LoudListener.t_lastEvent.Payload.Count); Assert.Equal(10, (long)LoudListener.t_lastEvent.Payload[0]); log.EventLL(10, 11); Assert.Equal(6, LoudListener.t_lastEvent.EventId); Assert.Equal(2, LoudListener.t_lastEvent.Payload.Count); Assert.Equal(10, (long)LoudListener.t_lastEvent.Payload[0]); Assert.Equal(11, (long)LoudListener.t_lastEvent.Payload[1]); log.EventLLL(10, 11, 12); Assert.Equal(7, LoudListener.t_lastEvent.EventId); Assert.Equal(3, LoudListener.t_lastEvent.Payload.Count); Assert.Equal(10, (long)LoudListener.t_lastEvent.Payload[0]); Assert.Equal(11, (long)LoudListener.t_lastEvent.Payload[1]); Assert.Equal(12, (long)LoudListener.t_lastEvent.Payload[2]); #endregion #region Validate "string" arguments log.EventS("10"); Assert.Equal(8, LoudListener.t_lastEvent.EventId); Assert.Equal(1, LoudListener.t_lastEvent.Payload.Count); Assert.Equal("10", (string)LoudListener.t_lastEvent.Payload[0]); log.EventSS("10", "11"); Assert.Equal(9, LoudListener.t_lastEvent.EventId); Assert.Equal(2, LoudListener.t_lastEvent.Payload.Count); Assert.Equal("10", (string)LoudListener.t_lastEvent.Payload[0]); Assert.Equal("11", (string)LoudListener.t_lastEvent.Payload[1]); log.EventSSS("10", "11", "12"); Assert.Equal(10, LoudListener.t_lastEvent.EventId); Assert.Equal(3, LoudListener.t_lastEvent.Payload.Count); Assert.Equal("10", (string)LoudListener.t_lastEvent.Payload[0]); Assert.Equal("11", (string)LoudListener.t_lastEvent.Payload[1]); Assert.Equal("12", (string)LoudListener.t_lastEvent.Payload[2]); #endregion #region Validate byte array arguments byte[] arr = new byte[20]; log.EventWithByteArray(arr); Assert.Equal(52, LoudListener.t_lastEvent.EventId); Assert.Equal(1, LoudListener.t_lastEvent.Payload.Count); Assert.Equal(arr.Length, ((byte[])LoudListener.t_lastEvent.Payload[0]).Length); #endregion #region Validate mixed type arguments log.EventSI("10", 11); Assert.Equal(11, LoudListener.t_lastEvent.EventId); Assert.Equal(2, LoudListener.t_lastEvent.Payload.Count); Assert.Equal("10", (string)LoudListener.t_lastEvent.Payload[0]); Assert.Equal(11, (int)LoudListener.t_lastEvent.Payload[1]); log.EventSL("10", 11); Assert.Equal(12, LoudListener.t_lastEvent.EventId); Assert.Equal(2, LoudListener.t_lastEvent.Payload.Count); Assert.Equal("10", (string)LoudListener.t_lastEvent.Payload[0]); Assert.Equal(11, (long)LoudListener.t_lastEvent.Payload[1]); log.EventSII("10", 11, 12); Assert.Equal(13, LoudListener.t_lastEvent.EventId); Assert.Equal(3, LoudListener.t_lastEvent.Payload.Count); Assert.Equal("10", (string)LoudListener.t_lastEvent.Payload[0]); Assert.Equal(11, (int)LoudListener.t_lastEvent.Payload[1]); Assert.Equal(12, (int)LoudListener.t_lastEvent.Payload[2]); #endregion #region Validate enums/flags log.EventEnum(MyColor.Blue); Assert.Equal(19, LoudListener.t_lastEvent.EventId); Assert.Equal(1, LoudListener.t_lastEvent.Payload.Count); Assert.Equal(MyColor.Blue, (MyColor)LoudListener.t_lastEvent.Payload[0]); log.EventEnum1(MyColor.Green); Assert.Equal(20, LoudListener.t_lastEvent.EventId); Assert.Equal(1, LoudListener.t_lastEvent.Payload.Count); Assert.Equal(MyColor.Green, (MyColor)LoudListener.t_lastEvent.Payload[0]); log.EventFlags(MyFlags.Flag1); Assert.Equal(21, LoudListener.t_lastEvent.EventId); Assert.Equal(1, LoudListener.t_lastEvent.Payload.Count); Assert.Equal(MyFlags.Flag1, (MyFlags)LoudListener.t_lastEvent.Payload[0]); log.EventFlags1(MyFlags.Flag1); Assert.Equal(22, LoudListener.t_lastEvent.EventId); Assert.Equal(1, LoudListener.t_lastEvent.Payload.Count); Assert.Equal(MyFlags.Flag1, (MyFlags)LoudListener.t_lastEvent.Payload[0]); #endregion #region Validate DateTime Test_WriteEvent_ArgsBasicTypes_Etw_Validate_DateTime(log); #endregion } } TestUtilities.CheckNoEventSourcesRunning("Stop"); }