Skip to content

Commit

Permalink
MongoTestBase: add proper client cleanup, some refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
Felk committed Nov 10, 2024
1 parent 594f6c1 commit ce38cc1
Showing 1 changed file with 43 additions and 42 deletions.
85 changes: 43 additions & 42 deletions tests/TPP.Persistence.MongoDB.Tests/Repos/MongoTestBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,57 +4,58 @@
using System.Threading;
using System.Threading.Tasks;
using MongoDB.Driver;
using MongoDB.Driver.Linq;
using NUnit.Framework;
using TPP.Persistence.MongoDB.Serializers;

namespace TPP.Persistence.MongoDB.Tests.Repos
namespace TPP.Persistence.MongoDB.Tests.Repos;

/// <summary>
/// Base class for tests that need to operate on an actual MongoDB server.
/// Connects to a local mongod instance running on the default port (27017).
/// Provides a CreateTemporaryDatabase method for obtaining a unique IMongoDatabase.
/// Databases created that way get cleaned up while the test class is being torn down.
/// </summary>
[Category("IntegrationTest")]
public abstract class MongoTestBase
{
/// <summary>
/// Base class for tests that need to operate on an actual MongoDB server.
/// Connects to a local mongod instance running on the default port (27017).
/// Provides a CreateTemporaryDatabase method for obtaining a unique IMongoDatabase.
/// Databases created that way get cleaned up while the test class is being torn down.
/// </summary>
[Category("IntegrationTest")]
public abstract class MongoTestBase
{
private const string ReplicaSetName = "rs0";
private static readonly Random Random = new Random();
private const string ReplicaSetName = "rs0";
private static readonly Random Random = new();

private MongoClient _client = null!;
private readonly List<string> _temporaryDatabases = new List<string>();
private MongoClient _client = null!;
private readonly List<string> _temporaryDatabases = [];

[OneTimeSetUp]
public void SetUpMongoClient()
[OneTimeSetUp]
public void SetUpMongoClient()
{
CustomSerializers.RegisterAll();
// try to connect to a mongodb running on the default port
MongoClientSettings settings = MongoClientSettings
.FromConnectionString($"mongodb://localhost:27017/?replicaSet={ReplicaSetName}");
_client = new MongoClient(settings);
bool success = _client.ListDatabaseNamesAsync(CancellationToken.None).Wait(TimeSpan.FromSeconds(5));
if (!success)
{
CustomSerializers.RegisterAll();
// try to connect to a mongodb running on the default port
MongoClientSettings settings = MongoClientSettings
.FromConnectionString($"mongodb://localhost:27017/?replicaSet={ReplicaSetName}");
_client = new MongoClient(settings);
bool success = _client.ListDatabaseNamesAsync(CancellationToken.None).Wait(TimeSpan.FromSeconds(5));
if (!success)
{
throw new AssertionException(
"Failed to connect to a local MongoDB instance running on the default port. " +
"Please start a local MongoDB instance on the default port (27017), " +
$"and make sure it is in replica set mode with a replica set named '{ReplicaSetName}'. " +
"Alternatively, skip these tests using 'dotnet test --filter TestCategory!=IntegrationTest'");
}
throw new AssertionException(
"Failed to connect to a local MongoDB instance running on the default port. " +
"Please start a local MongoDB instance on the default port (27017), " +
$"and make sure it is in replica set mode with a replica set named '{ReplicaSetName}'. " +
"Alternatively, skip these tests using 'dotnet test --filter TestCategory!=IntegrationTest'");
}
}

[OneTimeTearDown]
public void TearDownTempDatabases()
{
Task.WhenAll(_temporaryDatabases.Select(db => _client.DropDatabaseAsync(db))).Wait();
}
[OneTimeTearDown]
public void TearDownTempDatabases()
{
// ReSharper disable once AccessToDisposedClosure : task is Wait()-ed on before client gets disposed.
IEnumerable<Task> dropTasks = _temporaryDatabases.Select(db => _client.DropDatabaseAsync(db));
Task.WhenAll(dropTasks).Wait();
_client.Dispose();
}

protected IMongoDatabase CreateTemporaryDatabase()
{
string dbName = "testdb-" + Random.Next();
_temporaryDatabases.Add(dbName);
return _client.GetDatabase(dbName);
}
protected IMongoDatabase CreateTemporaryDatabase()
{
string dbName = "testdb-" + Random.Next();
_temporaryDatabases.Add(dbName);
return _client.GetDatabase(dbName);
}
}

0 comments on commit ce38cc1

Please sign in to comment.