Skip to content

Commit 7d30a79

Browse files
author
rstam
committed
Fix unit test that was failing on replica sets due to replication lag.
1 parent f61f965 commit 7d30a79

File tree

1 file changed

+25
-7
lines changed

1 file changed

+25
-7
lines changed

MongoDB.DriverUnitTests/Jira/CSharp269Tests.cs

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,10 @@
1313
* limitations under the License.
1414
*/
1515

16+
using System;
1617
using System.IO;
1718
using System.Text;
19+
using System.Threading;
1820
using MongoDB.Driver;
1921
using NUnit.Framework;
2022

@@ -23,6 +25,7 @@ namespace MongoDB.DriverUnitTests.Jira.CSharp269
2325
[TestFixture]
2426
public class CSharp269Tests
2527
{
28+
private MongoServer _server;
2629
private MongoDatabase _database;
2730

2831
[TestFixtureSetUp]
@@ -31,8 +34,8 @@ public void TestFixtureSetup()
3134
var clientSettings = Configuration.TestClient.Settings.Clone();
3235
clientSettings.ReadPreference = ReadPreference.SecondaryPreferred;
3336
var client = new MongoClient(clientSettings); // ReadPreference=SecondaryPreferred
34-
var server = client.GetServer();
35-
_database = server.GetDatabase(Configuration.TestDatabase.Name);
37+
_server = client.GetServer();
38+
_database = _server.GetDatabase(Configuration.TestDatabase.Name);
3639
_database.GridFS.Files.Drop();
3740
_database.GridFS.Chunks.Drop();
3841
}
@@ -47,12 +50,27 @@ public void TestUploadAndDownload()
4750
_database.GridFS.Upload(stream, "HelloWorld.txt");
4851
}
4952

50-
using (var stream = new MemoryStream())
53+
// use RequestStart so that if we are running this test against a replica set we will bind to a specific secondary
54+
using (_server.RequestStart(_database, ReadPreference.SecondaryPreferred))
5155
{
52-
_database.GridFS.Download(stream, "HelloWorld.txt");
53-
var downloadedBytes = stream.ToArray();
54-
var downloadedText = Encoding.UTF8.GetString(downloadedBytes);
55-
Assert.AreEqual("HelloWorld", downloadedText);
56+
// wait for the GridFS file to be replicated before trying to Download it
57+
var timeoutAt = DateTime.UtcNow.AddSeconds(30);
58+
while (!_database.GridFS.Exists("HelloWorld.txt"))
59+
{
60+
if (DateTime.UtcNow >= timeoutAt)
61+
{
62+
throw new TimeoutException("HelloWorld.txt failed to propagate to secondary");
63+
}
64+
Thread.Sleep(TimeSpan.FromMilliseconds(1));
65+
}
66+
67+
using (var stream = new MemoryStream())
68+
{
69+
_database.GridFS.Download(stream, "HelloWorld.txt");
70+
var downloadedBytes = stream.ToArray();
71+
var downloadedText = Encoding.UTF8.GetString(downloadedBytes);
72+
Assert.AreEqual("HelloWorld", downloadedText);
73+
}
5674
}
5775
}
5876
}

0 commit comments

Comments
 (0)