From ff6217d850b2e6cbe573561e2d243a3e3ec2a90f Mon Sep 17 00:00:00 2001 From: Stephen Toub Date: Mon, 29 Apr 2019 20:52:59 -0400 Subject: [PATCH] Add a test for Stopwatch.Elapsed to ensure it's within reason (dotnet/corefx#37279) If this experiences flakiness in CI, we can tweak it, replace it with something better, etc. Commit migrated from https://github.com/dotnet/corefx/commit/c28dbd19fda676a57fb3edf25aaa42196ed36f05 --- .../tests/System/Diagnostics/Stopwatch.cs | 30 ++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/src/libraries/System.Runtime.Extensions/tests/System/Diagnostics/Stopwatch.cs b/src/libraries/System.Runtime.Extensions/tests/System/Diagnostics/Stopwatch.cs index fc38a8d..4936377 100644 --- a/src/libraries/System.Runtime.Extensions/tests/System/Diagnostics/Stopwatch.cs +++ b/src/libraries/System.Runtime.Extensions/tests/System/Diagnostics/Stopwatch.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Collections.Generic; using System.Threading; using Xunit; @@ -93,6 +94,35 @@ namespace System.Diagnostics.Tests } } + [OuterLoop("Sleeps for relatively long periods of time")] + [Fact] + public static void ElapsedMilliseconds_WithinExpectedWindow() + { + const int AllowedTries = 30; + const int SleepTime = 1000; + const double WindowFactor = 2; + + var results = new List(); + + var sw = new Stopwatch(); + for (int trial = 0; trial < AllowedTries; trial++) + { + sw.Restart(); + Thread.Sleep(SleepTime); + sw.Stop(); + + if (sw.ElapsedMilliseconds >= (SleepTime / WindowFactor) && + sw.ElapsedMilliseconds <= (SleepTime * WindowFactor)) + { + return; + } + + results.Add(sw.ElapsedMilliseconds); + } + + Assert.True(false, $"All {AllowedTries} fell outside of {WindowFactor} window of {SleepTime} sleep time: {string.Join(", ", results)}"); + } + private static void Sleep(int milliseconds = 1) { s_sleepEvent.WaitOne(milliseconds); -- 2.7.4