Skip to content

Commit

Permalink
chore: upgrade to mongodb v3 (❗) (#255)
Browse files Browse the repository at this point in the history
* chore: upgrade to mongodb v3

* pr-fix: correct with new doc id serilization

* pr-fix: add space back
  • Loading branch information
stijnmoreels authored Jan 21, 2025
1 parent e8f7800 commit 4573107
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 26 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
<PackageReference Include="Azure.Identity" Version="[1.13.1,2.0.0)" />
<PackageReference Include="Azure.ResourceManager.CosmosDB" Version="[1.3.2,2.0.0)" />
<PackageReference Include="Microsoft.Azure.Cosmos" Version="[3.43.0,4.0.0)" />
<PackageReference Include="MongoDB.Driver" Version="[2.28.0,3.0.0)" />
<PackageReference Include="MongoDB.Driver" Version="[3.1.0,4.0.0)" />
</ItemGroup>

<ItemGroup>
Expand Down
12 changes: 6 additions & 6 deletions src/Arcus.Testing.Storage.Cosmos/TemporaryMongoDbCollection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ namespace Arcus.Testing
/// Represents the available options when the <see cref="TemporaryMongoDbCollection"/> is created.
/// </summary>
internal enum OnSetupMongoDbCollection { LeaveExisted = 0, CleanIfExisted, CleanIfMatched }

/// <summary>
/// Represents the available options when the <see cref="TemporaryMongoDbCollection"/> is deleted.
/// </summary>
Expand Down Expand Up @@ -88,7 +88,7 @@ public OnSetupMongoDbCollectionOptions CleanMatchingDocuments<TDocument>(FilterD

IBsonSerializerRegistry serializerRegistry = BsonSerializer.SerializerRegistry;
IBsonSerializer<TDocument> documentSerializer = serializerRegistry.GetSerializer<TDocument>();
BsonDocument doc = filter.Render(documentSerializer, serializerRegistry);
BsonDocument doc = filter.Render(new RenderArgs<TDocument>(documentSerializer, serializerRegistry));

IsMatched = Builders<BsonDocument>.Filter.Or(IsMatched, doc);
Documents = OnSetupMongoDbCollection.CleanIfMatched;
Expand Down Expand Up @@ -166,7 +166,7 @@ public OnTeardownMongoDbCollectionOptions CleanMatchingDocuments<TDocument>(Filt

IBsonSerializerRegistry serializerRegistry = BsonSerializer.SerializerRegistry;
IBsonSerializer<TDocument> documentSerializer = serializerRegistry.GetSerializer<TDocument>();
BsonDocument doc = filter.Render(documentSerializer, serializerRegistry);
BsonDocument doc = filter.Render(new RenderArgs<TDocument>(documentSerializer, serializerRegistry));

IsMatched = Builders<BsonDocument>.Filter.Or(IsMatched, doc);
Documents = OnTeardownMongoDbCollection.CleanIfMatched;
Expand Down Expand Up @@ -217,7 +217,7 @@ private TemporaryMongoDbCollection(
_database = database;
_options = options;
_logger = logger ?? NullLogger.Instance;

Name = collectionName;
}

Expand Down Expand Up @@ -268,7 +268,7 @@ public static async Task<TemporaryMongoDbCollection> CreateIfNotExistsAsync(
{
ArgumentNullException.ThrowIfNull(cosmosDbResourceId);
logger ??= NullLogger.Instance;

if (string.IsNullOrWhiteSpace(databaseName))
{
throw new ArgumentException(
Expand Down Expand Up @@ -409,7 +409,7 @@ public async ValueTask DisposeAsync()
disposables.Add(AsyncDisposable.Create(async () =>
{
_logger.LogDebug("[Test:Teardown] Delete Azure Cosmos MongoDb '{CollectionName}' collection in database '{DatabaseName}'", Name, _database.DatabaseNamespace.DatabaseName);
await _database.DropCollectionAsync(Name);
await _database.DropCollectionAsync(Name);
}));
}
else
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,14 +67,14 @@ private static async Task<MongoClient> AuthenticateMongoDbClientAsync(TestConfig
string cosmosDbName = config["Arcus:Cosmos:MongoDb:Name"];

var listConnectionStringUrl = $"https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{cosmosDbName}/listConnectionStrings?api-version=2021-04-15";

using var request = new HttpRequestMessage(HttpMethod.Post, listConnectionStringUrl);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken.Token);

using HttpResponseMessage response = await HttpClient.SendAsync(request);
string responseBody = await response.Content.ReadAsStringAsync();
var connectionStringDic = JsonSerializer.Deserialize<Dictionary<string, List<Dictionary<string, string>>>>(responseBody);

Assert.NotNull(connectionStringDic);
List<Dictionary<string, string>> connectionStrings = connectionStringDic["connectionStrings"];
Assert.NotEmpty(connectionStrings);
Expand Down Expand Up @@ -127,9 +127,9 @@ public async Task WhenCollectionDeletedAsync(string collectionName)
public async Task<BsonValue> WhenDocumentAvailableAsync<T>(string collectionName, T document)
{
IMongoCollection<BsonDocument> collection = _database.GetCollection<BsonDocument>(collectionName);

var bson = document.ToBsonDocument();

BsonClassMap classMap = BsonClassMap.LookupClassMap(typeof(T));
string elementName = classMap.IdMemberMap.ElementName;

Expand All @@ -149,7 +149,7 @@ public async Task<BsonValue> WhenDocumentAvailableAsync<T>(string collectionName
public async Task WhenDocumentDeletedAsync<T>(string collectionName, BsonValue id)
{
_logger.LogTrace("[Test] delete MongoDb document '{DocId}' in collection '{CollectionName}' outside test fixture's scope", id, collectionName);

IMongoCollection<T> collection = _database.GetCollection<T>(collectionName);
FilterDefinition<T> filter = CreateIdFilter<T>(id);

Expand All @@ -162,7 +162,7 @@ public async Task WhenDocumentDeletedAsync<T>(string collectionName, BsonValue i
public async Task ShouldStoreCollectionAsync(string collectionName)
{
Assert.True(
await StoresCollectionNameAsync(collectionName),
await StoresCollectionNameAsync(collectionName),
$"temporary mongo db collection '{collectionName}' should be available");
}

Expand All @@ -172,7 +172,7 @@ await StoresCollectionNameAsync(collectionName),
public async Task ShouldNotStoreCollectionAsync(string collectionName)
{
Assert.False(
await StoresCollectionNameAsync(collectionName),
await StoresCollectionNameAsync(collectionName),
$"temporary mongo db collection '{collectionName}' should not be available");
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using Bogus;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson.Serialization.IdGenerators;
using Xunit;
using Xunit.Abstractions;

Expand Down Expand Up @@ -52,7 +53,7 @@ public async Task CreateTempMongoDbDocument_OnExistingDocumentId_SucceedsByRever
BsonValue id = await context.WhenDocumentAvailableAsync(collectionName, original);

Product replacement = CreateProduct();
replacement.Id = (ObjectId) id;
replacement.Id = (ObjectId)id;

TemporaryMongoDbDocument temp = await WhenTempDocumentCreatedAsync(collectionName, replacement);
await context.ShouldStoreDocumentAsync<Product>(collectionName, id, stored => AssertProduct(replacement, stored));
Expand All @@ -64,7 +65,7 @@ public async Task CreateTempMongoDbDocument_OnExistingDocumentId_SucceedsByRever
await context.ShouldStoreDocumentAsync<Product>(collectionName, id, stored => AssertProduct(original, stored));
}

private async Task<TemporaryMongoDbDocument> WhenTempDocumentCreatedAsync<TDoc>(string collectionName, TDoc doc)
private async Task<TemporaryMongoDbDocument> WhenTempDocumentCreatedAsync<TDoc>(string collectionName, TDoc doc)
where TDoc : class
{
return await TemporaryMongoDbDocument.InsertIfNotExistsAsync(
Expand Down Expand Up @@ -108,32 +109,32 @@ public async Task CreateTempMongoDbDocument_WithOtherThanObjectIdPropertyType_Su
await using MongoDbTestContext context = await GivenCosmosMongoDbAsync();

string collectionName = await context.WhenCollectionNameAvailableAsync();
var original = DocWithIntId.Generate();
var original = DocWithStringId.Generate();
BsonValue id = await context.WhenDocumentAvailableAsync(collectionName, original);

var replacement = DocWithIntId.Generate();
replacement.Id = (Guid) id;
var replacement = DocWithStringId.Generate();
replacement.Id = (string)id;

TemporaryMongoDbDocument temp = await WhenTempDocumentCreatedAsync(collectionName, replacement);
await context.ShouldStoreDocumentAsync<DocWithIntId>(collectionName, id, stored => Assert.Equal(replacement.Name, stored.Name));
await context.ShouldStoreDocumentAsync<DocWithStringId>(collectionName, id, stored => Assert.Equal(replacement.Name, stored.Name));

// Act
await temp.DisposeAsync();

// Assert
await context.ShouldStoreDocumentAsync<DocWithIntId>(collectionName, id, stored => Assert.Equal(original.Name, stored.Name));
await context.ShouldStoreDocumentAsync<DocWithStringId>(collectionName, id, stored => Assert.Equal(original.Name, stored.Name));
}

public class DocWithIntId
public class DocWithStringId
{
[BsonId]
public Guid Id { get; set; }
[BsonId(IdGenerator = typeof(StringObjectIdGenerator))]
public string Id { get; set; }

public string Name { get; set; }

public static DocWithIntId Generate()
public static DocWithStringId Generate()
{
return new DocWithIntId { Name = Bogus.Random.Word() };
return new DocWithStringId { Name = Bogus.Random.Word() };
}
}

Expand Down

0 comments on commit 4573107

Please sign in to comment.