Skip to content

Commit 292e8b8

Browse files
Add integration test connection retry (#238)
* Add retry to DB connection in integration tests * Rename var
1 parent 9c30103 commit 292e8b8

File tree

2 files changed

+36
-2
lines changed

2 files changed

+36
-2
lines changed

test/Common/TestUtils.cs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
// Licensed under the MIT License. See License.txt in the project root for license information.
33

44
using System;
5+
using System.Collections.Generic;
56
using System.Data;
67
using System.Diagnostics;
78
using System.Threading;
@@ -117,5 +118,36 @@ public static object ExecuteScalar(
117118

118119
return null;
119120
}
121+
122+
/// <summary>
123+
/// Retries the specified action, waiting for the specified duration in between each attempt
124+
/// </summary>
125+
/// <param name="action">The action to run</param>
126+
/// <param name="retryCount">The max number of retries to attempt</param>
127+
/// <param name="waitDurationMs">The duration in milliseconds between each attempt</param>
128+
/// <exception cref="AggregateException">Aggregate of all exceptions thrown if all retries failed</exception>
129+
public static void Retry(Action action, int retryCount = 3, int waitDurationMs = 10000)
130+
{
131+
var exceptions = new List<Exception>();
132+
while (true)
133+
{
134+
try
135+
{
136+
action();
137+
break;
138+
}
139+
catch (Exception ex)
140+
{
141+
exceptions.Add(ex);
142+
retryCount--;
143+
if (retryCount == 0)
144+
{
145+
throw new AggregateException($"Action failed all retries", exceptions);
146+
}
147+
Console.WriteLine($"Error running action, retrying after {waitDurationMs}ms. {retryCount} retries left. {ex}");
148+
Thread.Sleep(waitDurationMs);
149+
}
150+
}
151+
}
120152
}
121153
}

test/Integration/IntegrationTestBase.cs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -105,12 +105,14 @@ private void SetupDatabase()
105105
this.MasterConnectionString = connectionStringBuilder.ToString();
106106

107107
// Create database
108+
// Retry this in case the server isn't fully initialized yet
108109
this.DatabaseName = TestUtils.GetUniqueDBName("SqlBindingsTest");
109-
using (var masterConnection = new SqlConnection(this.MasterConnectionString))
110+
TestUtils.Retry(() =>
110111
{
112+
using var masterConnection = new SqlConnection(this.MasterConnectionString);
111113
masterConnection.Open();
112114
TestUtils.ExecuteNonQuery(masterConnection, $"CREATE DATABASE [{this.DatabaseName}]");
113-
}
115+
});
114116

115117
// Setup connection
116118
connectionStringBuilder.InitialCatalog = this.DatabaseName;

0 commit comments

Comments
 (0)