From d8aa27df1a531d6190f9cc621f5d1d6a7dfe8f7a Mon Sep 17 00:00:00 2001 From: Gene Lee Date: Fri, 12 Jan 2018 15:09:45 -0800 Subject: [PATCH] SqlConnection timeout test is ported --- .../SqlConnectionBasicTests.cs | 96 ++++++++++++++++++- 1 file changed, 95 insertions(+), 1 deletion(-) diff --git a/src/System.Data.SqlClient/tests/FunctionalTests/SqlConnectionBasicTests.cs b/src/System.Data.SqlClient/tests/FunctionalTests/SqlConnectionBasicTests.cs index 2df596fac9c7..4611beeb7114 100644 --- a/src/System.Data.SqlClient/tests/FunctionalTests/SqlConnectionBasicTests.cs +++ b/src/System.Data.SqlClient/tests/FunctionalTests/SqlConnectionBasicTests.cs @@ -2,9 +2,11 @@ // 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.Data.Common; +using System.Diagnostics; using System.Reflection; +using System.Threading; using Xunit; namespace System.Data.SqlClient.Tests @@ -79,5 +81,97 @@ public void SqlConnectionInvalidParameters() Assert.Throws(() => new SqlConnection("Timeout=1a;")); Assert.Throws(() => new SqlConnection("Integrated Security=truee")); } + + [Fact] + public void ConnectionTimeoutTestWithThread() + { + int timeoutSec = 5; + string connStrNotAvailable = $"Server=tcp:fakeServer,1433;uid=fakeuser;pwd=fakepwd;Connection Timeout={timeoutSec}"; + + List list = new List(); + for (int i = 0; i < 10; ++i) + { + list.Add(new ConnectionWorker(connStrNotAvailable)); + } + + ConnectionWorker.Start(); + ConnectionWorker.Stop(); + + double theMax = 0; + foreach (ConnectionWorker w in list) + { + if (theMax < w.MaxTimeElapsed) + { + theMax = w.MaxTimeElapsed; + } + } + + int threshold = (timeoutSec + 1) * 1000; + Assert.True(theMax < threshold); + } + + public class ConnectionWorker + { + private static ManualResetEventSlim startEvent = new ManualResetEventSlim(false); + private static List workerList = new List(); + private ManualResetEventSlim doneEvent = new ManualResetEventSlim(false); + private double maxTimeElapsed; + private Thread thread; + private string connectionString; + + public ConnectionWorker(string connectionString) + { + workerList.Add(this); + this.connectionString = connectionString; + thread = new Thread(new ThreadStart(SqlConnectionOpen)); + thread.Start(); + } + + public double MaxTimeElapsed + { + get + { + return maxTimeElapsed; + } + } + + public static void Start() + { + startEvent.Set(); + } + + public static void Stop() + { + foreach (ConnectionWorker w in workerList) + { + w.doneEvent.Wait(); + } + } + + public void SqlConnectionOpen() + { + startEvent.Wait(); + + Stopwatch sw = new Stopwatch(); + using (SqlConnection con = new SqlConnection(connectionString)) + { + sw.Start(); + try + { + con.Open(); + } + catch { } + sw.Stop(); + } + + double elapsed = sw.Elapsed.TotalMilliseconds; + if (maxTimeElapsed < elapsed) + { + maxTimeElapsed = elapsed; + } + + doneEvent.Set(); + } + } } }