Compare commits

...

162 Commits

Author SHA1 Message Date
Alexandre Spieser a54b702841 update driver to 2.28 2024-11-23 16:01:33 +00:00
Alexandre SPIESER 9c48653dc6 Merge pull request #57 from mrtaikandi/mongodriver-2.25
Upgrade MongoDb driver and its related packages to 2.25.0
2024-05-28 15:16:53 +01:00
Mohammadreza Taikandi b083988509 Upgrade MongoDb driver and its related packages to 2.25.0 2024-05-28 15:07:12 +01:00
Alexandre SPIESER 7bd356c7da Merge pull request #56 from mrtaikandi/mongodriver-2.20
Upgrade to MongoDb Driver 2.20 and use GuidRepresentationMode.V3 as the default representation.
This potentially can cause a breaking change to the package consumer, but the behaviour can be set to V2 by overriding the void SetGuidRepresentation(GuidRepresentation guidRepresentation) method.
GuidRepresentation and GuidRepresentationMode will be removed in the next major release of the MongoDB Driver:
https://www.mongodb.com/community/forums/t/c-guid-style-dont-work/126901/2
What's new in 2.20 and 2.19:
https://www.mongodb.com/docs/drivers/csharp/current/whats-new/#std-label-csharp-whats-new
2023-08-11 11:07:13 +01:00
Mohammadreza Taikandi f59cccb3d9 Upgrade to MongoDb Driver 2.20 and use GuidRepresentationMode.V3 as default representation. 2023-08-07 11:34:35 +01:00
Alexandre Spieser 710b7b992f upgrade to MongoDb Driver 2.18 - 2.19 seems to have some broken some tests, investigating. 2023-08-02 22:56:58 +01:00
Alexandre SPIESER 9812bded04 Merge pull request #55 from blacktau/feature/cancellation-token-2
Feature/cancellation token 2
All comments addressed. Thanks Sean!
2023-07-22 12:52:34 +01:00
Sean Garrett 3b6b08a9ad Merge branch 'feature/cancellation-token-2' of github.com:blacktau/mongodb-generic-repository into feature/cancellation-token-2 2023-07-19 11:22:11 +01:00
Sean Garrett 5ff1c21780 removed redundant ToList() calls and added line break after region 2023-07-19 11:21:46 +01:00
Alexandre SPIESER 8f2f92f9d3 remove dotnet-xunit bet nuget package, update xunit packages 2023-07-18 23:01:21 +01:00
Sean Garrett 091ee9c204 removing comment 2023-07-18 08:56:03 +01:00
Sean Garrett 7bbbd7bd71 reverting target frameworks change 2023-07-18 08:55:06 +01:00
Sean Garrett cb55d3bffa removing empty test classes 2023-07-17 18:37:17 +01:00
Sean Garrett 67784e64ee getandupdate and getpaginated 2023-07-06 19:15:10 +01:00
Sean Garrett 3a7b24262e unit tests for repo update methods 2023-07-06 18:32:00 +01:00
Sean Garrett 26b71ff76e reformatting 2023-07-06 13:00:55 +01:00
Sean Garrett c70727212e cancellation tokens on repository update methods 2023-07-06 11:49:45 +01:00
Sean Garrett be58460bf1 tokens for updater and unit tests 2023-07-05 20:20:08 +01:00
Sean Garrett dc7a4dc67b tests for readonly repositories 2023-07-04 22:38:01 +01:00
Sean Garrett b09b359867 rest of the unit tests for readonly repo 2023-07-02 17:54:30 +01:00
Sean Garrett f9ea630611 unit tests for keyed readonly repo 2023-07-02 14:10:55 +01:00
Sean Garrett 40e287418b read only and tests 2023-07-01 22:27:11 +01:00
Sean Garrett 240b61d1d2 tests for getMaxVValue and GetMinValue 2023-06-25 22:27:40 +01:00
Sean Garrett f7ba046f20 Reader GetAll, GetByMin and getByMax test 2023-06-25 21:13:17 +01:00
Sean Garrett 0699130733 Reader GetAll, GetByMin and getByMax test 2023-06-25 21:12:52 +01:00
Sean Garrett 03b8b273f8 any and count tests 2023-06-25 16:55:44 +01:00
Sean Garrett dee1376a41 MongodbReader cancellation tokens and some unit tests 2023-06-25 15:03:52 +01:00
Sean Garrett 11ce19cb5c Cancellation tokens for CombinedTextIndex and DropIndex 2023-06-24 19:10:12 +01:00
Sean Garrett 387bf6beec Cancellation tokens on Create Hashed Index 2023-06-24 18:17:55 +01:00
Sean Garrett 807a4b17ce Ascending index tests and Descending Index and tests 2023-06-24 17:08:26 +01:00
Sean Garrett 251ffdacfa unit tests for Create and Get Indexes 2023-06-24 14:48:35 +01:00
Sean Garrett aaf80a7ae2 Cancellation Tokens for Text Index and GetIndex 2023-06-24 12:41:17 +01:00
Sean Garrett b7b23e7b92 added tests for index handler 2023-06-22 22:06:27 +01:00
Sean Garrett 25766febd4 Index tests 2023-06-20 22:06:30 +01:00
Sean Garrett ed2eddd33e unit tests for add 2023-06-18 18:37:30 +01:00
Sean Garrett 39e93dc968 added cancellation tokens to 'Create' methods 2023-06-18 18:08:50 +01:00
Sean Garrett cae2b01dd9 removing ignored file 2023-06-17 23:46:02 +01:00
Sean Garrett 86d9ea6990 added unit tests for MongoDBCreator and missing CancellationTokens 2023-06-17 23:42:10 +01:00
Sean Garrett 1b8f795e00 added cancellation tokens to sync deletes and added more unit tests 2023-06-17 17:49:49 +01:00
Sean Garrett b285c7d919 reverting verify change 2023-06-16 22:41:45 +01:00
Sean Garrett 23780697fb added some missing cancellation tokens and fixed incorrect tests 2023-06-16 22:40:46 +01:00
Sean Garrett f09cfc53c2 Delete unit tests for the repos 2023-06-16 17:20:04 +01:00
Sean Garrett c6545b9448 keyed Delete unit tests 2023-06-16 11:51:40 +01:00
Sean Garrett 54e756c695 unit tests 2023-06-15 21:56:47 +01:00
Sean Garrett 0cf6a7e5d3 added overloads for delete 2023-06-15 21:35:51 +01:00
Sean Garrett e23f659ffe removing volatile 2023-06-15 18:32:12 +01:00
Sean Garrett 02b9385fd8 fixed various warnings 2023-06-11 20:23:44 +01:00
Sean Garrett 14e261261c interfaces to seperate files 2023-06-11 18:39:22 +01:00
Alexandre SPIESER d166feb5d6 Merge pull request #46 from miszu/bump-mongodb-driver-to-2.15
Bumped mongodb.driver to 2.15
2022-08-22 18:19:01 +01:00
Michał Żołnieruk 885507274d Bumped mongodb.driver to 2.15 2022-04-04 15:51:51 +02:00
Alexandre SPIESER 52390fad25 Merge pull request #43 from khanhna/feature/read_process_integration_test
Add integration test for native read filter operations
2022-01-11 14:05:52 +00:00
Khanh Nguyen f888d5996b Add integration test for native read filter operations 2021-12-12 11:02:17 +07:00
Alexandre SPIESER f74254b411 Merge pull request #42 from khanhna/feature/read_process_added
Add read operation support for filter definition
2021-12-06 19:14:55 +00:00
Khanh Nguyen An c14ceffe4f Add read operation support for filter definition 2021-10-26 18:14:42 +07:00
Alexandre SPIESER dc196b24f7 Upgraded MongoDB.Driver to 2.13.2, move target framework of CoreIntegrationTests to netcoreapp2.1 2021-10-13 22:52:00 +01:00
Alexandre SPIESER fe02d871f3 Merge branch 'alex/CancellationTokenWork' 2021-03-15 11:39:18 +00:00
Alexandre SPIESER ff94611ee9 remove legacy stuff, bump to version 1.4.7 after missed cancellation token mapping in AddOneAsync. 2021-03-15 11:38:37 +00:00
Alexandre SPIESER 71b64c84a0 Merge pull request #39 from alexandre-spieser/alex/CancellationTokenWork
Alex/cancellation token work
2021-03-15 11:15:00 +00:00
Alexandre SPIESER 5f6e015bf2 fix mistake: missing cancellation token 2021-03-15 11:07:35 +00:00
Alexandre SPIESER 6d8e358ccc reference package in tests 2021-03-15 09:45:15 +00:00
Alexandre SPIESER 76a1aab671 pushed cancellation token changes 2021-03-15 08:03:50 +00:00
Alexandre SPIESER eebdc89575 adding cancellation token 2021-03-12 10:13:28 +00:00
Alexandre SPIESER ee4950c5d4 Merge branch 'master' into alex/UpdateMany 2021-03-10 08:45:10 +00:00
Alexandre SPIESER 658c753989 Added cancellation tokens (ongoing) 2021-03-10 08:44:50 +00:00
Alexandre SPIESER 0e8d629a8f Update README.md 2020-06-09 17:18:43 +01:00
Alexandre SPIESER ba3f876f95 Merge pull request #35 from alexandre-spieser/alex/UpdateMany
remove default option: IsUpset = true in update methods, to avoid une…
2020-06-09 09:02:31 +01:00
Alexandre SPIESER e4a36e5c60 remove default option: IsUpset = true in update methods, to avoid unexpected document insertions. 2020-06-09 09:01:53 +01:00
Alexandre SPIESER 592c30ed2c Merge pull request #34 from alexandre-spieser/alex/UpdateMany
Alex/update many
2020-06-06 12:16:58 +01:00
Alexandre SPIESER 83f1d2c7a6 nuget package works locally 2020-06-06 12:06:28 +01:00
Alexandre SPIESER ab294d1a5d remove ncrunch noise 2020-06-06 11:31:11 +01:00
Alexandre SPIESER dd8cbe3da7 Merge branch 'master' into alex/UpdateMany 2020-06-06 11:29:31 +01:00
Alexandre SPIESER 0844c51566 update many implementation, with tests 2020-06-06 11:28:46 +01:00
Alexandre SPIESER 601c0fd02d Update README.md 2020-06-06 08:31:35 +01:00
Alexandre SPIESER 91d15312e6 Update README.md 2020-06-05 07:26:28 +01:00
Alexandre SPIESER 54b2a63a8e Update README.md 2020-05-06 08:11:31 +01:00
Alexandre SPIESER dbb27aad39 Update README.md 2020-04-22 19:18:18 +01:00
Alexandre SPIESER afd0308849 Update README.md 2020-04-22 19:16:57 +01:00
Alexandre SPIESER 9cb35c5881 remove packaged dependencies 2020-02-05 21:37:44 +00:00
Alexandre SPIESER c5390214eb updated driver and test suite 2019-11-18 22:38:34 +00:00
Alexandre SPIESER ac1fd709a6 Merge pull request #26 from LeEmo86/upgrade-mongodbdriver
Updated the mongodb driver
2019-11-18 21:52:50 +00:00
Liam Flanagan f6b0aa274b Updated the mongodb driver 2019-11-18 19:20:57 +00:00
Alexandre SPIESER 7a82a281fb Merge pull request #23 from DanielGasson/master
Allow initialisation of MongoDbContext with connection string only
2019-06-18 21:50:50 +01:00
Daniel Gasson dca01b184c Allow initialisation of MongoDbContext with connection string only 2019-06-18 11:33:26 +01:00
Alexandre SPIESER b1cda2ac50 adding client session to mongodb updater methods 2019-05-18 19:49:44 +01:00
Alexandre SPIESER 8d6b796e7f Merge pull request #22 from alexandre-spieser/alex/refactorForKeyTypeRepo
1.4.0 release
2019-04-18 08:22:35 +01:00
Alexandre SPIESER 1a7763a312 1.4.0 release 2019-04-18 08:21:18 +01:00
Alexandre SPIESER 77cc85574c Update BaseMongoRepository.TKey.Update.cs 2019-04-17 19:08:13 +01:00
Alexandre SPIESER 846bb16730 Update BaseMongoRepository.TKey.Index.cs 2019-04-17 19:05:17 +01:00
Alexandre SPIESER 5e4cbfa1b3 Update BaseMongoRepository.TKey.Delete.cs 2019-04-17 19:04:38 +01:00
Alexandre SPIESER 804dc18c4f Update BaseMongoRepository.TKey.Create.cs 2019-04-17 19:03:59 +01:00
Alexandre SPIESER 182ee0a335 Update BaseMongoRepository.Update.cs 2019-04-17 19:02:57 +01:00
Alexandre SPIESER bd662d25d6 Update BaseMongoRepository.Index.cs 2019-04-17 19:00:33 +01:00
Alexandre SPIESER 6c8d4bdafb Update BaseMongoRepository.Delete.cs 2019-04-17 18:59:27 +01:00
Alexandre SPIESER 4d94a1b436 Update BaseMongoRepository.Create.cs 2019-04-17 18:58:47 +01:00
Alexandre SPIESER d91a644b4a Update README.md 2019-04-15 23:58:44 +01:00
Alexandre SPIESER 9d1950e9c7 Update README.md 2019-04-15 23:58:13 +01:00
Alexandre SPIESER 67d0a4c8a3 Update README.md 2019-04-15 00:48:19 +01:00
Alexandre SPIESER 1826668cea Update README.md 2019-04-15 00:47:06 +01:00
Alexandre SPIESER b855677efd Merge pull request #20 from alexandre-spieser/alex/refactorForKeyTypeRepo
added test suite for BaseMongoRepository<TKey>
2019-04-15 00:26:52 +01:00
Alexandre SPIESER 530309e9fc added test suite for BaseMongoRepository<TKey> 2019-04-15 00:26:10 +01:00
Alexandre SPIESER 69ad94e4a3 Merge pull request #19 from alexandre-spieser/alex/refactorForKeyTypeRepo
Alex/refactor for key type repo
2019-04-14 22:48:59 +01:00
Alexandre SPIESER baaf2b5ee9 tests now full clear the mongo collections / added GetSortedPaginatedAsync + tests 2019-04-14 22:47:06 +01:00
Alexandre SPIESER d2df667b3f added objectid tests 2019-04-14 20:18:37 +01:00
Alexandre SPIESER 8ccced66ea adding group by test 2019-04-14 20:07:56 +01:00
Alexandre SPIESER c92a126ecc Merge pull request #18 from alexandre-spieser/alex/refactorForKeyTypeRepo
Alex/refactor for key type repo
2019-04-14 19:36:44 +01:00
Alexandre SPIESER 2207f2f1a1 rename after full refactor 2019-04-14 19:31:28 +01:00
Alexandre SPIESER 0626292d09 fixed some tests 2019-04-14 18:10:45 +01:00
Alexandre SPIESER 29f01d2dab better segregation of concern and interfaces. 2019-04-14 17:58:31 +01:00
Alexandre SPIESER a7391e06f8 first step to split function into separate classes for better reuse and easier maintenance. 2019-04-11 23:59:34 +01:00
Alexandre SPIESER 43677b72a1 Merge pull request #16 from alexandre-spieser/alex/sum
Alex/sum
2019-04-10 23:59:11 +01:00
Alexandre SPIESER 2f29efafe3 SumByDecimal() test 2019-04-10 23:57:52 +01:00
Alexandre SPIESER d2f465b063 reorg + inheritance setup, using interface segregation to split concern / exposure of <TDocument,TKey> methods. 2019-04-10 23:48:44 +01:00
Alexandre SPIESER 75b894cb2a ran tests + removed obsolete methods 2019-04-10 22:07:15 +01:00
Alexandre SPIESER ba723be738 adding Key typed base repo functionality 2019-04-04 23:45:07 +01:00
Alexandre SPIESER f773e599d0 some good progress on refactoring into the KeyTyped repo for read only functionality 2019-04-04 22:48:09 +01:00
Alexandre SPIESER 17653b05f7 Update README.md
updated copyright year
2019-03-22 18:27:46 +00:00
Alexandre SPIESER 69903fd69b Merge branch 'master' into alex/sum 2019-02-10 17:00:23 +00:00
Alexandre SPIESER 9edd7e97fe moving TKEY related methods to there own partial class in the readonly repo 2019-02-07 08:48:36 +00:00
Alexandre SPIESER b77978e57a introucting KeyTypedReadOnlyMongoRepository 2019-02-07 08:47:27 +00:00
Alexandre SPIESER 648b57612d Merge pull request #14 from alexandre-spieser/alex/sum
Alex/sum
2019-02-04 23:13:28 +00:00
Alexandre SPIESER 4ac0ffe91c added tests for the sumbyasync methods 2019-02-04 23:11:36 +00:00
Alexandre SPIESER eaa90d67f5 sum for decimal fields, untested. 2019-01-02 23:43:37 +00:00
Alexandre SPIESER 2d866d966c Update MongoDbContext.cs
Added a MongoDbContext ctor that takes a MongoClient for custom setup.
2018-12-04 12:58:44 +00:00
Alexandre SPIESER ffc7e65b7b Update README.md 2018-10-07 19:46:34 +01:00
alexandre-spieser 0cf24b1dcf integration tested index management functionality 2018-10-07 19:05:59 +01:00
alexandre-spieser fd8f98e375 adding more tests 2018-10-01 22:31:08 +01:00
alexandre-spieser fa6687c084 fixed test by adding semaphores. Also reduced collections name to avoid hitting the 127 byte limit regarding index names. 2018-09-30 19:26:25 +01:00
alexandre-spieser 0b939592ba Implementation of index management.CreateTextIndexWithOptionAsync is failing. 2018-09-30 19:07:38 +01:00
alexandre-spieser ad18170804 work on indexes continued 2018-09-17 22:39:14 +01:00
alexandre-spieser 099e16a88c prep work on indexes methods 2018-09-17 08:41:36 +01:00
alexandre-spieser e41a73f745 1.3.7 release 2018-09-09 18:55:53 +01:00
alexandre-spieser 526adf0a23 remove unused using statements 2018-09-09 13:31:42 +01:00
alexandre-spieser db4061dc3c cleanup. Removing redundant GetCollection and Drop collection method, removed static constructor, added a virtual initialization method. 2018-09-09 13:05:45 +01:00
alexandre-spieser 72ea6e7999 clean up + full support for bulk insertion and deletion of documents of the same type but with different partitionkey values 2018-09-09 12:14:43 +01:00
alexandre-spieser 7f126a098d support insertion of documents with different PartitionKey values 2018-09-03 21:46:30 +01:00
alexandre-spieser 456af09a84 + Upgraded packages
+ Added GetByMax, GetByMaxAsync, GetByMin, GetByMinAsync, GetMaxValue and GetMaxValueAsync Methods (GetMinValue and GetMinValueAsync will come in another PR)
+ Added tests
2018-08-05 21:10:41 +01:00
Alexandre SPIESER f0af32adca Update copyright year to 2018 2018-05-11 22:53:43 +01:00
alexandre-spieser 345fca2e6e Added summary where needed. 2018-03-06 23:11:33 +00:00
alexandre-spieser 57d332ef2a Add support for ObjectId type for the Id of the document. 2018-03-05 23:07:56 +00:00
Alexandre SPIESER 2f6515a809 Merge pull request #3 from alexandre-spieser/add-license-1
Create LICENSE
2018-02-24 12:22:58 +00:00
Alexandre SPIESER 82dc2f2024 Create LICENSE 2018-02-24 12:22:49 +00:00
Alexandre SPIESER bc992e8c61 Update README.md 2018-02-16 15:11:09 +00:00
Alexandre SPIESER 47e85f1760 Update README.md 2018-02-16 15:10:18 +00:00
alexandre-spieser 6f5eb71dad Prepare for 1.3.5 release. 2018-02-10 18:32:45 +00:00
alexandre-spieser ed0d206a97 Merge branch 'master' of https://github.com/alexandre-spieser/mongodb-generic-repository 2018-02-10 18:17:42 +00:00
alexandre-spieser 40ff874cf6 CoreIntegrationTests refactored and passing. 2018-02-10 18:16:14 +00:00
alexandre-spieser 9fc74fc28e cleanup redundant tests. 2018-02-10 16:46:59 +00:00
alexandre-spieser 5270271008 Continues refactoring tests, added overload for UpdateOne and UpdateOneAsync so that we can pass a LINQ query to the method. 2018-02-10 16:38:47 +00:00
alexandre-spieser bf2119432e Test refactoring, continued. 2018-02-10 14:13:10 +00:00
Alexandre SPIESER e581586161 Update README.md 2018-02-07 12:59:13 +00:00
alexandre-spieser 1a83abd25f refactoring test classes. 2018-02-05 23:48:11 +00:00
Alexandre SPIESER 03b0e4265b Merge pull request #2 from Etchelon/master
Add CollectionName attribute for allowing explicit naming of collections
2018-02-05 20:32:50 +00:00
Andrea Bertoldo c117bf2a7f Add CollectionName attribute for allowing explicit naming of collections 2018-02-05 14:48:26 +01:00
Alexandre SPIESER c50e4d086e Update README.md 2018-01-27 16:44:03 +00:00
alexandre-spieser 3a42a1c574 Upgraded mongodb driver + new package version released. 2018-01-27 15:58:16 +00:00
alexandre-spieser 67e7318021 updating mongodb driver to version 2.5.0 for MongoDB 3.6 support. 2018-01-27 14:49:13 +00:00
alexandre-spieser 29012d1e52 nuget package update 2018-01-27 14:41:39 +00:00
alexandre-spieser e15c1e4ad2 Refactoring to have a greater separation of concern. 2017-12-06 23:20:53 +00:00
alexandre-spieser 3d104764ae added dependencies 2017-11-19 19:05:22 +00:00
alexandre-spieser 3af68c06db Merge branch 'master' of https://github.com/alexandre-spieser/mongodb-generic-repository 2017-11-17 18:39:38 +00:00
alexandre-spieser a3ae98d077 added comments and updated nuspec 2017-11-17 18:39:34 +00:00
Alexandre SPIESER aff276f9e3 Update README.md 2017-11-16 17:14:40 +00:00
296 changed files with 61797 additions and 15920 deletions
Binary file not shown.
File diff suppressed because it is too large Load Diff
+22
View File
@@ -0,0 +1,22 @@
using CoreIntegrationTests.Infrastructure;
using MongoDB.Bson;
namespace CoreIntegrationTests
{
public class CoreObjectIdTestDocument : TestDoc<ObjectId>
{
}
public class CRUDObjectIdTests : MongoDbTKeyDocumentTestBase<CoreObjectIdTestDocument, ObjectId>
{
public CRUDObjectIdTests(MongoDbTestFixture<CoreObjectIdTestDocument, ObjectId> fixture) : base(fixture)
{
}
public override string GetClassName()
{
return "CRUDObjectIdTests";
}
}
}
@@ -0,0 +1,31 @@
using CoreIntegrationTests.Infrastructure;
using MongoDbGenericRepository.Attributes;
using MongoDbGenericRepository.Models;
using System;
namespace CoreIntegrationTests
{
[CollectionName("CoreTestingCNameAttrPart")]
public class CorePartitionedCollectionNameDoc : TestDoc, IPartitionedDocument
{
public CorePartitionedCollectionNameDoc()
{
PartitionKey = "CoreTestPartitionKeyCollectionName";
}
public string PartitionKey { get; set; }
}
public class CRUDPartitionedCollectionNameAttributeTests : MongoDbDocumentTestBase<CorePartitionedCollectionNameDoc>
{
public CRUDPartitionedCollectionNameAttributeTests(MongoDbTestFixture<CorePartitionedCollectionNameDoc, Guid> fixture) : base(fixture)
{
}
public override string GetClassName()
{
return "CoreCRUDPartitionedCollectionNameAttributeTests";
}
}
}
@@ -0,0 +1,28 @@
using CoreIntegrationTests.Infrastructure;
using MongoDbGenericRepository.Models;
using System;
namespace CoreIntegrationTests
{
public class CorePartitionedDoc : TestDoc, IPartitionedDocument
{
public CorePartitionedDoc()
{
PartitionKey = "CoreTestPartitionKey";
}
public string PartitionKey { get; set; }
}
public class CRUDPartitionedTests : MongoDbDocumentTestBase<CorePartitionedDoc>
{
public CRUDPartitionedTests(MongoDbTestFixture<CorePartitionedDoc, Guid> fixture) : base(fixture)
{
}
public override string GetClassName()
{
return "CoreCRUDPartitionedTests";
}
}
}
@@ -0,0 +1,65 @@
using CoreIntegrationTests.Infrastructure;
using MongoDB.Bson;
using MongoDbGenericRepository.Attributes;
using MongoDbGenericRepository.Models;
using System;
namespace CoreIntegrationTests
{
#region Guid Type
[CollectionName("TestingCNameAttrPartTKey")]
public class CoreTKeyPartitionedCollectionNameDoc : TestDoc<Guid>, IPartitionedDocument
{
public CoreTKeyPartitionedCollectionNameDoc()
{
PartitionKey = "CoreTestPartitionKey";
}
public string PartitionKey { get; set; }
}
public class CRUDTKeyPartitionedCollectionNameAttributeTests : MongoDbTKeyDocumentTestBase<CoreTKeyPartitionedCollectionNameDoc, Guid>
{
public CRUDTKeyPartitionedCollectionNameAttributeTests(MongoDbTestFixture<CoreTKeyPartitionedCollectionNameDoc, Guid> fixture) : base(fixture)
{
}
public override string GetClassName()
{
return "CoreCRUDTKeyPartitionedCollectionNameAttributeTests";
}
}
#endregion Guid Type
#region ObjectId Type
[CollectionName("TestingCNameAttrPartObjectId")]
public class CoreObjectIdPartitionedCollectionNameDoc : TestDoc<ObjectId>, IPartitionedDocument
{
public CoreObjectIdPartitionedCollectionNameDoc()
{
PartitionKey = "CoreTestPartitionKeyObjectId";
}
public string PartitionKey { get; set; }
}
public class CRUDObjectIdPartitionedCollectionNameAttributeTests : MongoDbTKeyDocumentTestBase<CoreObjectIdPartitionedCollectionNameDoc, ObjectId>
{
public CRUDObjectIdPartitionedCollectionNameAttributeTests(MongoDbTestFixture<CoreObjectIdPartitionedCollectionNameDoc, ObjectId> fixture) : base(fixture)
{
}
public override string GetClassName()
{
return "CoreCRUDTKeyPartitionedCollectionNameAttributeTests";
}
}
#endregion ObjectId Type
}
@@ -0,0 +1,28 @@
using CoreIntegrationTests.Infrastructure;
using MongoDbGenericRepository.Models;
using System;
namespace CoreIntegrationTests
{
public class CorePartitionedTKeyTestDocument : TestDoc<Guid>, IPartitionedDocument
{
public CorePartitionedTKeyTestDocument()
{
PartitionKey = "CoreTestPartitionKey";
}
public string PartitionKey { get; set; }
}
public class CRUDTKeyPartitionedTests : MongoDbTKeyDocumentTestBase<CorePartitionedTKeyTestDocument, Guid>
{
public CRUDTKeyPartitionedTests(MongoDbTestFixture<CorePartitionedTKeyTestDocument, Guid> fixture) : base(fixture)
{
}
public override string GetClassName()
{
return "CoreCRUDTKeyPartitionedTests";
}
}
}
+22
View File
@@ -0,0 +1,22 @@
using CoreIntegrationTests.Infrastructure;
using System;
namespace CoreIntegrationTests
{
public class CoreTKeyTestDocument : TestDoc<Guid>
{
}
public class CRUDTKeyTests : MongoDbTKeyDocumentTestBase<CoreTKeyTestDocument, Guid>
{
public CRUDTKeyTests(MongoDbTestFixture<CoreTKeyTestDocument, Guid> fixture) : base(fixture)
{
}
public override string GetClassName()
{
return "CreateTKeyTests";
}
}
}
+21
View File
@@ -0,0 +1,21 @@
using CoreIntegrationTests.Infrastructure;
using System;
namespace CoreIntegrationTests
{
public class CoreTestDocument : TestDoc
{
}
public class CRUDTests : MongoDbDocumentTestBase<CoreTestDocument>
{
public CRUDTests(MongoDbTestFixture<CoreTestDocument, Guid> fixture) : base(fixture)
{
}
public override string GetClassName()
{
return "CRUDTests";
}
}
}
@@ -1,22 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Identity" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Identity.Stores" Version="2.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.5.0-preview-20170810-02" />
<PackageReference Include="MongoDB.Driver" Version="2.4.4" />
<PackageReference Include="xunit" Version="2.3.0" />
<PackageReference Include="xunit.runner.console" Version="2.3.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.3.0" />
<DotNetCliToolReference Include="dotnet-xunit" Version="2.3.0-beta4-build3742" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\MongoDbGenericRepository\MongoDbGenericRepository.csproj" />
<PackageReference Include="Microsoft.AspNetCore.Identity" Version="2.1.2" />
<PackageReference Include="Microsoft.Extensions.Identity.Stores" Version="2.1.2" />
<PackageReference Include="MongoDB.Driver" Version="2.28.0" />
<PackageReference Include="xunit" Version="2.5.0" />
<PackageReference Include="xunit.runner.console" Version="2.5.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.6.3" />
</ItemGroup>
<ItemGroup>
@@ -25,4 +26,8 @@
</None>
</ItemGroup>
</Project>
<ItemGroup>
<ProjectReference Include="..\MongoDbGenericRepository\MongoDbGenericRepository.csproj" />
</ItemGroup>
</Project>
@@ -1,67 +0,0 @@
using CoreIntegrationTests.Infrastructure;
using MongoDbGenericRepository.Models;
using Xunit;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace CoreIntegrationTests
{
public class CreateTestsPartitionedDocument : PartitionedDocument
{
public CreateTestsPartitionedDocument() : base("TestPartitionKey")
{
Version = 1;
}
public string SomeContent { get; set; }
}
public class CreatePartitionedTests : BaseMongoDbRepositoryTests<CreateTestsPartitionedDocument>
{
private void PartitionedAddOne()
{
// Arrange
var document = new CreateTestsPartitionedDocument();
// Act
SUT.AddOne(document);
// Assert
long count = SUT.Count<CreateTestsPartitionedDocument>(e => e.Id == document.Id, PartitionKey);
Xunit.Assert.Equal(1, count);
}
[Fact]
public async Task PartitionedAddOneAsync()
{
// Arrange
var document = new CreateTestsPartitionedDocument();
// Act
await SUT.AddOneAsync(document);
// Assert
long count = SUT.Count<CreateTestsPartitionedDocument>(e => e.Id == document.Id, PartitionKey);
Assert.Equal(1, count);
}
[Fact]
public void PartitionedAddMany()
{
// Arrange
var documents = new List<CreateTestsPartitionedDocument> { new CreateTestsPartitionedDocument(), new CreateTestsPartitionedDocument() };
// Act
SUT.AddMany(documents);
// Assert
long count = SUT.Count<CreateTestsPartitionedDocument>(e => e.Id == documents[0].Id || e.Id == documents[1].Id, PartitionKey);
Assert.Equal(2, count);
}
[Fact]
public async Task PartitionedAddManyAsync()
{
// Arrange
var documents = new List<CreateTestsPartitionedDocument> { new CreateTestsPartitionedDocument(), new CreateTestsPartitionedDocument() };
// Act
await SUT.AddManyAsync(documents);
// Assert
long count = SUT.Count<CreateTestsPartitionedDocument>(e => e.Id == documents[0].Id || e.Id == documents[1].Id, PartitionKey);
Assert.Equal(2, count);
}
}
}
-68
View File
@@ -1,68 +0,0 @@
using CoreIntegrationTests.Infrastructure;
using MongoDbGenericRepository.Models;
using Xunit;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace CoreIntegrationTests
{
public class CreateTestsDocument : Document
{
public CreateTestsDocument()
{
Version = 2;
}
public string SomeContent { get; set; }
}
public class CreateTests : BaseMongoDbRepositoryTests<CreateTestsDocument>
{
[Fact]
public void AddOne()
{
// Arrange
var document = new CreateTestsDocument();
// Act
SUT.AddOne(document);
// Assert
long count = SUT.Count<CreateTestsDocument>(e => e.Id == document.Id);
Assert.Equal(1, count);
}
[Fact]
public async Task AddOneAsync()
{
// Arrange
var document = new CreateTestsDocument();
// Act
await SUT.AddOneAsync(document);
// Assert
long count = SUT.Count<CreateTestsDocument>(e => e.Id == document.Id);
Assert.Equal(1, count);
}
[Fact]
public void AddMany()
{
// Arrange
var documents = new List<CreateTestsDocument> { new CreateTestsDocument(), new CreateTestsDocument() };
// Act
SUT.AddMany(documents);
// Assert
long count = SUT.Count<CreateTestsDocument>(e => e.Id == documents[0].Id || e.Id == documents[1].Id);
Assert.Equal(2, count);
}
[Fact]
public async Task AddManyAsync()
{
// Arrange
var documents = new List<CreateTestsDocument> { new CreateTestsDocument(), new CreateTestsDocument() };
// Act
await SUT.AddManyAsync(documents);
// Assert
long count = SUT.Count<CreateTestsDocument>(e => e.Id == documents[0].Id || e.Id == documents[1].Id);
Assert.Equal(2, count);
}
}
}
@@ -1,129 +0,0 @@
using CoreIntegrationTests.Infrastructure;
using MongoDbGenericRepository.Models;
using Xunit;
using System.Threading.Tasks;
namespace CoreIntegrationTests
{
public class DeleteTestsPartitionedDocument : PartitionedDocument
{
public DeleteTestsPartitionedDocument() : base("TestPartitionKey")
{
Version = 1;
}
public string SomeContent { get; set; }
}
public class DeletePartitionedTests : BaseMongoDbRepositoryTests<DeleteTestsPartitionedDocument>
{
[Fact]
public void PartitionedDeleteOne()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = SUT.DeleteOne(document);
// Assert
Assert.Equal(1, result);
Assert.False(SUT.Any<DeleteTestsPartitionedDocument>(e => e.Id == document.Id, PartitionKey));
}
[Fact]
public void PartitionedDeleteOneLinq()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = SUT.DeleteOne<DeleteTestsPartitionedDocument>(e => e.Id == document.Id, PartitionKey);
// Assert
Assert.Equal(1, result);
Assert.False(SUT.Any<DeleteTestsPartitionedDocument>(e => e.Id == document.Id, PartitionKey));
}
[Fact]
public async Task PartitionedDeleteOneAsync()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = await SUT.DeleteOneAsync(document);
// Assert
Assert.Equal(1, result);
Assert.False(SUT.Any<DeleteTestsPartitionedDocument>(e => e.Id == document.Id, PartitionKey));
}
[Fact]
public async Task PartitionedDeleteOneAsyncLinq()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = await SUT.DeleteOneAsync<DeleteTestsPartitionedDocument>(e => e.Id == document.Id, PartitionKey);
// Assert
Assert.Equal(1, result);
Assert.False(SUT.Any<DeleteTestsPartitionedDocument>(e => e.Id == document.Id, PartitionKey));
}
[Fact]
public async Task PartitionedDeleteManyAsyncLinq()
{
// Arrange
var documents = CreateTestDocuments(5);
documents.ForEach(e => e.SomeContent = "DeleteManyAsyncLinqContent");
SUT.AddMany(documents);
// Act
var result = await SUT.DeleteManyAsync<DeleteTestsPartitionedDocument>(e => e.SomeContent == "DeleteManyAsyncLinqContent", PartitionKey);
// Assert
Assert.Equal(5, result);
Assert.False(SUT.Any<DeleteTestsPartitionedDocument>(e => e.SomeContent == "DeleteManyAsyncLinqContent", PartitionKey));
}
[Fact]
public async Task PartitionedDeleteManyAsync()
{
// Arrange
var documents = CreateTestDocuments(5);
documents.ForEach(e => e.SomeContent = "DeleteManyAsyncLinqContent");
SUT.AddMany(documents);
// Act
var result = await SUT.DeleteManyAsync(documents);
// Assert
Assert.Equal(5, result);
Assert.False(SUT.Any<DeleteTestsPartitionedDocument>(e => e.SomeContent == "DeleteManyAsyncLinqContent", PartitionKey));
}
[Fact]
public void PartitionedDeleteManyLinq()
{
// Arrange
var content = "DeleteManyLinqContent";
var documents = CreateTestDocuments(5);
documents.ForEach(e => e.SomeContent = content);
SUT.AddMany(documents);
// Act
var result = SUT.DeleteMany<DeleteTestsPartitionedDocument>(e => e.SomeContent == content, PartitionKey);
// Assert
Assert.Equal(5, result);
Assert.False(SUT.Any<DeleteTestsPartitionedDocument>(e => e.SomeContent == content, PartitionKey));
}
[Fact]
public void PartitionedDeleteMany()
{
// Arrange
var content = "DeleteManyContent";
var documents = CreateTestDocuments(5);
documents.ForEach(e => e.SomeContent = content);
SUT.AddMany(documents);
// Act
var result = SUT.DeleteMany(documents);
// Assert
Assert.Equal(5, result);
Assert.False(SUT.Any<DeleteTestsPartitionedDocument>(e => e.SomeContent == content, PartitionKey));
}
}
}
-129
View File
@@ -1,129 +0,0 @@
using CoreIntegrationTests.Infrastructure;
using MongoDbGenericRepository.Models;
using Xunit;
using System.Threading.Tasks;
namespace CoreIntegrationTests
{
public class DeleteTestsDocument : Document
{
public DeleteTestsDocument()
{
Version = 2;
}
public string SomeContent { get; set; }
}
public class DeleteTests : BaseMongoDbRepositoryTests<DeleteTestsDocument>
{
[Fact]
public void DeleteOne()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = SUT.DeleteOne(document);
// Assert
Assert.Equal(1, result);
Assert.False(SUT.Any<DeleteTestsDocument>(e => e.Id == document.Id));
}
[Fact]
public void DeleteOneLinq()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = SUT.DeleteOne<DeleteTestsDocument>(e => e.Id == document.Id);
// Assert
Assert.Equal(1, result);
Assert.False(SUT.Any<DeleteTestsDocument>(e => e.Id == document.Id));
}
[Fact]
public async Task DeleteOneAsync()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = await SUT.DeleteOneAsync(document);
// Assert
Assert.Equal(1, result);
Assert.False(SUT.Any<DeleteTestsDocument>(e => e.Id == document.Id));
}
[Fact]
public async Task DeleteOneAsyncLinq()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = await SUT.DeleteOneAsync<DeleteTestsDocument>(e => e.Id == document.Id);
// Assert
Assert.Equal(1, result);
Assert.False(SUT.Any<DeleteTestsDocument>(e => e.Id == document.Id));
}
[Fact]
public async Task DeleteManyAsyncLinq()
{
// Arrange
var documents = CreateTestDocuments(5);
documents.ForEach(e => e.SomeContent = "DeleteManyAsyncLinqContent");
SUT.AddMany(documents);
// Act
var result = await SUT.DeleteManyAsync<DeleteTestsDocument>(e => e.SomeContent == "DeleteManyAsyncLinqContent");
// Assert
Assert.Equal(5, result);
Assert.False(SUT.Any<DeleteTestsDocument>(e => e.SomeContent == "DeleteManyAsyncLinqContent"));
}
[Fact]
public async Task DeleteManyAsync()
{
// Arrange
var documents = CreateTestDocuments(5);
documents.ForEach(e => e.SomeContent = "DeleteManyAsyncLinqContent");
SUT.AddMany(documents);
// Act
var result = await SUT.DeleteManyAsync(documents);
// Assert
Assert.Equal(5, result);
Assert.False(SUT.Any<DeleteTestsDocument>(e => e.SomeContent == "DeleteManyAsyncLinqContent"));
}
[Fact]
public void DeleteManyLinq()
{
// Arrange
var content = "DeleteManyLinqContent";
var documents = CreateTestDocuments(5);
documents.ForEach(e => e.SomeContent = content);
SUT.AddMany(documents);
// Act
var result = SUT.DeleteMany<DeleteTestsDocument>(e => e.SomeContent == content);
// Assert
Assert.Equal(5, result);
Assert.False(SUT.Any<DeleteTestsDocument>(e => e.SomeContent == content));
}
[Fact]
public void DeleteMany()
{
// Arrange
var content = "DeleteManyContent";
var documents = CreateTestDocuments(5);
documents.ForEach(e => e.SomeContent = content);
SUT.AddMany(documents);
// Act
var result = SUT.DeleteMany(documents);
// Assert
Assert.Equal(5, result);
Assert.False(SUT.Any<DeleteTestsDocument>(e => e.SomeContent == content));
}
}
}
+1 -1
View File
@@ -6,7 +6,7 @@ using Xunit;
using Microsoft.AspNetCore.Identity;
using System.Threading.Tasks;
namespace CoreCoreIntegrationTests
namespace CoreIntegrationTests
{
public class MongoIdentityUser<TKey> : IdentityUser<TKey>, IDocument<TKey>
where TKey : IEquatable<TKey>
@@ -62,18 +62,18 @@ namespace CoreIntegrationTests.Infrastructure
}
#region IDisposable Support
private bool disposedValue = false; // Pour détecter les appels redondants
private bool _disposedValue; // Pour détecter les appels redondants
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
if (!_disposedValue)
{
if (disposing)
{
Cleanup();
}
disposedValue = true;
_disposedValue = true;
}
}
@@ -0,0 +1,15 @@
using System;
namespace CoreIntegrationTests.Infrastructure
{
/// <summary>
/// A class holding global variables.
/// </summary>
public static class GlobalVariables
{
/// <summary>
/// A random number generator.
/// </summary>
public static Random Random = new Random();
}
}
@@ -1,14 +1,12 @@
using CoreCoreIntegrationTests;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Bson.Serialization.Conventions;
using System.Threading;
namespace CoreIntegrationTests.Infrastructure
{
internal static class MongoDbConfig
{
private static bool _initialized = false;
private static object _initializationLock = new object();
private static bool _initialized;
private static object _initializationLock = new();
private static object _initializationTarget;
public static void EnsureConfigured()
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,381 @@
using MongoDB.Driver;
using MongoDbGenericRepository;
using MongoDbGenericRepository.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace CoreIntegrationTests.Infrastructure
{
public abstract partial class MongoDbDocumentTestBase<T> :
IClassFixture<MongoDbTestFixture<T, Guid>>
where T : TestDoc, new()
{
#region Update One
[Fact]
public void UpdateOne()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T>(document);
var content = GetContent();
document.SomeContent = content;
// Act
var result = SUT.UpdateOne<T>(document);
// Assert
Assert.True(result);
var updatedDocument = SUT.GetById<T>(document.Id, PartitionKey);
Assert.True(null != updatedDocument, GetTestName());
Assert.True(content == updatedDocument.SomeContent, GetTestName());
}
[Fact]
public async Task UpdateOneAsync()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T>(document);
var content = GetContent();
document.SomeContent = content;
// Act
var result = await SUT.UpdateOneAsync<T>(document);
// Assert
Assert.True(result);
var updatedDocument = SUT.GetById<T>(document.Id, PartitionKey);
Assert.True(null != updatedDocument, GetTestName());
Assert.True(content == updatedDocument.SomeContent, GetTestName());
}
[Fact]
public void UpdateOneField()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T>(document);
var content = GetContent();
// Act
var result = SUT.UpdateOne<T, string>(document, x => x.SomeContent, content);
// Assert
Assert.True(result, GetTestName());
var updatedDocument = SUT.GetById<T>(document.Id, PartitionKey);
Assert.True(null != updatedDocument, GetTestName());
Assert.True(content == updatedDocument.SomeContent, GetTestName());
}
[Fact]
public async Task UpdateOneFieldAsync()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T>(document);
var content = GetContent();
// Act
var result = await SUT.UpdateOneAsync<T, string>(document, x => x.SomeContent, content);
// Assert
Assert.True(result, GetTestName());
var updatedDocument = SUT.GetById<T>(document.Id, PartitionKey);
Assert.True(null != updatedDocument, GetTestName());
Assert.True(content == updatedDocument.SomeContent, GetTestName());
}
[Fact]
public void UpdateOneFieldWithFilter()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T>(document);
var content = GetContent();
// Act
var result = SUT.UpdateOne<T, string>(x => x.Id.Equals(document.Id), x => x.SomeContent, content, PartitionKey);
// Assert
Assert.True(result, GetTestName());
var updatedDocument = SUT.GetById<T>(document.Id, PartitionKey);
Assert.True(null != updatedDocument, GetTestName());
Assert.True(content == updatedDocument.SomeContent, GetTestName());
}
[Fact]
public async Task UpdateOneFieldWithFilterAsync()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T>(document);
var content = GetContent();
// Act
var result = await SUT.UpdateOneAsync<T, string>(x => x.Id.Equals(document.Id), x => x.SomeContent, content, PartitionKey);
// Assert
Assert.True(result, GetTestName());
var updatedDocument = SUT.GetById<T>(document.Id, PartitionKey);
Assert.True(null != updatedDocument, GetTestName());
Assert.True(content == updatedDocument.SomeContent, GetTestName());
}
[Fact]
public async Task UpdateOneAsyncWithUpdateDefinition()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T>(document);
var childrenToAdd = new List<Child>
{
new Child("testType1", "testValue1"),
new Child("testType2", "testValue2")
};
var updateDef = MongoDB.Driver.Builders<T>.Update.AddToSetEach(p => p.Children, childrenToAdd);
// Act
var result = await SUT.UpdateOneAsync<T>(document, updateDef);
// Assert
Assert.True(result);
var updatedDocument = SUT.GetById<T>(document.Id, PartitionKey);
Assert.True(null != updatedDocument);
Assert.True(childrenToAdd[0].Type == updatedDocument.Children[0].Type, GetTestName());
Assert.True(childrenToAdd[0].Value == updatedDocument.Children[0].Value, GetTestName());
Assert.True(childrenToAdd[1].Type == updatedDocument.Children[1].Type, GetTestName());
Assert.True(childrenToAdd[1].Value == updatedDocument.Children[1].Value, GetTestName());
}
[Fact]
public void UpdateOneWithUpdateDefinition()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T>(document);
var childrenToAdd = new List<Child>
{
new Child("testType1", "testValue1"),
new Child("testType2", "testValue2")
};
var updateDef = MongoDB.Driver.Builders<T>.Update.AddToSetEach(p => p.Children, childrenToAdd);
// Act
var result = SUT.UpdateOne<T>(document, updateDef);
// Assert
Assert.True(result);
var updatedDocument = SUT.GetById<T>(document.Id, PartitionKey);
Assert.True(null != updatedDocument);
Assert.True(childrenToAdd[0].Type == updatedDocument.Children[0].Type, GetTestName());
Assert.True(childrenToAdd[0].Value == updatedDocument.Children[0].Value, GetTestName());
Assert.True(childrenToAdd[1].Type == updatedDocument.Children[1].Type, GetTestName());
Assert.True(childrenToAdd[1].Value == updatedDocument.Children[1].Value, GetTestName());
}
#endregion Update One
#region Update Many
[Fact]
public async Task UpdateManyWithLinqFilterAsync()
{
// Arrange
var documents = CreateTestDocuments(2);
SUT.AddMany<T>(documents);
var docIds = documents.Select(u => u.Id).ToArray();
var content = GetContent();
// Act
var result = await SUT.UpdateManyAsync<T, string>(x => docIds.Contains(x.Id), x => x.SomeContent, content, PartitionKey);
// Assert
Assert.True(result == 2, GetTestName());
var updatedDocument = SUT.GetAll<T>(x => docIds.Contains(x.Id), PartitionKey);
Assert.True(updatedDocument.Count == 2);
Assert.True(updatedDocument.All(u => u.SomeContent == content), GetTestName());
}
[Fact]
public async Task UpdateManyWithFilterDefinitionAsync()
{
// Arrange
var documents = CreateTestDocuments(2);
SUT.AddMany<T>(documents);
var docIds = documents.Select(u => u.Id).ToArray();
var filterDefinition = Builders<T>.Filter.Where(x => docIds.Contains(x.Id));
var content = GetContent();
// Act
var result = await SUT.UpdateManyAsync<T, string>(filterDefinition, x => x.SomeContent, content, PartitionKey);
// Assert
Assert.True(result == 2, GetTestName());
var updatedDocument = SUT.GetAll<T>(x => docIds.Contains(x.Id), PartitionKey);
Assert.True(updatedDocument.Count == 2);
Assert.True(updatedDocument.All(u => u.SomeContent == content), GetTestName());
}
[Fact]
public async Task UpdateManyWithLinqFilterAndUpdateDefinitionAsync()
{
// Arrange
var documents = CreateTestDocuments(2);
SUT.AddMany<T>(documents);
var docIds = documents.Select(u => u.Id).ToArray();
var childrenToAdd = new List<Child>
{
new Child("testType1", "testValue1"),
new Child("testType2", "testValue2")
};
var updateDef = Builders<T>.Update.AddToSetEach(p => p.Children, childrenToAdd);
var content = GetContent();
// Act
var result = await SUT.UpdateManyAsync<T>(x => docIds.Contains(x.Id), updateDef, PartitionKey);
// Assert
Assert.True(result == 2, GetTestName());
var updatedDocuments = SUT.GetAll<T>(x => docIds.Contains(x.Id), PartitionKey);
Assert.True(updatedDocuments.Count == 2);
updatedDocuments.ForEach(updatedDocument =>
{
Assert.True(childrenToAdd[0].Type == updatedDocument.Children[0].Type, GetTestName());
Assert.True(childrenToAdd[0].Value == updatedDocument.Children[0].Value, GetTestName());
Assert.True(childrenToAdd[1].Type == updatedDocument.Children[1].Type, GetTestName());
Assert.True(childrenToAdd[1].Value == updatedDocument.Children[1].Value, GetTestName());
});
}
[Fact]
public async Task UpdateManyWithFilterAndUpdateDefinitionsAsync()
{
// Arrange
var documents = CreateTestDocuments(2);
SUT.AddMany<T>(documents);
var childrenToAdd = new List<Child>
{
new Child("testType1", "testValue1"),
new Child("testType2", "testValue2")
};
var updateDef = Builders<T>.Update.AddToSetEach(p => p.Children, childrenToAdd);
var docIds = documents.Select(u => u.Id).ToArray();
var filterDefinition = Builders<T>.Filter.Where(x => docIds.Contains(x.Id));
var content = GetContent();
// Act
var result = await SUT.UpdateManyAsync<T>(filterDefinition, updateDef, PartitionKey);
// Assert
Assert.True(result == 2, GetTestName());
var updatedDocuments = SUT.GetAll<T>(x => docIds.Contains(x.Id), PartitionKey);
Assert.True(updatedDocuments.Count == 2);
updatedDocuments.ForEach(updatedDocument =>
{
Assert.True(childrenToAdd[0].Type == updatedDocument.Children[0].Type, GetTestName());
Assert.True(childrenToAdd[0].Value == updatedDocument.Children[0].Value, GetTestName());
Assert.True(childrenToAdd[1].Type == updatedDocument.Children[1].Type, GetTestName());
Assert.True(childrenToAdd[1].Value == updatedDocument.Children[1].Value, GetTestName());
});
}
[Fact]
public void UpdateManyWithLinqFilter()
{
// Arrange
var documents = CreateTestDocuments(2);
SUT.AddMany<T>(documents);
var docIds = documents.Select(u => u.Id).ToArray();
var content = GetContent();
// Act
var result = SUT.UpdateMany<T, string>(x => docIds.Contains(x.Id), x => x.SomeContent, content, PartitionKey);
// Assert
Assert.True(result == 2, GetTestName());
var updatedDocument = SUT.GetAll<T>(x => docIds.Contains(x.Id), PartitionKey);
Assert.True(updatedDocument.Count == 2);
Assert.True(updatedDocument.All(u => u.SomeContent == content), GetTestName());
}
[Fact]
public void UpdateManyWithFilterDefinition()
{
// Arrange
var documents = CreateTestDocuments(2);
SUT.AddMany<T>(documents);
var docIds = documents.Select(u => u.Id).ToArray();
var filterDefinition = Builders<T>.Filter.Where(x => docIds.Contains(x.Id));
var content = GetContent();
// Act
var result = SUT.UpdateMany<T, string>(filterDefinition, x => x.SomeContent, content, PartitionKey);
// Assert
Assert.True(result == 2, GetTestName());
var updatedDocument = SUT.GetAll<T>(x => docIds.Contains(x.Id), PartitionKey);
Assert.True(updatedDocument.Count == 2);
Assert.True(updatedDocument.All(u => u.SomeContent == content), GetTestName());
}
[Fact]
public void UpdateManyWithLinqFilterAndUpdateDefinition()
{
// Arrange
var documents = CreateTestDocuments(2);
SUT.AddMany<T>(documents);
var docIds = documents.Select(u => u.Id).ToArray();
var childrenToAdd = new List<Child>
{
new Child("testType1", "testValue1"),
new Child("testType2", "testValue2")
};
var updateDef = Builders<T>.Update.AddToSetEach(p => p.Children, childrenToAdd);
var content = GetContent();
// Act
var result = SUT.UpdateMany<T>(x => docIds.Contains(x.Id), updateDef, PartitionKey);
// Assert
Assert.True(result == 2, GetTestName());
var updatedDocuments = SUT.GetAll<T>(x => docIds.Contains(x.Id), PartitionKey);
Assert.True(updatedDocuments.Count == 2);
updatedDocuments.ForEach(updatedDocument =>
{
Assert.True(childrenToAdd[0].Type == updatedDocument.Children[0].Type, GetTestName());
Assert.True(childrenToAdd[0].Value == updatedDocument.Children[0].Value, GetTestName());
Assert.True(childrenToAdd[1].Type == updatedDocument.Children[1].Type, GetTestName());
Assert.True(childrenToAdd[1].Value == updatedDocument.Children[1].Value, GetTestName());
});
}
[Fact]
public void UpdateManyWithFilterAndUpdateDefinitions()
{
// Arrange
var documents = CreateTestDocuments(2);
SUT.AddMany<T>(documents);
var childrenToAdd = new List<Child>
{
new Child("testType1", "testValue1"),
new Child("testType2", "testValue2")
};
var updateDef = Builders<T>.Update.AddToSetEach(p => p.Children, childrenToAdd);
var docIds = documents.Select(u => u.Id).ToArray();
var filterDefinition = Builders<T>.Filter.Where(x => docIds.Contains(x.Id));
var content = GetContent();
// Act
var result = SUT.UpdateMany<T>(filterDefinition, updateDef, PartitionKey);
// Assert
Assert.True(result == 2, GetTestName());
var updatedDocuments = SUT.GetAll<T>(x => docIds.Contains(x.Id), PartitionKey);
Assert.True(updatedDocuments.Count == 2);
updatedDocuments.ForEach(updatedDocument =>
{
Assert.True(childrenToAdd[0].Type == updatedDocument.Children[0].Type, GetTestName());
Assert.True(childrenToAdd[0].Value == updatedDocument.Children[0].Value, GetTestName());
Assert.True(childrenToAdd[1].Type == updatedDocument.Children[1].Type, GetTestName());
Assert.True(childrenToAdd[1].Value == updatedDocument.Children[1].Value, GetTestName());
});
}
#endregion Update Many
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,377 @@
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace CoreIntegrationTests.Infrastructure
{
public abstract partial class MongoDbTKeyDocumentTestBase<T, TKey> :
IClassFixture<MongoDbTestFixture<T, TKey>>
where T : TestDoc<TKey>, new()
where TKey : IEquatable<TKey>
{
#region Update One
[Fact]
public void UpdateOne()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T, TKey>(document);
var content = GetContent();
document.SomeContent = content;
// Act
var result = SUT.UpdateOne<T, TKey>(document);
// Assert
Assert.True(result);
var updatedDocument = SUT.GetById<T, TKey>(document.Id, PartitionKey);
Assert.True(null != updatedDocument, GetTestName());
Assert.True(content == updatedDocument.SomeContent, GetTestName());
}
[Fact]
public async Task UpdateOneAsync()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T, TKey>(document);
var content = GetContent();
document.SomeContent = content;
// Act
var result = await SUT.UpdateOneAsync<T, TKey>(document);
// Assert
Assert.True(result);
var updatedDocument = SUT.GetById<T, TKey>(document.Id, PartitionKey);
Assert.True(null != updatedDocument, GetTestName());
Assert.True(content == updatedDocument.SomeContent, GetTestName());
}
[Fact]
public void UpdateOneField()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T, TKey>(document);
var content = GetContent();
// Act
var result = SUT.UpdateOne<T, TKey, string>(document, x => x.SomeContent, content);
// Assert
Assert.True(result, GetTestName());
var updatedDocument = SUT.GetById<T, TKey>(document.Id, PartitionKey);
Assert.True(null != updatedDocument, GetTestName());
Assert.True(content == updatedDocument.SomeContent, GetTestName());
}
[Fact]
public async Task UpdateOneFieldAsync()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T, TKey>(document);
var content = GetContent();
// Act
var result = await SUT.UpdateOneAsync<T, TKey, string>(document, x => x.SomeContent, content);
// Assert
Assert.True(result, GetTestName());
var updatedDocument = SUT.GetById<T, TKey>(document.Id, PartitionKey);
Assert.True(null != updatedDocument, GetTestName());
Assert.True(content == updatedDocument.SomeContent, GetTestName());
}
[Fact]
public void UpdateOneFieldWithFilter()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T, TKey>(document);
var content = GetContent();
// Act
var result = SUT.UpdateOne<T, TKey, string>(x => x.Id.Equals(document.Id), x => x.SomeContent, content, PartitionKey);
// Assert
Assert.True(result, GetTestName());
var updatedDocument = SUT.GetById<T, TKey>(document.Id, PartitionKey);
Assert.True(null != updatedDocument, GetTestName());
Assert.True(content == updatedDocument.SomeContent, GetTestName());
}
[Fact]
public async Task UpdateOneFieldWithFilterAsync()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T, TKey>(document);
var content = GetContent();
// Act
var result = await SUT.UpdateOneAsync<T, TKey, string>(x => x.Id.Equals(document.Id), x => x.SomeContent, content, PartitionKey);
// Assert
Assert.True(result, GetTestName());
var updatedDocument = SUT.GetById<T, TKey>(document.Id, PartitionKey);
Assert.True(null != updatedDocument, GetTestName());
Assert.True(content == updatedDocument.SomeContent, GetTestName());
}
[Fact]
public async Task UpdateOneAsyncWithUpdateDefinition()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T, TKey>(document);
var childrenToAdd = new List<Child>
{
new Child("testType1", "testValue1"),
new Child("testType2", "testValue2")
};
var updateDef = MongoDB.Driver.Builders<T>.Update.AddToSetEach(p => p.Children, childrenToAdd);
// Act
var result = await SUT.UpdateOneAsync<T, TKey>(document, updateDef);
// Assert
Assert.True(result);
var updatedDocument = SUT.GetById<T, TKey>(document.Id, PartitionKey);
Assert.True(null != updatedDocument);
Assert.True(childrenToAdd[0].Type == updatedDocument.Children[0].Type, GetTestName());
Assert.True(childrenToAdd[0].Value == updatedDocument.Children[0].Value, GetTestName());
Assert.True(childrenToAdd[1].Type == updatedDocument.Children[1].Type, GetTestName());
Assert.True(childrenToAdd[1].Value == updatedDocument.Children[1].Value, GetTestName());
}
[Fact]
public void UpdateOneWithUpdateDefinition()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne<T, TKey>(document);
var childrenToAdd = new List<Child>
{
new Child("testType1", "testValue1"),
new Child("testType2", "testValue2")
};
var updateDef = MongoDB.Driver.Builders<T>.Update.AddToSetEach(p => p.Children, childrenToAdd);
// Act
var result = SUT.UpdateOne<T, TKey>(document, updateDef);
// Assert
Assert.True(result);
var updatedDocument = SUT.GetById<T, TKey>(document.Id, PartitionKey);
Assert.True(null != updatedDocument);
Assert.True(childrenToAdd[0].Type == updatedDocument.Children[0].Type, GetTestName());
Assert.True(childrenToAdd[0].Value == updatedDocument.Children[0].Value, GetTestName());
Assert.True(childrenToAdd[1].Type == updatedDocument.Children[1].Type, GetTestName());
Assert.True(childrenToAdd[1].Value == updatedDocument.Children[1].Value, GetTestName());
}
#endregion Update One
#region Update Many
[Fact]
public async Task UpdateManyWithLinqFilterAsync()
{
// Arrange
var documents = CreateTestDocuments(2);
SUT.AddMany<T, TKey>(documents);
var docIds = documents.Select(u => u.Id).ToArray();
var content = GetContent();
// Act
var result = await SUT.UpdateManyAsync<T, TKey, string>(x => docIds.Contains(x.Id), x => x.SomeContent, content, PartitionKey);
// Assert
Assert.True(result == 2, GetTestName());
var updatedDocument = SUT.GetAll<T, TKey>(x => docIds.Contains(x.Id), PartitionKey);
Assert.True(updatedDocument.Count == 2);
Assert.True(updatedDocument.All(u => u.SomeContent == content), GetTestName());
}
[Fact]
public async Task UpdateManyWithFilterDefinitionAsync()
{
// Arrange
var documents = CreateTestDocuments(2);
SUT.AddMany<T, TKey>(documents);
var docIds = documents.Select(u => u.Id).ToArray();
var filterDefinition = Builders<T>.Filter.Where(x => docIds.Contains(x.Id));
var content = GetContent();
// Act
var result = await SUT.UpdateManyAsync<T, TKey, string>(filterDefinition, x => x.SomeContent, content, PartitionKey);
// Assert
Assert.True(result == 2, GetTestName());
var updatedDocument = SUT.GetAll<T, TKey>(x => docIds.Contains(x.Id), PartitionKey);
Assert.True(updatedDocument.Count == 2);
Assert.True(updatedDocument.All(u => u.SomeContent == content), GetTestName());
}
[Fact]
public async Task UpdateManyWithLinqFilterAndUpdateDefinitionAsync()
{
// Arrange
var documents = CreateTestDocuments(2);
SUT.AddMany<T, TKey>(documents);
var docIds = documents.Select(u => u.Id).ToArray();
var childrenToAdd = new List<Child>
{
new Child("testType1", "testValue1"),
new Child("testType2", "testValue2")
};
var updateDef = Builders<T>.Update.AddToSetEach(p => p.Children, childrenToAdd);
var content = GetContent();
// Act
var result = await SUT.UpdateManyAsync<T, TKey>(x => docIds.Contains(x.Id), updateDef, PartitionKey);
// Assert
Assert.True(result == 2, GetTestName());
var updatedDocuments = SUT.GetAll<T, TKey>(x => docIds.Contains(x.Id), PartitionKey);
Assert.True(updatedDocuments.Count == 2);
updatedDocuments.ForEach(updatedDocument =>
{
Assert.True(childrenToAdd[0].Type == updatedDocument.Children[0].Type, GetTestName());
Assert.True(childrenToAdd[0].Value == updatedDocument.Children[0].Value, GetTestName());
Assert.True(childrenToAdd[1].Type == updatedDocument.Children[1].Type, GetTestName());
Assert.True(childrenToAdd[1].Value == updatedDocument.Children[1].Value, GetTestName());
});
}
[Fact]
public async Task UpdateManyWithFilterAndUpdateDefinitionsAsync()
{
// Arrange
var documents = CreateTestDocuments(2);
SUT.AddMany<T, TKey>(documents);
var childrenToAdd = new List<Child>
{
new Child("testType1", "testValue1"),
new Child("testType2", "testValue2")
};
var updateDef = Builders<T>.Update.AddToSetEach(p => p.Children, childrenToAdd);
var docIds = documents.Select(u => u.Id).ToArray();
var filterDefinition = Builders<T>.Filter.Where(x => docIds.Contains(x.Id));
var content = GetContent();
// Act
var result = await SUT.UpdateManyAsync<T, TKey>(filterDefinition, updateDef, PartitionKey);
// Assert
Assert.True(result == 2, GetTestName());
var updatedDocuments = SUT.GetAll<T, TKey>(x => docIds.Contains(x.Id), PartitionKey);
Assert.True(updatedDocuments.Count == 2);
updatedDocuments.ForEach(updatedDocument =>
{
Assert.True(childrenToAdd[0].Type == updatedDocument.Children[0].Type, GetTestName());
Assert.True(childrenToAdd[0].Value == updatedDocument.Children[0].Value, GetTestName());
Assert.True(childrenToAdd[1].Type == updatedDocument.Children[1].Type, GetTestName());
Assert.True(childrenToAdd[1].Value == updatedDocument.Children[1].Value, GetTestName());
});
}
[Fact]
public void UpdateManyWithLinqFilter()
{
// Arrange
var documents = CreateTestDocuments(2);
SUT.AddMany<T, TKey>(documents);
var docIds = documents.Select(u => u.Id).ToArray();
var content = GetContent();
// Act
var result = SUT.UpdateMany<T, TKey, string>(x => docIds.Contains(x.Id), x => x.SomeContent, content, PartitionKey);
// Assert
Assert.True(result == 2, GetTestName());
var updatedDocument = SUT.GetAll<T, TKey>(x => docIds.Contains(x.Id), PartitionKey);
Assert.True(updatedDocument.Count == 2);
Assert.True(updatedDocument.All(u => u.SomeContent == content), GetTestName());
}
[Fact]
public void UpdateManyWithFilterDefinition()
{
// Arrange
var documents = CreateTestDocuments(2);
SUT.AddMany<T, TKey>(documents);
var docIds = documents.Select(u => u.Id).ToArray();
var filterDefinition = Builders<T>.Filter.Where(x => docIds.Contains(x.Id));
var content = GetContent();
// Act
var result = SUT.UpdateMany<T, TKey, string>(filterDefinition, x => x.SomeContent, content, PartitionKey);
// Assert
Assert.True(result == 2, GetTestName());
var updatedDocument = SUT.GetAll<T, TKey>(x => docIds.Contains(x.Id), PartitionKey);
Assert.True(updatedDocument.Count == 2);
Assert.True(updatedDocument.All(u => u.SomeContent == content), GetTestName());
}
[Fact]
public void UpdateManyWithLinqFilterAndUpdateDefinition()
{
// Arrange
var documents = CreateTestDocuments(2);
SUT.AddMany<T, TKey>(documents);
var docIds = documents.Select(u => u.Id).ToArray();
var childrenToAdd = new List<Child>
{
new Child("testType1", "testValue1"),
new Child("testType2", "testValue2")
};
var updateDef = Builders<T>.Update.AddToSetEach(p => p.Children, childrenToAdd);
var content = GetContent();
// Act
var result = SUT.UpdateMany<T, TKey>(x => docIds.Contains(x.Id), updateDef, PartitionKey);
// Assert
Assert.True(result == 2, GetTestName());
var updatedDocuments = SUT.GetAll<T, TKey>(x => docIds.Contains(x.Id), PartitionKey);
Assert.True(updatedDocuments.Count == 2);
updatedDocuments.ForEach(updatedDocument =>
{
Assert.True(childrenToAdd[0].Type == updatedDocument.Children[0].Type, GetTestName());
Assert.True(childrenToAdd[0].Value == updatedDocument.Children[0].Value, GetTestName());
Assert.True(childrenToAdd[1].Type == updatedDocument.Children[1].Type, GetTestName());
Assert.True(childrenToAdd[1].Value == updatedDocument.Children[1].Value, GetTestName());
});
}
[Fact]
public void UpdateManyWithFilterAndUpdateDefinitions()
{
// Arrange
var documents = CreateTestDocuments(2);
SUT.AddMany<T, TKey>(documents);
var childrenToAdd = new List<Child>
{
new Child("testType1", "testValue1"),
new Child("testType2", "testValue2")
};
var updateDef = Builders<T>.Update.AddToSetEach(p => p.Children, childrenToAdd);
var docIds = documents.Select(u => u.Id).ToArray();
var filterDefinition = Builders<T>.Filter.Where(x => docIds.Contains(x.Id));
var content = GetContent();
// Act
var result = SUT.UpdateMany<T, TKey>(filterDefinition, updateDef, PartitionKey);
// Assert
Assert.True(result == 2, GetTestName());
var updatedDocuments = SUT.GetAll<T, TKey>(x => docIds.Contains(x.Id), PartitionKey);
Assert.True(updatedDocuments.Count == 2);
updatedDocuments.ForEach(updatedDocument =>
{
Assert.True(childrenToAdd[0].Type == updatedDocument.Children[0].Type, GetTestName());
Assert.True(childrenToAdd[0].Value == updatedDocument.Children[0].Value, GetTestName());
Assert.True(childrenToAdd[1].Type == updatedDocument.Children[1].Type, GetTestName());
Assert.True(childrenToAdd[1].Value == updatedDocument.Children[1].Value, GetTestName());
});
}
#endregion Update Many
}
}
@@ -0,0 +1,53 @@
using MongoDbGenericRepository;
using MongoDbGenericRepository.Models;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
namespace CoreIntegrationTests.Infrastructure
{
public class MongoDbTestFixture<T, TKey> : IDisposable
where T : IDocument<TKey>, new()
where TKey : IEquatable<TKey>
{
public IMongoDbContext Context;
public MongoDbTestFixture()
{
}
public string PartitionKey { get; set; }
public static ConcurrentBag<T> DocsToDelete { get; set; } = new ConcurrentBag<T>();
public virtual void Dispose()
{
if (DocsToDelete.Any())
{
TestRepository.Instance.DeleteMany<T, TKey>(DocsToDelete.ToList());
}
}
public T CreateTestDocument()
{
var doc = new T();
DocsToDelete.Add(doc);
return doc;
}
public List<T> CreateTestDocuments(int numberOfDocumentsToCreate)
{
var docs = new List<T>();
for (var i = 0; i < numberOfDocumentsToCreate; i++)
{
var doc = new T();
docs.Add(doc);
DocsToDelete.Add(doc);
}
return docs;
}
}
}
@@ -0,0 +1,61 @@
using System;
namespace CoreIntegrationTests.Infrastructure
{
// Thanks BlueRaja - Danny Pflughoeft https://stackoverflow.com/a/13095144/5103354
/// <summary>
/// Extensions for the random number generator <see cref="Random"/>
/// </summary>
public static class RandomExtensions
{
/// <summary>
/// Returns a random long from min (inclusive) to max (exclusive)
/// </summary>
/// <param name="random">The given random instance</param>
/// <param name="min">The inclusive minimum bound</param>
/// <param name="max">The exclusive maximum bound. Must be greater than min</param>
public static long NextLong(this Random random, long min, long max)
{
if (max <= min)
throw new ArgumentOutOfRangeException("max", "max must be > min!");
//Working with ulong so that modulo works correctly with values > long.MaxValue
ulong uRange = (ulong)(max - min);
//Prevent a modulo bias; see https://stackoverflow.com/a/10984975/238419
//for more information.
//In the worst case, the expected number of calls is 2 (though usually it's
//much closer to 1) so this loop doesn't really hurt performance at all.
ulong ulongRand;
do
{
byte[] buf = new byte[8];
random.NextBytes(buf);
ulongRand = (ulong)BitConverter.ToInt64(buf, 0);
} while (ulongRand > ulong.MaxValue - ((ulong.MaxValue % uRange) + 1) % uRange);
return (long)(ulongRand % uRange) + min;
}
/// <summary>
/// Returns a random long from 0 (inclusive) to max (exclusive)
/// </summary>
/// <param name="random">The given random instance</param>
/// <param name="max">The exclusive maximum bound. Must be greater than 0</param>
public static long NextLong(this Random random, long max)
{
return random.NextLong(0, max);
}
/// <summary>
/// Returns a random long over all possible values of long (except long.MaxValue, similar to
/// random.Next())
/// </summary>
/// <param name="random">The given random instance</param>
public static long NextLong(this Random random)
{
return random.NextLong(long.MinValue, long.MaxValue);
}
}
}
@@ -0,0 +1,104 @@
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDbGenericRepository.Models;
using MongoDbGenericRepository.Utils;
using System;
using System.Collections.Generic;
namespace CoreIntegrationTests.Infrastructure
{
public class ProjectedGroup
{
public int Key { get; set; }
public List<string> Content { get; set; }
}
public class MyTestProjection
{
public string SomeContent { get; set; }
public DateTime SomeDate { get; set; }
}
public class Nested
{
public DateTime SomeDate { get; set; }
[BsonRepresentation(BsonType.Decimal128)]
public decimal SomeAmount { get; set; }
}
public class Child
{
public Child(string type, string value)
{
Type = type;
Value = value;
}
public string Type { get; set; }
public string Value { get; set; }
}
public class TestDoc : Document
{
public TestDoc()
{
Version = 2;
Nested = new Nested
{
SomeDate = DateTime.UtcNow
};
Children = new List<Child>();
}
public int SomeValue { get; set; }
public string SomeContent { get; set; }
public string SomeContent2 { get; set; }
public string SomeContent3 { get; set; }
public int GroupingKey { get; set; }
public Nested Nested { get; set; }
public List<Child> Children { get; set; }
}
public class TestDoc<TKey> : IDocument<TKey>
where TKey : IEquatable<TKey>
{
[BsonId]
public TKey Id { get; set; }
public int Version { get; set; }
public TestDoc()
{
InitializeFields();
Version = 2;
Nested = new Nested
{
SomeDate = DateTime.UtcNow
};
Children = new List<Child>();
}
public int GroupingKey { get; set; }
public string SomeContent { get; set; }
public string SomeContent4 { get; set; }
public string SomeContent5 { get; set; }
public Nested Nested { get; set; }
public List<Child> Children { get; set; }
public TId Init<TId>()
{
return IdGenerator.GetId<TId>();
}
private void InitializeFields()
{
Id = Init<TKey>();
}
}
}
@@ -1,7 +1,43 @@
using MongoDbGenericRepository;
using MongoDB.Bson;
using MongoDbGenericRepository;
using System;
namespace CoreIntegrationTests.Infrastructure
{
public interface ITestRepository<TKey> : IBaseMongoRepository<TKey> where TKey : IEquatable<TKey>
{
void DropTestCollection<TDocument>();
void DropTestCollection<TDocument>(string partitionKey);
}
public class TestTKeyRepository<TKey> : BaseMongoRepository<TKey>, ITestRepository<TKey> where TKey : IEquatable<TKey>
{
const string connectionString = "mongodb://localhost:27017/MongoDbTests";
private static readonly ITestRepository<TKey> _instance = new TestTKeyRepository<TKey>(connectionString);
/// <inheritdoc />
private TestTKeyRepository(string connectionString) : base(connectionString)
{
}
public static ITestRepository<TKey> Instance
{
get
{
return _instance;
}
}
public void DropTestCollection<TDocument>()
{
MongoDbContext.DropCollection<TDocument>();
}
public void DropTestCollection<TDocument>(string partitionKey)
{
MongoDbContext.DropCollection<TDocument>(partitionKey);
}
}
/// <summary>
/// A singleton implementation of the TestRepository
/// </summary>
@@ -1,140 +0,0 @@
using CoreIntegrationTests.Infrastructure;
using MongoDbGenericRepository.Models;
using Xunit;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace CoreIntegrationTests
{
public class ProjectTestsPartitionedDocument : PartitionedDocument
{
public ProjectTestsPartitionedDocument() : base("TestPartitionKey")
{
Version = 2;
Nested = new Nested
{
SomeDate = DateTime.UtcNow
};
}
public string SomeContent { get; set; }
public Nested Nested { get; set; }
}
public class ProjectPartitionedTests : BaseMongoDbRepositoryTests<ProjectTestsPartitionedDocument>
{
[Fact]
public async Task PartitionedProjectOneAsync()
{
// Arrange
const string someContent = "ProjectOneAsyncContent";
var someDate = DateTime.UtcNow;
var document = CreateTestDocument();
document.SomeContent = someContent;
document.Nested.SomeDate = someDate;
SUT.AddOne(document);
// Act
var result = await SUT.ProjectOneAsync<ProjectTestsPartitionedDocument, MyProjection>(
x => x.Id == document.Id,
x => new MyProjection
{
SomeContent = x.SomeContent,
SomeDate = x.Nested.SomeDate
},
PartitionKey);
// Assert
Assert.NotNull(result);
Assert.Equal(someContent, result.SomeContent);
Assert.Equal(someDate.Minute, result.SomeDate.Minute);
Assert.Equal(someDate.Second, result.SomeDate.Second);
}
[Fact]
public void PartitionedProjectOne()
{
// Arrange
const string someContent = "ProjectOneContent";
var someDate = DateTime.UtcNow;
var document = CreateTestDocument();
document.SomeContent = someContent;
document.Nested.SomeDate = someDate;
SUT.AddOne(document);
// Act
var result = SUT.ProjectOne<ProjectTestsPartitionedDocument, MyProjection>(
x => x.Id == document.Id,
x => new MyProjection
{
SomeContent = x.SomeContent,
SomeDate = x.Nested.SomeDate
},
PartitionKey);
// Assert
Assert.NotNull(result);
Assert.Equal(someContent, result.SomeContent);
Assert.Equal(someDate.Minute, result.SomeDate.Minute);
Assert.Equal(someDate.Second, result.SomeDate.Second);
}
[Fact]
public async Task PartitionedProjectManyAsync()
{
// Arrange
const string someContent = "ProjectManyAsyncContent";
var someDate = DateTime.UtcNow;
var document = CreateTestDocuments(5);
document.ForEach(e =>
{
e.SomeContent = someContent;
e.Nested.SomeDate = someDate;
});
SUT.AddMany(document);
// Act
var result = await SUT.ProjectManyAsync<ProjectTestsPartitionedDocument, MyProjection>(
x => x.SomeContent == someContent,
x => new MyProjection
{
SomeContent = x.SomeContent,
SomeDate = x.Nested.SomeDate
},
PartitionKey);
// Assert
Assert.Equal(5, result.Count);
Assert.Equal(someContent, result.First().SomeContent);
Assert.Equal(someDate.Minute, result.First().SomeDate.Minute);
Assert.Equal(someDate.Second, result.First().SomeDate.Second);
}
[Fact]
public void PartitionedProjectMany()
{
// Arrange
const string someContent = "ProjectManyContent";
var someDate = DateTime.UtcNow;
var document = CreateTestDocuments(5);
document.ForEach(e =>
{
e.SomeContent = someContent;
e.Nested.SomeDate = someDate;
});
SUT.AddMany(document);
// Act
var result = SUT.ProjectMany<ProjectTestsPartitionedDocument, MyProjection>(
x => x.SomeContent == someContent,
x => new MyProjection
{
SomeContent = x.SomeContent,
SomeDate = x.Nested.SomeDate
},
PartitionKey);
// Assert
Assert.Equal(5, result.Count);
Assert.Equal(someContent, result.First().SomeContent);
Assert.Equal(someDate.Minute, result.First().SomeDate.Minute);
Assert.Equal(someDate.Second, result.First().SomeDate.Second);
}
}
}
-149
View File
@@ -1,149 +0,0 @@
using CoreIntegrationTests.Infrastructure;
using MongoDbGenericRepository.Models;
using Xunit;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace CoreIntegrationTests
{
public class Nested
{
public DateTime SomeDate { get; set; }
}
public class MyProjection
{
public DateTime SomeDate { get; set; }
public string SomeContent { get; set; }
}
public class ProjectTestsDocument : Document
{
public ProjectTestsDocument()
{
Version = 2;
Nested = new Nested
{
SomeDate = DateTime.UtcNow
};
}
public string SomeContent { get; set; }
public Nested Nested { get; set; }
}
public class ProjectTests : BaseMongoDbRepositoryTests<ProjectTestsDocument>
{
[Fact]
public async Task ProjectOneAsync()
{
// Arrange
const string someContent = "ProjectOneAsyncContent";
var someDate = DateTime.UtcNow;
var document = CreateTestDocument();
document.SomeContent = someContent;
document.Nested.SomeDate = someDate;
SUT.AddOne(document);
// Act
var result = await SUT.ProjectOneAsync<ProjectTestsDocument, MyProjection>(
x => x.Id == document.Id,
x => new MyProjection
{
SomeContent = x.SomeContent,
SomeDate = x.Nested.SomeDate
});
// Assert
Assert.NotNull(result);
Assert.Equal(someContent, result.SomeContent);
Assert.Equal(someDate.Minute, result.SomeDate.Minute);
Assert.Equal(someDate.Second, result.SomeDate.Second);
}
[Fact]
public void ProjectOne()
{
// Arrange
const string someContent = "ProjectOneContent";
var someDate = DateTime.UtcNow;
var document = CreateTestDocument();
document.SomeContent = someContent;
document.Nested.SomeDate = someDate;
SUT.AddOne(document);
// Act
var result = SUT.ProjectOne<ProjectTestsDocument, MyProjection>(
x => x.Id == document.Id,
x => new MyProjection
{
SomeContent = x.SomeContent,
SomeDate = x.Nested.SomeDate
});
// Assert
Assert.NotNull(result);
Assert.Equal(someContent, result.SomeContent);
Assert.Equal(someDate.Minute, result.SomeDate.Minute);
Assert.Equal(someDate.Second, result.SomeDate.Second);
}
[Fact]
public async Task ProjectManyAsync()
{
// Arrange
const string someContent = "ProjectManyAsyncContent";
var someDate = DateTime.UtcNow;
var document = CreateTestDocuments(5);
document.ForEach(e =>
{
e.SomeContent = someContent;
e.Nested.SomeDate = someDate;
});
SUT.AddMany(document);
// Act
var result = await SUT.ProjectManyAsync<ProjectTestsDocument, MyProjection>(
x => x.SomeContent == someContent,
x => new MyProjection
{
SomeContent = x.SomeContent,
SomeDate = x.Nested.SomeDate
});
// Assert
Assert.Equal(5, result.Count);
Assert.Equal(someContent, result.First().SomeContent);
Assert.Equal(someDate.Minute, result.First().SomeDate.Minute);
Assert.Equal(someDate.Second, result.First().SomeDate.Second);
}
[Fact]
public void ProjectMany()
{
// Arrange
const string someContent = "ProjectManyContent";
var someDate = DateTime.UtcNow;
var document = CreateTestDocuments(5);
document.ForEach(e =>
{
e.SomeContent = someContent;
e.Nested.SomeDate = someDate;
});
SUT.AddMany(document);
// Act
var result = SUT.ProjectMany<ProjectTestsDocument, MyProjection>(
x => x.SomeContent == someContent,
x => new MyProjection
{
SomeContent = x.SomeContent,
SomeDate = x.Nested.SomeDate
});
// Assert
Assert.Equal(5, result.Count);
Assert.Equal(someContent, result.First().SomeContent);
Assert.Equal(someDate.Minute, result.First().SomeDate.Minute);
Assert.Equal(someDate.Second, result.First().SomeDate.Second);
}
}
}
@@ -1,181 +0,0 @@
using CoreIntegrationTests.Infrastructure;
using MongoDbGenericRepository.Models;
using Xunit;
using System;
using System.Threading.Tasks;
namespace CoreIntegrationTests
{
public class ReadTestsPartitionedDocument : PartitionedDocument
{
public ReadTestsPartitionedDocument() : base("TestPartitionKey")
{
Version = 1;
}
public string SomeContent { get; set; }
}
public class ReadPartitionedTests : BaseMongoDbRepositoryTests<ReadTestsPartitionedDocument>
{
[Fact]
public async Task PartitionedGetByIdAsync()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = await SUT.GetByIdAsync<ReadTestsPartitionedDocument>(document.Id, PartitionKey);
// Assert
Assert.NotNull(result);
}
[Fact]
public void PartitionedGetById()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = SUT.GetById<ReadTestsPartitionedDocument>(document.Id, PartitionKey);
// Assert
Assert.NotNull(result);
}
[Fact]
public async Task PartitionedGetOneAsync()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = await SUT.GetOneAsync<ReadTestsPartitionedDocument>(x => x.Id == document.Id, PartitionKey);
// Assert
Assert.NotNull(result);
}
[Fact]
public void PartitionedGetOne()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = SUT.GetOne<ReadTestsPartitionedDocument>(x => x.Id == document.Id, PartitionKey);
// Assert
Assert.NotNull(result);
}
[Fact]
public void PartitionedGetCursor()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var cursor = SUT.GetCursor<ReadTestsPartitionedDocument>(x => x.Id == document.Id, PartitionKey);
var count = cursor.Count();
// Assert
Assert.Equal(1, count);
}
[Fact]
public async Task PartitionedAnyAsyncReturnsTrue()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = await SUT.AnyAsync<ReadTestsPartitionedDocument>(x => x.Id == document.Id, PartitionKey);
// Assert
Assert.True(result);
}
[Fact]
public async Task PartitionedAnyAsyncReturnsFalse()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = await SUT.AnyAsync<ReadTestsPartitionedDocument>(x => x.Id == Guid.NewGuid(), PartitionKey);
// Assert
Assert.False(result);
}
[Fact]
public void PartitionedAnyReturnsTrue()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = SUT.Any<ReadTestsPartitionedDocument>(x => x.Id == document.Id, PartitionKey);
// Assert
Assert.True(result);
}
[Fact]
public void PartitionedAnyReturnsFalse()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = SUT.Any<ReadTestsPartitionedDocument>(x => x.Id == Guid.NewGuid(), PartitionKey);
// Assert
Assert.False(result);
}
[Fact]
public async Task PartitionedGetAllAsync()
{
// Arrange
var documents = CreateTestDocuments(5);
documents.ForEach(e => e.SomeContent = "GetAllAsyncContent");
SUT.AddMany(documents);
// Act
var result = await SUT.GetAllAsync<ReadTestsPartitionedDocument>(x => x.SomeContent == "GetAllAsyncContent", PartitionKey);
// Assert
Assert.Equal(5, result.Count);
}
[Fact]
public void PartitionedGetAll()
{
// Arrange
var documents = CreateTestDocuments(5);
documents.ForEach(e => e.SomeContent = "GetAllContent");
SUT.AddMany(documents);
// Act
var result = SUT.GetAll<ReadTestsPartitionedDocument>(x => x.SomeContent == "GetAllContent", PartitionKey);
// Assert
Assert.Equal(5, result.Count);
}
[Fact]
public async Task PartitionedCountAsync()
{
// Arrange
var documents = CreateTestDocuments(5);
documents.ForEach(e => e.SomeContent = "CountAsyncContent");
SUT.AddMany(documents);
// Act
var result = await SUT.CountAsync<ReadTestsPartitionedDocument>(x => x.SomeContent == "CountAsyncContent", PartitionKey);
// Assert
Assert.Equal(5, result);
}
[Fact]
public void PartitionedCount()
{
// Arrange
var documents = CreateTestDocuments(5);
documents.ForEach(e => e.SomeContent = "CountContent");
SUT.AddMany(documents);
// Act
var result = SUT.Count<ReadTestsPartitionedDocument>(x => x.SomeContent == "CountContent", PartitionKey);
// Assert
Assert.Equal(5, result);
}
}
}
-181
View File
@@ -1,181 +0,0 @@
using CoreIntegrationTests.Infrastructure;
using MongoDbGenericRepository.Models;
using Xunit;
using System;
using System.Threading.Tasks;
namespace CoreIntegrationTests
{
public class ReadTestsDocument : Document
{
public ReadTestsDocument()
{
Version = 2;
}
public string SomeContent { get; set; }
}
public class ReadTests : BaseMongoDbRepositoryTests<ReadTestsDocument>
{
[Fact]
public async Task GetByIdAsync()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = await SUT.GetByIdAsync<ReadTestsDocument>(document.Id);
// Assert
Assert.NotNull(result);
}
[Fact]
public void GetById()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = SUT.GetById<ReadTestsDocument>(document.Id);
// Assert
Assert.NotNull(result);
}
[Fact]
public async Task GetOneAsync()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = await SUT.GetOneAsync<ReadTestsDocument>(x => x.Id == document.Id);
// Assert
Assert.NotNull(result);
}
[Fact]
public void GetOne()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = SUT.GetOne<ReadTestsDocument>(x => x.Id == document.Id);
// Assert
Assert.NotNull(result);
}
[Fact]
public void GetCursor()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var cursor = SUT.GetCursor<ReadTestsDocument>(x => x.Id == document.Id);
var count = cursor.Count();
// Assert
Assert.Equal(1, count);
}
[Fact]
public async Task AnyAsyncReturnsTrue()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = await SUT.AnyAsync<ReadTestsDocument>(x => x.Id == document.Id);
// Assert
Assert.True(result);
}
[Fact]
public async Task AnyAsyncReturnsFalse()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = await SUT.AnyAsync<ReadTestsDocument>(x => x.Id == Guid.NewGuid());
// Assert
Assert.False(result);
}
[Fact]
public void AnyReturnsTrue()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = SUT.Any<ReadTestsDocument>(x => x.Id == document.Id);
// Assert
Assert.True(result);
}
[Fact]
public void AnyReturnsFalse()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
// Act
var result = SUT.Any<ReadTestsDocument>(x => x.Id == Guid.NewGuid());
// Assert
Assert.False(result);
}
[Fact]
public async Task GetAllAsync()
{
// Arrange
var documents = CreateTestDocuments(5);
documents.ForEach(e => e.SomeContent = "GetAllAsyncContent");
SUT.AddMany(documents);
// Act
var result = await SUT.GetAllAsync<ReadTestsDocument>(x => x.SomeContent == "GetAllAsyncContent");
// Assert
Assert.Equal(5, result.Count);
}
[Fact]
public void GetAll()
{
// Arrange
var documents = CreateTestDocuments(5);
documents.ForEach(e => e.SomeContent = "GetAllContent");
SUT.AddMany(documents);
// Act
var result = SUT.GetAll<ReadTestsDocument>(x => x.SomeContent == "GetAllContent");
// Assert
Assert.Equal(5, result.Count);
}
[Fact]
public async Task CountAsync()
{
// Arrange
var documents = CreateTestDocuments(5);
documents.ForEach(e => e.SomeContent = "CountAsyncContent");
SUT.AddMany(documents);
// Act
var result = await SUT.CountAsync<ReadTestsDocument>(x => x.SomeContent == "CountAsyncContent");
// Assert
Assert.Equal(5, result);
}
[Fact]
public void Count()
{
// Arrange
var documents = CreateTestDocuments(5);
documents.ForEach(e => e.SomeContent = "CountContent");
SUT.AddMany(documents);
// Act
var result = SUT.Count<ReadTestsDocument>(x => x.SomeContent == "CountContent");
// Assert
Assert.Equal(5, result);
}
}
}
@@ -1,51 +0,0 @@
using CoreIntegrationTests.Infrastructure;
using MongoDbGenericRepository.Models;
using Xunit;
using System.Threading.Tasks;
namespace CoreIntegrationTests
{
public class UpdateTestsPartitionedDocument : PartitionedDocument
{
public UpdateTestsPartitionedDocument() : base("TestPartitionKey")
{
Version = 2;
}
public string SomeContent { get; set; }
}
public class UpdatePartitionedTests : BaseMongoDbRepositoryTests<UpdateTestsPartitionedDocument>
{
[Fact]
public void PartitionedUpdateOne()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
document.SomeContent = "UpdateOneContent";
// Act
var result = SUT.UpdateOne(document);
// Assert
Assert.True(result);
var updatedDocument = SUT.GetById<UpdateTestsPartitionedDocument>(document.Id, PartitionKey);
Assert.NotNull(updatedDocument);
Assert.Equal("UpdateOneContent", updatedDocument.SomeContent);
}
[Fact]
public async Task PartitionedUpdateOneAsync()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
document.SomeContent = "UpdateOneAsyncContent";
// Act
var result = await SUT.UpdateOneAsync(document);
// Assert
Assert.True(result);
var updatedDocument = SUT.GetById<UpdateTestsPartitionedDocument>(document.Id, PartitionKey);
Assert.NotNull(updatedDocument);
Assert.Equal("UpdateOneAsyncContent", updatedDocument.SomeContent);
}
}
}
-51
View File
@@ -1,51 +0,0 @@
using CoreIntegrationTests.Infrastructure;
using MongoDbGenericRepository.Models;
using Xunit;
using System.Threading.Tasks;
namespace CoreIntegrationTests
{
public class UpdateTestsDocument : Document
{
public UpdateTestsDocument()
{
Version = 2;
}
public string SomeContent { get; set; }
}
public class UpdateTests : BaseMongoDbRepositoryTests<UpdateTestsDocument>
{
[Fact]
public void UpdateOne()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
document.SomeContent = "UpdateOneContent";
// Act
var result = SUT.UpdateOne(document);
// Assert
Assert.True(result);
var updatedDocument = SUT.GetById<UpdateTestsDocument>(document.Id);
Assert.NotNull(updatedDocument);
Assert.Equal("UpdateOneContent", updatedDocument.SomeContent);
}
[Fact]
public async Task UpdateOneAsync()
{
// Arrange
var document = CreateTestDocument();
SUT.AddOne(document);
document.SomeContent = "UpdateOneAsyncContent";
// Act
var result = await SUT.UpdateOneAsync(document);
// Assert
Assert.True(result);
var updatedDocument = SUT.GetById<UpdateTestsDocument>(document.Id);
Assert.NotNull(updatedDocument);
Assert.Equal("UpdateOneAsyncContent", updatedDocument.SomeContent);
}
}
}
+218
View File
@@ -0,0 +1,218 @@
# All Files
[*]
charset = utf-8
indent_style = space
indent_size = 4
insert_final_newline = true
trim_trailing_whitespace = true
#########################################
# File Extension Settings
##########################################
# .NET Style Rules
# https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/language-rules#net-style-rules
[*.cs]
# "this." and "Me." qualifiers
dotnet_style_qualification_for_field = false:warning
dotnet_style_qualification_for_property = false:warning
dotnet_style_qualification_for_method = false:warning
dotnet_style_qualification_for_event = false:warning
# Language keywords instead of framework type names for type references
dotnet_style_predefined_type_for_locals_parameters_members = true:warning
dotnet_style_predefined_type_for_member_access = true:warning
# Modifier preferences
dotnet_style_require_accessibility_modifiers = always:warning
csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:warning
visual_basic_preferred_modifier_order = Partial,Default,Private,Protected,Public,Friend,NotOverridable,Overridable,MustOverride,Overloads,Overrides,MustInherit,NotInheritable,Static,Shared,Shadows,ReadOnly,WriteOnly,Dim,Const,WithEvents,Widening,Narrowing,Custom,Async:warning
dotnet_style_readonly_field = true:warning
# Parentheses preferences
dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:warning
dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:warning
dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:warning
dotnet_style_parentheses_in_other_operators = never_if_unnecessary:warning
# Expression-level preferences
dotnet_style_object_initializer = true:warning
dotnet_style_collection_initializer = true:warning
dotnet_style_explicit_tuple_names = true:warning
dotnet_style_prefer_inferred_tuple_names = true:warning
dotnet_style_prefer_inferred_anonymous_type_member_names = true:warning
dotnet_style_prefer_auto_properties = true:warning
dotnet_style_prefer_conditional_expression_over_assignment = false:suggestion
dotnet_diagnostic.IDE0045.severity = suggestion
dotnet_style_prefer_conditional_expression_over_return = false:suggestion
dotnet_diagnostic.IDE0046.severity = suggestion
dotnet_style_prefer_compound_assignment = true:warning
dotnet_style_prefer_simplified_interpolation = true:warning
dotnet_style_prefer_simplified_boolean_expressions = true:warning
# Null-checking preferences
dotnet_style_coalesce_expression = true:warning
dotnet_style_null_propagation = true:warning
dotnet_style_prefer_is_null_check_over_reference_equality_method = true:warning
# File header preferences
# file_header_template = <copyright file="{fileName}" company="PROJECT-AUTHOR">\n© PROJECT-AUTHOR\n</copyright>
# If you use StyleCop, you'll need to disable SA1636: File header copyright text should match.
# dotnet_diagnostic.SA1636.severity = none
# Undocumented
dotnet_style_operator_placement_when_wrapping = end_of_line:warning
csharp_style_prefer_null_check_over_type_check = true:warning
dotnet_analyzer_diagnostic.severity = warning
dotnet_code_quality_unused_parameters = all:warning
dotnet_remove_unnecessary_suppression_exclusions = none:warning
dotnet_sort_system_directives_first = true
dotnet_separate_import_directive_groups = false
dotnet_style_namespace_match_folder = true:suggestion
dotnet_diagnostic.IDE0130.severity = suggestion
dotnet_naming_style.camel_case_style.capitalization = camel_case
dotnet_naming_style.pascal_case_style.capitalization = pascal_case
dotnet_naming_style.first_upper_style.capitalization = first_word_upper
dotnet_naming_style.prefix_interface_with_i_style.capitalization = pascal_case
dotnet_naming_style.prefix_interface_with_i_style.required_prefix = I
dotnet_naming_style.prefix_type_parameters_with_t_style.capitalization = pascal_case
dotnet_naming_style.prefix_type_parameters_with_t_style.required_prefix = T
dotnet_naming_style.disallowed_style.capitalization = pascal_case
dotnet_naming_style.disallowed_style.required_prefix = ____RULE_VIOLATION____
dotnet_naming_style.disallowed_style.required_suffix = ____RULE_VIOLATION____
dotnet_naming_style.internal_error_style.capitalization = pascal_case
dotnet_naming_style.internal_error_style.required_prefix = ____INTERNAL_ERROR____
dotnet_naming_style.internal_error_style.required_suffix = ____INTERNAL_ERROR____
dotnet_naming_symbols.public_protected_constant_fields_group.applicable_accessibilities = public, protected, protected_internal
dotnet_naming_symbols.public_protected_constant_fields_group.required_modifiers = const
dotnet_naming_symbols.public_protected_constant_fields_group.applicable_kinds = field
dotnet_naming_rule.public_protected_constant_fields_must_be_pascal_case_rule.symbols = public_protected_constant_fields_group
dotnet_naming_rule.public_protected_constant_fields_must_be_pascal_case_rule.style = pascal_case_style
dotnet_naming_rule.public_protected_constant_fields_must_be_pascal_case_rule.severity = warning
dotnet_naming_symbols.public_protected_static_readonly_fields_group.applicable_accessibilities = public, protected, protected_internal
dotnet_naming_symbols.public_protected_static_readonly_fields_group.required_modifiers = static, readonly
dotnet_naming_symbols.public_protected_static_readonly_fields_group.applicable_kinds = field
dotnet_naming_rule.public_protected_static_readonly_fields_must_be_pascal_case_rule.symbols = public_protected_static_readonly_fields_group
dotnet_naming_rule.public_protected_static_readonly_fields_must_be_pascal_case_rule.style = pascal_case_style
dotnet_naming_rule.public_protected_static_readonly_fields_must_be_pascal_case_rule.severity = warning
dotnet_naming_symbols.other_public_protected_fields_group.applicable_accessibilities = public, protected, protected_internal
dotnet_naming_symbols.other_public_protected_fields_group.applicable_kinds = field
dotnet_naming_rule.other_public_protected_fields_disallowed_rule.symbols = other_public_protected_fields_group
dotnet_naming_rule.other_public_protected_fields_disallowed_rule.style = disallowed_style
dotnet_naming_rule.other_public_protected_fields_disallowed_rule.severity = error
dotnet_naming_symbols.stylecop_constant_fields_group.applicable_accessibilities = public, internal, protected_internal, protected, private_protected, private
dotnet_naming_symbols.stylecop_constant_fields_group.required_modifiers = const
dotnet_naming_symbols.stylecop_constant_fields_group.applicable_kinds = field
dotnet_naming_rule.stylecop_constant_fields_must_be_pascal_case_rule.symbols = stylecop_constant_fields_group
dotnet_naming_rule.stylecop_constant_fields_must_be_pascal_case_rule.style = pascal_case_style
dotnet_naming_rule.stylecop_constant_fields_must_be_pascal_case_rule.severity = warning
dotnet_naming_symbols.stylecop_static_readonly_fields_group.applicable_accessibilities = public, internal, protected_internal, protected, private_protected, private
dotnet_naming_symbols.stylecop_static_readonly_fields_group.required_modifiers = static, readonly
dotnet_naming_symbols.stylecop_static_readonly_fields_group.applicable_kinds = field
dotnet_naming_rule.stylecop_static_readonly_fields_must_be_pascal_case_rule.symbols = stylecop_static_readonly_fields_group
dotnet_naming_rule.stylecop_static_readonly_fields_must_be_pascal_case_rule.style = pascal_case_style
dotnet_naming_rule.stylecop_static_readonly_fields_must_be_pascal_case_rule.severity = warning
dotnet_naming_symbols.stylecop_fields_must_be_private_group.applicable_accessibilities = public, internal, protected_internal, protected, private_protected
dotnet_naming_symbols.stylecop_fields_must_be_private_group.applicable_kinds = field
dotnet_naming_rule.stylecop_instance_fields_must_be_private_rule.symbols = stylecop_fields_must_be_private_group
dotnet_naming_rule.stylecop_instance_fields_must_be_private_rule.style = disallowed_style
dotnet_naming_rule.stylecop_instance_fields_must_be_private_rule.severity = error
dotnet_naming_symbols.stylecop_private_fields_group.applicable_accessibilities = private
dotnet_naming_symbols.stylecop_private_fields_group.applicable_kinds = field
dotnet_naming_rule.stylecop_private_fields_must_be_camel_case_rule.symbols = stylecop_private_fields_group
dotnet_naming_rule.stylecop_private_fields_must_be_camel_case_rule.style = camel_case_style
dotnet_naming_rule.stylecop_private_fields_must_be_camel_case_rule.severity = warning
dotnet_naming_symbols.stylecop_local_fields_group.applicable_accessibilities = local
dotnet_naming_symbols.stylecop_local_fields_group.applicable_kinds = local
dotnet_naming_rule.stylecop_local_fields_must_be_camel_case_rule.symbols = stylecop_local_fields_group
dotnet_naming_rule.stylecop_local_fields_must_be_camel_case_rule.style = camel_case_style
dotnet_naming_rule.stylecop_local_fields_must_be_camel_case_rule.severity = silent
dotnet_naming_symbols.sanity_check_uncovered_field_case_group.applicable_accessibilities = *
dotnet_naming_symbols.sanity_check_uncovered_field_case_group.applicable_kinds = field
dotnet_naming_rule.sanity_check_uncovered_field_case_rule.symbols = sanity_check_uncovered_field_case_group
dotnet_naming_rule.sanity_check_uncovered_field_case_rule.style = internal_error_style
dotnet_naming_rule.sanity_check_uncovered_field_case_rule.severity = error
dotnet_naming_symbols.element_group.applicable_kinds = namespace, class, enum, struct, delegate, event, method, property
dotnet_naming_rule.element_rule.symbols = element_group
dotnet_naming_rule.element_rule.style = pascal_case_style
dotnet_naming_rule.element_rule.severity = warning
dotnet_naming_symbols.interface_group.applicable_kinds = interface
dotnet_naming_rule.interface_rule.symbols = interface_group
dotnet_naming_rule.interface_rule.style = prefix_interface_with_i_style
dotnet_naming_rule.interface_rule.severity = warning
dotnet_naming_symbols.type_parameter_group.applicable_kinds = type_parameter
dotnet_naming_rule.type_parameter_rule.symbols = type_parameter_group
dotnet_naming_rule.type_parameter_rule.style = prefix_type_parameters_with_t_style
dotnet_naming_rule.type_parameter_rule.severity = warning
dotnet_naming_symbols.parameters_group.applicable_kinds = parameter
dotnet_naming_rule.parameters_rule.symbols = parameters_group
dotnet_naming_rule.parameters_rule.style = camel_case_style
dotnet_naming_rule.parameters_rule.severity = warning
csharp_style_var_for_built_in_types = true:warning
csharp_style_var_when_type_is_apparent = true:warning
csharp_style_var_elsewhere = true:warning
csharp_style_expression_bodied_methods = true:warning
csharp_style_expression_bodied_constructors = true:warning
csharp_style_expression_bodied_operators = true:warning
csharp_style_expression_bodied_properties = true:warning
csharp_style_expression_bodied_indexers = true:warning
csharp_style_expression_bodied_accessors = true:warning
csharp_style_expression_bodied_lambdas = true:warning
csharp_style_expression_bodied_local_functions = true:warning
csharp_style_pattern_matching_over_is_with_cast_check = true:warning
csharp_style_pattern_matching_over_as_with_null_check = true:warning
csharp_style_prefer_switch_expression = true:warning
csharp_style_prefer_pattern_matching = true:warning
csharp_style_prefer_not_pattern = true:warning
csharp_style_inlined_variable_declaration = true:warning
csharp_prefer_simple_default_expression = true:warning
csharp_style_pattern_local_over_anonymous_function = true:warning
csharp_style_deconstructed_variable_declaration = true:warning
csharp_style_prefer_index_operator = true:warning
csharp_style_prefer_range_operator = true:warning
csharp_style_implicit_object_creation_when_type_is_apparent = true:warning
csharp_style_throw_expression = true:warning
csharp_style_conditional_delegate_call = true:warning
csharp_prefer_braces = true:warning
csharp_prefer_simple_using_statement = true:suggestion
dotnet_diagnostic.IDE0063.severity = suggestion
csharp_using_directive_placement = outside_namespace
csharp_prefer_static_local_function = true:warning
csharp_style_unused_value_expression_statement_preference = discard_variable:suggestion
dotnet_diagnostic.IDE0058.severity = suggestion
csharp_style_unused_value_assignment_preference = discard_variable:suggestion
dotnet_diagnostic.IDE0059.severity = suggestion
csharp_new_line_before_open_brace = all
csharp_new_line_before_else = true
csharp_new_line_before_catch = true
csharp_new_line_before_finally = true
csharp_new_line_before_members_in_object_initializers = true
csharp_new_line_before_members_in_anonymous_types = true
csharp_new_line_between_query_expression_clauses = true
csharp_indent_case_contents = true
csharp_indent_switch_labels = true
csharp_indent_labels = no_change
csharp_indent_block_contents = true
csharp_indent_braces = false
csharp_indent_case_contents_when_block = false
csharp_space_after_cast = false
csharp_space_after_keywords_in_control_flow_statements = true
csharp_space_between_parentheses = false
csharp_space_before_colon_in_inheritance_clause = true
csharp_space_after_colon_in_inheritance_clause = true
csharp_space_around_binary_operators = before_and_after
csharp_space_between_method_declaration_parameter_list_parentheses = false
csharp_space_between_method_declaration_empty_parameter_list_parentheses = false
csharp_space_between_method_declaration_name_and_open_parenthesis = false
csharp_space_between_method_call_parameter_list_parentheses = false
csharp_space_between_method_call_empty_parameter_list_parentheses = false
csharp_space_between_method_call_name_and_opening_parenthesis = false
csharp_space_after_comma = true
csharp_space_before_comma = false
csharp_space_after_dot = false
csharp_space_before_dot = false
csharp_space_after_semicolon_in_for_statement = true
csharp_space_before_semicolon_in_for_statement = false
csharp_space_around_declaration_statements = false
csharp_space_before_open_square_brackets = false
csharp_space_between_empty_square_brackets = false
csharp_space_between_square_brackets = false
csharp_preserve_single_line_statements = false
csharp_preserve_single_line_blocks = true
csharp_style_namespace_declarations = file_scoped:warning
dotnet_diagnostic.CA1707.severity = none
@@ -0,0 +1,77 @@
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AutoFixture;
using CoreUnitTests.Infrastructure;
using CoreUnitTests.Infrastructure.Model;
using MongoDbGenericRepository.DataAccess.Create;
using Moq;
using Xunit;
namespace CoreUnitTests.BaseMongoRepositoryTests.AddTests;
public class AddManyAsyncTests : TestMongoRepositoryContext
{
[Fact]
public async Task WithDocument_ShouldAddOne()
{
// Arrange
var documents = Fixture.CreateMany<TestDocument>().ToList();
Creator = new Mock<IMongoDbCreator>();
// Act
await Sut.AddManyAsync(documents);
// Assert
Creator.Verify(x => x.AddManyAsync<TestDocument, Guid>(documents, CancellationToken.None), Times.Once);
}
[Fact]
public async Task WithDocumentAndCancellationToken_ShouldAddOne()
{
// Arrange
var documents = Fixture.CreateMany<TestDocument>().ToList();
var token = new CancellationToken(true);
Creator = new Mock<IMongoDbCreator>();
// Act
await Sut.AddManyAsync(documents, token);
// Assert
Creator.Verify(x => x.AddManyAsync<TestDocument, Guid>(documents, token), Times.Once);
}
#region Keyed
[Fact]
public async Task Keyed_WithDocument_ShouldAddOne()
{
// Arrange
var documents = Fixture.CreateMany<TestDocumentWithKey<int>>().ToList();
Creator = new Mock<IMongoDbCreator>();
// Act
await Sut.AddManyAsync<TestDocumentWithKey<int>, int>(documents);
// Assert
Creator.Verify(x => x.AddManyAsync<TestDocumentWithKey<int>, int>(documents, CancellationToken.None), Times.Once);
}
[Fact]
public async Task Keyed_WithDocumentAndCancellationToken_ShouldAddOne()
{
// Arrange
var documents = Fixture.CreateMany<TestDocumentWithKey<int>>().ToList();
var token = new CancellationToken(true);
Creator = new Mock<IMongoDbCreator>();
// Act
await Sut.AddManyAsync<TestDocumentWithKey<int>, int>(documents, token);
// Assert
Creator.Verify(x => x.AddManyAsync<TestDocumentWithKey<int>, int>(documents, token), Times.Once);
}
#endregion
}
@@ -0,0 +1,77 @@
using System;
using System.Linq;
using System.Threading;
using AutoFixture;
using CoreUnitTests.Infrastructure;
using CoreUnitTests.Infrastructure.Model;
using MongoDbGenericRepository.DataAccess.Create;
using Moq;
using Xunit;
namespace CoreUnitTests.BaseMongoRepositoryTests.AddTests;
public class AddManyTests : TestMongoRepositoryContext
{
[Fact]
public void WithDocument_ShouldAddOne()
{
// Arrange
var documents = Fixture.CreateMany<TestDocument>().ToList();
Creator = new Mock<IMongoDbCreator>();
// Act
Sut.AddMany(documents);
// Assert
Creator.Verify(x => x.AddMany<TestDocument, Guid>(documents, CancellationToken.None), Times.Once);
}
[Fact]
public void WithDocumentAndCancellationToken_ShouldAddOne()
{
// Arrange
var documents = Fixture.CreateMany<TestDocument>().ToList();
var token = new CancellationToken(true);
Creator = new Mock<IMongoDbCreator>();
// Act
Sut.AddMany(documents, token);
// Assert
Creator.Verify(x => x.AddMany<TestDocument, Guid>(documents, token), Times.Once);
}
#region Keyed
[Fact]
public void Keyed_WithDocument_ShouldAddOne()
{
// Arrange
var documents = Fixture.CreateMany<TestDocumentWithKey<int>>().ToList();
Creator = new Mock<IMongoDbCreator>();
// Act
Sut.AddMany<TestDocumentWithKey<int>, int>(documents);
// Assert
Creator.Verify(x => x.AddMany<TestDocumentWithKey<int>, int>(documents, CancellationToken.None), Times.Once);
}
[Fact]
public void Keyed_WithDocumentAndCancellationToken_ShouldAddOne()
{
// Arrange
var documents = Fixture.CreateMany<TestDocumentWithKey<int>>().ToList();
var token = new CancellationToken(true);
Creator = new Mock<IMongoDbCreator>();
// Act
Sut.AddMany<TestDocumentWithKey<int>, int>(documents, token);
// Assert
Creator.Verify(x => x.AddMany<TestDocumentWithKey<int>, int>(documents, token), Times.Once);
}
#endregion
}
@@ -0,0 +1,76 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using AutoFixture;
using CoreUnitTests.Infrastructure;
using CoreUnitTests.Infrastructure.Model;
using MongoDbGenericRepository.DataAccess.Create;
using Moq;
using Xunit;
namespace CoreUnitTests.BaseMongoRepositoryTests.AddTests;
public class AddOneAsyncTests : TestMongoRepositoryContext
{
[Fact]
public async Task WithDocument_ShouldAddOne()
{
// Arrange
var document = Fixture.Create<TestDocument>();
Creator = new Mock<IMongoDbCreator>();
// Act
await Sut.AddOneAsync(document);
// Assert
Creator.Verify(x => x.AddOneAsync<TestDocument, Guid>(document, CancellationToken.None), Times.Once);
}
[Fact]
public async Task WithDocumentAndCancellationToken_ShouldAddOne()
{
// Arrange
var document = Fixture.Create<TestDocument>();
var token = new CancellationToken(true);
Creator = new Mock<IMongoDbCreator>();
// Act
await Sut.AddOneAsync(document, token);
// Assert
Creator.Verify(x => x.AddOneAsync<TestDocument, Guid>(document, token), Times.Once);
}
#region Keyed
[Fact]
public async Task Keyed_WithDocument_ShouldAddOne()
{
// Arrange
var document = Fixture.Create<TestDocumentWithKey<int>>();
Creator = new Mock<IMongoDbCreator>();
// Act
await Sut.AddOneAsync<TestDocumentWithKey<int>, int>(document);
// Assert
Creator.Verify(x => x.AddOneAsync<TestDocumentWithKey<int>, int>(document, CancellationToken.None), Times.Once);
}
[Fact]
public async Task Keyed_WithDocumentAndCancellationToken_ShouldAddOne()
{
// Arrange
var document = Fixture.Create<TestDocumentWithKey<int>>();
var token = new CancellationToken(true);
Creator = new Mock<IMongoDbCreator>();
// Act
await Sut.AddOneAsync<TestDocumentWithKey<int>, int>(document, token);
// Assert
Creator.Verify(x => x.AddOneAsync<TestDocumentWithKey<int>, int>(document, token), Times.Once);
}
#endregion
}
@@ -0,0 +1,75 @@
using System;
using System.Threading;
using AutoFixture;
using CoreUnitTests.Infrastructure;
using CoreUnitTests.Infrastructure.Model;
using MongoDbGenericRepository.DataAccess.Create;
using Moq;
using Xunit;
namespace CoreUnitTests.BaseMongoRepositoryTests.AddTests;
public class AddOneTests : TestMongoRepositoryContext
{
[Fact]
public void WithDocument_ShouldAddOne()
{
// Arrange
var document = Fixture.Create<TestDocument>();
Creator = new Mock<IMongoDbCreator>();
// Act
Sut.AddOne(document);
// Assert
Creator.Verify(x => x.AddOne<TestDocument, Guid>(document, CancellationToken.None), Times.Once);
}
[Fact]
public void WithDocumentAndCancellationToken_ShouldAddOne()
{
// Arrange
var document = Fixture.Create<TestDocument>();
var token = new CancellationToken(true);
Creator = new Mock<IMongoDbCreator>();
// Act
Sut.AddOne(document, token);
// Assert
Creator.Verify(x => x.AddOne<TestDocument, Guid>(document, token), Times.Once);
}
#region Keyed
[Fact]
public void Keyed_WithDocument_ShouldAddOne()
{
// Arrange
var document = Fixture.Create<TestDocumentWithKey<int>>();
Creator = new Mock<IMongoDbCreator>();
// Act
Sut.AddOne<TestDocumentWithKey<int>, int>(document);
// Assert
Creator.Verify(x => x.AddOne<TestDocumentWithKey<int>, int>(document, CancellationToken.None), Times.Once);
}
[Fact]
public void Keyed_WithDocumentAndCancellationToken_ShouldAddOne()
{
// Arrange
var document = Fixture.Create<TestDocumentWithKey<int>>();
var token = new CancellationToken(true);
Creator = new Mock<IMongoDbCreator>();
// Act
Sut.AddOne<TestDocumentWithKey<int>, int>(document, token);
// Assert
Creator.Verify(x => x.AddOne<TestDocumentWithKey<int>, int>(document, token), Times.Once);
}
#endregion
}
@@ -0,0 +1,320 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using AutoFixture;
using CoreUnitTests.Infrastructure;
using CoreUnitTests.Infrastructure.Model;
using FluentAssertions;
using MongoDbGenericRepository.DataAccess.Delete;
using Moq;
using Xunit;
namespace CoreUnitTests.BaseMongoRepositoryTests.DeleteTests;
public class DeleteManyAsyncTests : TestMongoRepositoryContext
{
[Fact]
public async Task WithDocuments_ShouldDeleteMany()
{
// Arrange
var documents = Fixture.CreateMany<TestDocument>().ToList();
var count = Fixture.Create<long>();
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(x => x.DeleteManyAsync<TestDocument, Guid>(It.IsAny<IEnumerable<TestDocument>>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(count);
// Act
var result = await Sut.DeleteManyAsync(documents);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteManyAsync<TestDocument, Guid>(documents, CancellationToken.None), Times.Once);
}
[Fact]
public async Task WithDocumentsAndCancellationToken_ShouldDeleteMany()
{
// Arrange
var documents = Fixture.CreateMany<TestDocument>().ToList();
var count = Fixture.Create<long>();
var cancellationToken = new CancellationToken(true);
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(x => x.DeleteManyAsync<TestDocument, Guid>(It.IsAny<IEnumerable<TestDocument>>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(count);
// Act
var result = await Sut.DeleteManyAsync(documents, cancellationToken);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteManyAsync<TestDocument, Guid>(documents, cancellationToken), Times.Once);
}
[Fact]
public async Task WithFilter_ShouldDeleteMany()
{
// Arrange
var content = Fixture.Create<string>();
var count = Fixture.Create<long>();
Expression<Func<TestDocument, bool>> filter = x => x.SomeContent == content;
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(x => x.DeleteManyAsync<TestDocument, Guid>(
It.IsAny<Expression<Func<TestDocument, bool>>>(),
It.IsAny<string>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(count);
// Act
var result = await Sut.DeleteManyAsync(filter);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteManyAsync<TestDocument, Guid>(filter, null, CancellationToken.None), Times.Once);
}
[Fact]
public async Task WithFilterAndCancellationToken_ShouldDeleteMany()
{
// Arrange
var content = Fixture.Create<string>();
var count = Fixture.Create<long>();
var token = new CancellationToken(true);
Expression<Func<TestDocument, bool>> filter = x => x.SomeContent == content;
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(x => x.DeleteManyAsync<TestDocument, Guid>(
It.IsAny<Expression<Func<TestDocument, bool>>>(),
It.IsAny<string>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(count);
// Act
var result = await Sut.DeleteManyAsync(filter, token);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteManyAsync<TestDocument, Guid>(filter, null, token), Times.Once);
}
[Fact]
public async Task WithFilterAndPartitionKey_ShouldDeleteMany()
{
// Arrange
var content = Fixture.Create<string>();
var count = Fixture.Create<long>();
var partitionKey = Fixture.Create<string>();
Expression<Func<TestDocument, bool>> filter = x => x.SomeContent == content;
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(x => x.DeleteManyAsync<TestDocument, Guid>(
It.IsAny<Expression<Func<TestDocument, bool>>>(),
It.IsAny<string>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(count);
// Act
var result = await Sut.DeleteManyAsync(filter, partitionKey);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteManyAsync<TestDocument, Guid>(filter, partitionKey, CancellationToken.None), Times.Once);
}
[Fact]
public async Task WithFilterAndPartitionKeyAndCancellationToken_ShouldDeleteMany()
{
// Arrange
var content = Fixture.Create<string>();
var count = Fixture.Create<long>();
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
Expression<Func<TestDocument, bool>> filter = x => x.SomeContent == content;
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(x => x.DeleteManyAsync<TestDocument, Guid>(
It.IsAny<Expression<Func<TestDocument, bool>>>(),
It.IsAny<string>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(count);
// Act
var result = await Sut.DeleteManyAsync(filter, partitionKey, token);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteManyAsync<TestDocument, Guid>(filter, partitionKey, token), Times.Once);
}
#region Keyed
[Fact]
public async Task Keyed_WithDocuments_ShouldDeleteMany()
{
// Arrange
var documents = Fixture.CreateMany<TestDocumentWithKey<int>>().ToList();
var count = Fixture.Create<long>();
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(x => x.DeleteManyAsync<TestDocumentWithKey<int>, int>(It.IsAny<IEnumerable<TestDocumentWithKey<int>>>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(count);
// Act
var result = await Sut.DeleteManyAsync<TestDocumentWithKey<int>, int>(documents);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteManyAsync<TestDocumentWithKey<int>, int>(documents, CancellationToken.None), Times.Once);
}
[Fact]
public async Task Keyed_WithDocumentsAndCancellationToken_ShouldDeleteMany()
{
// Arrange
var documents = Fixture.CreateMany<TestDocumentWithKey<int>>().ToList();
var count = Fixture.Create<long>();
var cancellationToken = new CancellationToken(true);
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(x => x.DeleteManyAsync<TestDocumentWithKey<int>, int>(It.IsAny<IEnumerable<TestDocumentWithKey<int>>>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(count);
// Act
var result = await Sut.DeleteManyAsync<TestDocumentWithKey<int>, int>(documents, cancellationToken);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteManyAsync<TestDocumentWithKey<int>, int>(documents, cancellationToken), Times.Once);
}
[Fact]
public async Task Keyed_WithFilter_ShouldDeleteMany()
{
// Arrange
var content = Fixture.Create<string>();
var count = Fixture.Create<long>();
Expression<Func<TestDocumentWithKey<int>, bool>> filter = x => x.SomeContent == content;
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(x => x.DeleteManyAsync<TestDocumentWithKey<int>, int>(
It.IsAny<Expression<Func<TestDocumentWithKey<int>, bool>>>(),
It.IsAny<string>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(count);
// Act
var result = await Sut.DeleteManyAsync<TestDocumentWithKey<int>, int>(filter);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteManyAsync<TestDocumentWithKey<int>, int>(filter, null, CancellationToken.None), Times.Once);
}
[Fact]
public async Task Keyed_WithFilterAndCancellationToken_ShouldDeleteMany()
{
// Arrange
var content = Fixture.Create<string>();
var count = Fixture.Create<long>();
var token = new CancellationToken(true);
Expression<Func<TestDocumentWithKey<int>, bool>> filter = x => x.SomeContent == content;
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(x => x.DeleteManyAsync<TestDocumentWithKey<int>, int>(
It.IsAny<Expression<Func<TestDocumentWithKey<int>, bool>>>(),
It.IsAny<string>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(count);
// Act
var result = await Sut.DeleteManyAsync<TestDocumentWithKey<int>, int>(filter, token);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteManyAsync<TestDocumentWithKey<int>, int>(filter, null, token), Times.Once);
}
[Fact]
public async Task Keyed_WithFilterAndPartitionKey_ShouldDeleteMany()
{
// Arrange
var content = Fixture.Create<string>();
var count = Fixture.Create<long>();
var partitionKey = Fixture.Create<string>();
Expression<Func<TestDocumentWithKey<int>, bool>> filter = x => x.SomeContent == content;
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(x => x.DeleteManyAsync<TestDocumentWithKey<int>, int>(
It.IsAny<Expression<Func<TestDocumentWithKey<int>, bool>>>(),
It.IsAny<string>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(count);
// Act
var result = await Sut.DeleteManyAsync<TestDocumentWithKey<int>, int>(filter, partitionKey);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteManyAsync<TestDocumentWithKey<int>, int>(filter, partitionKey, CancellationToken.None), Times.Once);
}
[Fact]
public async Task Keyed_WithFilterAndPartitionKeyAndCancellationToken_ShouldDeleteMany()
{
// Arrange
var content = Fixture.Create<string>();
var count = Fixture.Create<long>();
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
Expression<Func<TestDocumentWithKey<int>, bool>> filter = x => x.SomeContent == content;
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(x => x.DeleteManyAsync<TestDocumentWithKey<int>, int>(
It.IsAny<Expression<Func<TestDocumentWithKey<int>, bool>>>(),
It.IsAny<string>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(count);
// Act
var result = await Sut.DeleteManyAsync<TestDocumentWithKey<int>, int>(filter, partitionKey, token);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteManyAsync<TestDocumentWithKey<int>, int>(filter, partitionKey, token), Times.Once);
}
#endregion
}
@@ -0,0 +1,294 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using AutoFixture;
using CoreUnitTests.Infrastructure;
using CoreUnitTests.Infrastructure.Model;
using FluentAssertions;
using MongoDbGenericRepository.DataAccess.Delete;
using Moq;
using Xunit;
namespace CoreUnitTests.BaseMongoRepositoryTests.DeleteTests;
public class DeleteManyTests : TestMongoRepositoryContext
{
[Fact]
public void WithDocuments_ShouldDeleteMany()
{
// Arrange
var documents = Fixture.CreateMany<TestDocument>().ToList();
var count = Fixture.Create<long>();
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(x => x.DeleteMany<TestDocument, Guid>(It.IsAny<IEnumerable<TestDocument>>(), It.IsAny<CancellationToken>()))
.Returns(count);
// Act
var result = Sut.DeleteMany(documents);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteMany<TestDocument, Guid>(documents, CancellationToken.None), Times.Once);
}
[Fact]
public void WithDocumentsAndCancellationToken_ShouldDeleteMany()
{
// Arrange
var documents = Fixture.CreateMany<TestDocument>().ToList();
var count = Fixture.Create<long>();
var token = new CancellationToken(true);
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(x => x.DeleteMany<TestDocument, Guid>(It.IsAny<IEnumerable<TestDocument>>(), It.IsAny<CancellationToken>()))
.Returns(count);
// Act
var result = Sut.DeleteMany(documents, token);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteMany<TestDocument, Guid>(documents, token), Times.Once);
}
[Fact]
public void WithFilter_ShouldDeleteMany()
{
// Arrange
var content = Fixture.Create<string>();
var count = Fixture.Create<long>();
Expression<Func<TestDocument, bool>> filter = x => x.SomeContent == content;
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(x => x.DeleteMany<TestDocument, Guid>(It.IsAny<Expression<Func<TestDocument, bool>>>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.Returns(count);
// Act
var result = Sut.DeleteMany(filter);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteMany<TestDocument, Guid>(filter, null, CancellationToken.None), Times.Once);
}
[Fact]
public void WithFilterAndCancellationToken_ShouldDeleteMany()
{
// Arrange
var content = Fixture.Create<string>();
var count = Fixture.Create<long>();
var token = new CancellationToken(true);
Expression<Func<TestDocument, bool>> filter = x => x.SomeContent == content;
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(x => x.DeleteMany<TestDocument, Guid>(It.IsAny<Expression<Func<TestDocument, bool>>>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.Returns(count);
// Act
var result = Sut.DeleteMany(filter, token);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteMany<TestDocument, Guid>(filter, null, token), Times.Once);
}
[Fact]
public void WithFilterAndPartitionKey_ShouldDeleteMany()
{
// Arrange
var content = Fixture.Create<string>();
var count = Fixture.Create<long>();
var partitionKey = Fixture.Create<string>();
Expression<Func<TestDocument, bool>> filter = x => x.SomeContent == content;
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(x => x.DeleteMany<TestDocument, Guid>(It.IsAny<Expression<Func<TestDocument, bool>>>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.Returns(count);
// Act
var result = Sut.DeleteMany(filter, partitionKey);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteMany<TestDocument, Guid>(filter, partitionKey, CancellationToken.None), Times.Once);
}
[Fact]
public void WithFilterAndPartitionKeyAndCancellationToken_ShouldDeleteMany()
{
// Arrange
var content = Fixture.Create<string>();
var count = Fixture.Create<long>();
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
Expression<Func<TestDocument, bool>> filter = x => x.SomeContent == content;
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(x => x.DeleteMany<TestDocument, Guid>(It.IsAny<Expression<Func<TestDocument, bool>>>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.Returns(count);
// Act
var result = Sut.DeleteMany(filter, partitionKey, token);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteMany<TestDocument, Guid>(filter, partitionKey, token), Times.Once);
}
#region Keyed
[Fact]
public void Keyed_WithDocuments_ShouldDeleteMany()
{
// Arrange
var documents = Fixture.CreateMany<TestDocumentWithKey<int>>().ToList();
var count = Fixture.Create<long>();
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(x => x.DeleteMany<TestDocumentWithKey<int>, int>(It.IsAny<IEnumerable<TestDocumentWithKey<int>>>(), It.IsAny<CancellationToken>()))
.Returns(count);
// Act
var result = Sut.DeleteMany<TestDocumentWithKey<int>, int>(documents);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteMany<TestDocumentWithKey<int>, int>(documents, CancellationToken.None), Times.Once);
}
[Fact]
public void Keyed_WithDocumentsAndCancellationToken_ShouldDeleteMany()
{
// Arrange
var documents = Fixture.CreateMany<TestDocumentWithKey<int>>().ToList();
var count = Fixture.Create<long>();
var token = new CancellationToken(true);
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(x => x.DeleteMany<TestDocumentWithKey<int>, int>(It.IsAny<IEnumerable<TestDocumentWithKey<int>>>(), It.IsAny<CancellationToken>()))
.Returns(count);
// Act
var result = Sut.DeleteMany<TestDocumentWithKey<int>, int>(documents, token);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteMany<TestDocumentWithKey<int>, int>(documents, token), Times.Once);
}
[Fact]
public void Keyed_WithFilter_ShouldDeleteMany()
{
// Arrange
var content = Fixture.Create<string>();
var count = Fixture.Create<long>();
Expression<Func<TestDocumentWithKey<int>, bool>> filter = x => x.SomeContent == content;
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(x => x.DeleteMany<TestDocumentWithKey<int>, int>(It.IsAny<Expression<Func<TestDocumentWithKey<int>, bool>>>(), null, CancellationToken.None))
.Returns(count);
// Act
var result = Sut.DeleteMany<TestDocumentWithKey<int>, int>(filter);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteMany<TestDocumentWithKey<int>, int>(filter, null, CancellationToken.None), Times.Once);
}
[Fact]
public void Keyed_WithFilterAndCancellationToken_ShouldDeleteMany()
{
// Arrange
var content = Fixture.Create<string>();
var count = Fixture.Create<long>();
var token = new CancellationToken(true);
Expression<Func<TestDocumentWithKey<int>, bool>> filter = x => x.SomeContent == content;
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(x => x.DeleteMany<TestDocumentWithKey<int>, int>(It.IsAny<Expression<Func<TestDocumentWithKey<int>, bool>>>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.Returns(count);
// Act
var result = Sut.DeleteMany<TestDocumentWithKey<int>, int>(filter, token);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteMany<TestDocumentWithKey<int>, int>(filter, null, token), Times.Once);
}
[Fact]
public void Keyed_WithFilterAndPartitionKey_ShouldDeleteMany()
{
// Arrange
var content = Fixture.Create<string>();
var count = Fixture.Create<long>();
var partitionKey = Fixture.Create<string>();
Expression<Func<TestDocumentWithKey<int>, bool>> filter = x => x.SomeContent == content;
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(x => x.DeleteMany<TestDocumentWithKey<int>, int>(It.IsAny<Expression<Func<TestDocumentWithKey<int>, bool>>>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.Returns(count);
// Act
var result = Sut.DeleteMany<TestDocumentWithKey<int>, int>(filter, partitionKey);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteMany<TestDocumentWithKey<int>, int>(filter, partitionKey, CancellationToken.None), Times.Once);
}
[Fact]
public void Keyed_WithFilterAndPartitionKeyAndCancellationToken_ShouldDeleteMany()
{
// Arrange
var content = Fixture.Create<string>();
var count = Fixture.Create<long>();
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
Expression<Func<TestDocumentWithKey<int>, bool>> filter = x => x.SomeContent == content;
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(x => x.DeleteMany<TestDocumentWithKey<int>, int>(It.IsAny<Expression<Func<TestDocumentWithKey<int>, bool>>>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.Returns(count);
// Act
var result = Sut.DeleteMany<TestDocumentWithKey<int>, int>(filter, partitionKey, token);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteMany<TestDocumentWithKey<int>, int>(filter, partitionKey, token), Times.Once);
}
#endregion
}
@@ -0,0 +1,296 @@
using System;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using AutoFixture;
using CoreUnitTests.Infrastructure;
using CoreUnitTests.Infrastructure.Model;
using FluentAssertions;
using MongoDbGenericRepository.DataAccess.Delete;
using Moq;
using Xunit;
namespace CoreUnitTests.BaseMongoRepositoryTests.DeleteTests;
public class DeleteOneAsyncTests : TestMongoRepositoryContext
{
[Fact]
public async Task WithDocument_ShouldDeleteOne()
{
// Arrange
var document = Fixture.Create<TestDocument>();
var count = Fixture.Create<long>();
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(x => x.DeleteOneAsync<TestDocument, Guid>(It.IsAny<TestDocument>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(count);
// Act
var result = await Sut.DeleteOneAsync(document);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteOneAsync<TestDocument, Guid>(document, CancellationToken.None), Times.Once);
}
[Fact]
public async Task WithDocumentAndCancellationToken_ShouldDeleteOne()
{
// Arrange
var document = Fixture.Create<TestDocument>();
var count = Fixture.Create<long>();
var token = new CancellationToken(true);
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(x => x.DeleteOneAsync<TestDocument, Guid>(It.IsAny<TestDocument>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(count);
// Act
var result = await Sut.DeleteOneAsync(document, token);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteOneAsync<TestDocument, Guid>(document, token), Times.Once);
}
[Fact]
public async Task WithFilter_ShouldDeleteOne()
{
// Arrange
var count = Fixture.Create<long>();
var content = Fixture.Create<string>();
Expression<Func<TestDocument, bool>> filter = x => x.SomeContent == content;
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(x => x.DeleteOneAsync<TestDocument, Guid>(It.IsAny<Expression<Func<TestDocument, bool>>>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(count);
// Act
var result = await Sut.DeleteOneAsync(filter);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteOneAsync<TestDocument, Guid>(filter, null, CancellationToken.None), Times.Once);
}
[Fact]
public async Task WithFilterAndCancellationToken_ShouldDeleteOne()
{
// Arrange
var count = Fixture.Create<long>();
var content = Fixture.Create<string>();
var token = new CancellationToken(true);
Expression<Func<TestDocument, bool>> filter = x => x.SomeContent == content;
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(x => x.DeleteOneAsync<TestDocument, Guid>(It.IsAny<Expression<Func<TestDocument, bool>>>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(count);
// Act
var result = await Sut.DeleteOneAsync(filter, token);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteOneAsync<TestDocument, Guid>(filter, null, token), Times.Once);
}
[Fact]
public async Task WithFilterAndPartitionKey_ShouldDeleteOne()
{
// Arrange
var count = Fixture.Create<long>();
var content = Fixture.Create<string>();
var partitionKey = Fixture.Create<string>();
Expression<Func<TestDocument, bool>> filter = x => x.SomeContent == content;
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(x => x.DeleteOneAsync<TestDocument, Guid>(It.IsAny<Expression<Func<TestDocument, bool>>>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(count);
// Act
var result = await Sut.DeleteOneAsync(filter, partitionKey);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteOneAsync<TestDocument, Guid>(filter, partitionKey, CancellationToken.None), Times.Once);
}
[Fact]
public async Task WithFilterAndPartitionKeyAndCancellationToken_ShouldDeleteOne()
{
// Arrange
var count = Fixture.Create<long>();
var content = Fixture.Create<string>();
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
Expression<Func<TestDocument, bool>> filter = x => x.SomeContent == content;
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(x => x.DeleteOneAsync<TestDocument, Guid>(It.IsAny<Expression<Func<TestDocument, bool>>>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(count);
// Act
var result = await Sut.DeleteOneAsync(filter, partitionKey, token);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteOneAsync<TestDocument, Guid>(filter, partitionKey, token), Times.Once);
}
#region Keyed
[Fact]
public async Task Keyed_WithDocument_ShouldDeleteOne()
{
// Arrange
var document = Fixture.Create<TestDocumentWithKey<int>>();
var count = Fixture.Create<long>();
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(x => x.DeleteOneAsync<TestDocumentWithKey<int>, int>(It.IsAny<TestDocumentWithKey<int>>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(count);
// Act
var result = await Sut.DeleteOneAsync<TestDocumentWithKey<int>, int>(document);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteOneAsync<TestDocumentWithKey<int>, int>(document, CancellationToken.None), Times.Once);
}
[Fact]
public async Task Keyed_WithDocumentAndCancellationToken_ShouldDeleteOne()
{
// Arrange
var document = Fixture.Create<TestDocumentWithKey<int>>();
var count = Fixture.Create<long>();
var token = new CancellationToken(true);
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(x => x.DeleteOneAsync<TestDocumentWithKey<int>, int>(It.IsAny<TestDocumentWithKey<int>>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(count);
// Act
var result = await Sut.DeleteOneAsync<TestDocumentWithKey<int>, int>(document, token);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteOneAsync<TestDocumentWithKey<int>, int>(document, token), Times.Once);
}
[Fact]
public async Task Keyed_WithFilter_ShouldDeleteOne()
{
// Arrange
var count = Fixture.Create<long>();
var content = Fixture.Create<string>();
Expression<Func<TestDocumentWithKey<int>, bool>> filter = x => x.SomeContent == content;
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(x => x.DeleteOneAsync<TestDocumentWithKey<int>, int>(It.IsAny<Expression<Func<TestDocumentWithKey<int>, bool>>>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(count);
// Act
var result = await Sut.DeleteOneAsync<TestDocumentWithKey<int>, int>(filter);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteOneAsync<TestDocumentWithKey<int>, int>(filter, null, CancellationToken.None), Times.Once);
}
[Fact]
public async Task Keyed_WithFilterAndCancellationToken_ShouldDeleteOne()
{
// Arrange
var count = Fixture.Create<long>();
var content = Fixture.Create<string>();
var token = new CancellationToken(true);
Expression<Func<TestDocumentWithKey<int>, bool>> filter = x => x.SomeContent == content;
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(x => x.DeleteOneAsync<TestDocumentWithKey<int>, int>(It.IsAny<Expression<Func<TestDocumentWithKey<int>, bool>>>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(count);
// Act
var result = await Sut.DeleteOneAsync<TestDocumentWithKey<int>, int>(filter, token);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteOneAsync<TestDocumentWithKey<int>, int>(filter, null, token), Times.Once);
}
[Fact]
public async Task Keyed_WithFilterAndPartitionKey_ShouldDeleteOne()
{
// Arrange
var count = Fixture.Create<long>();
var content = Fixture.Create<string>();
var partitionKey = Fixture.Create<string>();
Expression<Func<TestDocumentWithKey<int>, bool>> filter = x => x.SomeContent == content;
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(x => x.DeleteOneAsync<TestDocumentWithKey<int>, int>(It.IsAny<Expression<Func<TestDocumentWithKey<int>, bool>>>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(count);
// Act
var result = await Sut.DeleteOneAsync<TestDocumentWithKey<int>, int>(filter, partitionKey);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteOneAsync<TestDocumentWithKey<int>, int>(filter, partitionKey, CancellationToken.None), Times.Once);
}
[Fact]
public async Task Keyed_WithFilterAndPartitionKeyAndCancellationToken_ShouldDeleteOne()
{
// Arrange
var count = Fixture.Create<long>();
var content = Fixture.Create<string>();
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
Expression<Func<TestDocumentWithKey<int>, bool>> filter = x => x.SomeContent == content;
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(x => x.DeleteOneAsync<TestDocumentWithKey<int>, int>(It.IsAny<Expression<Func<TestDocumentWithKey<int>, bool>>>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(count);
// Act
var result = await Sut.DeleteOneAsync<TestDocumentWithKey<int>, int>(filter, partitionKey, token);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteOneAsync<TestDocumentWithKey<int>, int>(filter, partitionKey, token), Times.Once);
}
#endregion
}
@@ -0,0 +1,317 @@
namespace CoreUnitTests.BaseMongoRepositoryTests.DeleteTests;
using System;
using System.Linq.Expressions;
using System.Threading;
using AutoFixture;
using FluentAssertions;
using Infrastructure;
using Infrastructure.Model;
using MongoDbGenericRepository.DataAccess.Delete;
using Moq;
using Xunit;
public class DeleteOneTests : TestMongoRepositoryContext
{
[Fact]
public void WithDocument_ShouldDeleteOne()
{
// Arrange
var document = Fixture.Create<TestDocument>();
var count = Fixture.Create<long>();
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(x => x.DeleteOne<TestDocument, Guid>(It.IsAny<TestDocument>(), It.IsAny<CancellationToken>()))
.Returns(count);
// Act
var result = Sut.DeleteOne(document);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteOne<TestDocument, Guid>(document, CancellationToken.None), Times.Once);
}
[Fact]
public void WithDocumentAndCancellationToken_ShouldDeleteOne()
{
// Arrange
var document = Fixture.Create<TestDocument>();
var count = Fixture.Create<long>();
var token = new CancellationToken(true);
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(x => x.DeleteOne<TestDocument, Guid>(It.IsAny<TestDocument>(), It.IsAny<CancellationToken>()))
.Returns(count);
// Act
var result = Sut.DeleteOne(document, token);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteOne<TestDocument, Guid>(document, token), Times.Once);
}
[Fact]
public void WithFilter_ShouldDeleteOne()
{
// Arrange
var count = Fixture.Create<long>();
var content = Fixture.Create<string>();
Expression<Func<TestDocument, bool>> filter = x => x.SomeContent == content;
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(x => x.DeleteOne<TestDocument, Guid>(It.IsAny<Expression<Func<TestDocument, bool>>>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.Returns(count);
// Act
var result = Sut.DeleteOne(filter);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteOne<TestDocument, Guid>(filter, null, CancellationToken.None), Times.Once);
}
[Fact]
public void WithFilterAndCancellationToken_ShouldDeleteOne()
{
// Arrange
var count = Fixture.Create<long>();
var content = Fixture.Create<string>();
var token = new CancellationToken(true);
Expression<Func<TestDocument, bool>> filter = x => x.SomeContent == content;
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(
x => x.DeleteOne<TestDocument, Guid>(
It.IsAny<Expression<Func<TestDocument, bool>>>(),
It.IsAny<string>(),
It.IsAny<CancellationToken>()))
.Returns(count);
// Act
var result = Sut.DeleteOne(filter, token);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteOne<TestDocument, Guid>(filter, null, token), Times.Once);
}
[Fact]
public void WithFilterAndPartitionKey_ShouldDeleteOne()
{
// Arrange
var count = Fixture.Create<long>();
var content = Fixture.Create<string>();
var partitionKey = Fixture.Create<string>();
Expression<Func<TestDocument, bool>> filter = x => x.SomeContent == content;
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(
x => x.DeleteOne<TestDocument, Guid>(
It.IsAny<Expression<Func<TestDocument, bool>>>(),
It.IsAny<string>(),
It.IsAny<CancellationToken>()))
.Returns(count);
// Act
var result = Sut.DeleteOne(filter, partitionKey);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteOne<TestDocument, Guid>(filter, partitionKey, CancellationToken.None), Times.Once);
}
[Fact]
public void WithFilterAndPartitionKeyAndCancellationToken_ShouldDeleteOne()
{
// Arrange
var count = Fixture.Create<long>();
var content = Fixture.Create<string>();
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
Expression<Func<TestDocument, bool>> filter = x => x.SomeContent == content;
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(
x => x.DeleteOne<TestDocument, Guid>(
It.IsAny<Expression<Func<TestDocument, bool>>>(),
It.IsAny<string>(),
It.IsAny<CancellationToken>()))
.Returns(count);
// Act
var result = Sut.DeleteOne(filter, partitionKey, token);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteOne<TestDocument, Guid>(filter, partitionKey, token), Times.Once);
}
[Fact]
public void WithKeyedDocument_ShouldDeleteOne()
{
// Arrange
var document = Fixture.Create<TestDocumentWithKey<int>>();
var count = Fixture.Create<long>();
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(x => x.DeleteOne<TestDocumentWithKey<int>, int>(It.IsAny<TestDocumentWithKey<int>>(), It.IsAny<CancellationToken>()))
.Returns(count);
// Act
var result = Sut.DeleteOne<TestDocumentWithKey<int>, int>(document);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteOne<TestDocumentWithKey<int>, int>(document, CancellationToken.None), Times.Once);
}
[Fact]
public void WithKeyedDocumentAndCancellationToken_ShouldDeleteOne()
{
// Arrange
var document = Fixture.Create<TestDocumentWithKey<int>>();
var count = Fixture.Create<long>();
var token = new CancellationToken(true);
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(x => x.DeleteOne<TestDocumentWithKey<int>, int>(It.IsAny<TestDocumentWithKey<int>>(), It.IsAny<CancellationToken>()))
.Returns(count);
// Act
var result = Sut.DeleteOne<TestDocumentWithKey<int>, int>(document, token);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteOne<TestDocumentWithKey<int>, int>(document, token), Times.Once);
}
[Fact]
public void Keyed_WithFilter_ShouldDeleteOne()
{
// Arrange
var count = Fixture.Create<long>();
var content = Fixture.Create<string>();
Expression<Func<TestDocumentWithKey<int>, bool>> filter = x => x.SomeContent == content;
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(
x => x.DeleteOne<TestDocumentWithKey<int>, int>(
It.IsAny<Expression<Func<TestDocumentWithKey<int>, bool>>>(),
It.IsAny<string>(),
It.IsAny<CancellationToken>()))
.Returns(count);
// Act
var result = Sut.DeleteOne<TestDocumentWithKey<int>, int>(filter);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteOne<TestDocumentWithKey<int>, int>(filter, null, CancellationToken.None), Times.Once);
}
[Fact]
public void Keyed_WithFilterAndCancellationToken_ShouldDeleteOne()
{
// Arrange
var count = Fixture.Create<long>();
var content = Fixture.Create<string>();
var token = new CancellationToken(true);
Expression<Func<TestDocumentWithKey<int>, bool>> filter = x => x.SomeContent == content;
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(
x => x.DeleteOne<TestDocumentWithKey<int>, int>(
It.IsAny<Expression<Func<TestDocumentWithKey<int>, bool>>>(),
It.IsAny<string>(),
It.IsAny<CancellationToken>()))
.Returns(count);
// Act
var result = Sut.DeleteOne<TestDocumentWithKey<int>, int>(filter, token);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteOne<TestDocumentWithKey<int>, int>(filter, null, token), Times.Once);
}
[Fact]
public void Keyed_WithFilterAndPartitionKey_ShouldDeleteOne()
{
// Arrange
var count = Fixture.Create<long>();
var content = Fixture.Create<string>();
var partitionKey = Fixture.Create<string>();
Expression<Func<TestDocumentWithKey<int>, bool>> filter = x => x.SomeContent == content;
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(
x => x.DeleteOne<TestDocumentWithKey<int>, int>(
It.IsAny<Expression<Func<TestDocumentWithKey<int>, bool>>>(),
It.IsAny<string>(),
It.IsAny<CancellationToken>()))
.Returns(count);
// Act
var result = Sut.DeleteOne<TestDocumentWithKey<int>, int>(filter, partitionKey);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteOne<TestDocumentWithKey<int>, int>(filter, partitionKey, CancellationToken.None), Times.Once);
}
[Fact]
public void Keyed_WithFilterAndPartitionKeyAndCancellationToken_ShouldDeleteOne()
{
// Arrange
var count = Fixture.Create<long>();
var content = Fixture.Create<string>();
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
Expression<Func<TestDocumentWithKey<int>, bool>> filter = x => x.SomeContent == content;
Eraser = new Mock<IMongoDbEraser>();
Eraser
.Setup(
x => x.DeleteOne<TestDocumentWithKey<int>, int>(
It.IsAny<Expression<Func<TestDocumentWithKey<int>, bool>>>(),
It.IsAny<string>(),
It.IsAny<CancellationToken>()))
.Returns(count);
// Act
var result = Sut.DeleteOne<TestDocumentWithKey<int>, int>(filter, partitionKey, token);
// Assert
result.Should().Be(count);
Eraser.Verify(x => x.DeleteOne<TestDocumentWithKey<int>, int>(filter, partitionKey, token), Times.Once);
}
}
@@ -0,0 +1,35 @@
using System;
using System.Threading;
using CoreUnitTests.Infrastructure;
using MongoDB.Bson;
using MongoDB.Driver;
using Moq;
namespace CoreUnitTests.BaseMongoRepositoryTests.IndexTests;
public class BaseIndexTests : TestMongoRepositoryContext
{
protected Mock<IAsyncCursor<BsonDocument>> SetupIndex<TDocument>(BsonDocument index, Mock<IMongoCollection<TDocument>> collection)
{
var asyncCursor = new Mock<IAsyncCursor<BsonDocument>>();
asyncCursor
.SetupSequence(x => x.MoveNextAsync(It.IsAny<CancellationToken>()))
.ReturnsAsync(true)
.ReturnsAsync(false);
asyncCursor
.SetupGet(x => x.Current)
.Returns(new[] { index });
var indexManager = new Mock<IMongoIndexManager<TDocument>>();
indexManager
.Setup(x => x.ListAsync(It.IsAny<CancellationToken>()))
.ReturnsAsync(asyncCursor.Object);
collection
.SetupGet(x => x.Indexes)
.Returns(indexManager.Object);
return asyncCursor;
}
}
@@ -0,0 +1,294 @@
using System;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using AutoFixture;
using CoreUnitTests.Infrastructure.Model;
using MongoDbGenericRepository.DataAccess.Index;
using MongoDbGenericRepository.Models;
using Moq;
using Xunit;
namespace CoreUnitTests.BaseMongoRepositoryTests.IndexTests;
public class CreateAscendingIndexAsyncTests : BaseIndexTests
{
private readonly Expression<Func<TestDocumentWithKey<int>, object>> keyedFieldExpression = t => t.SomeContent2;
private readonly Expression<Func<TestDocument, object>> fieldExpression = t => t.SomeContent2;
[Fact]
public async Task WithFieldExpression_CreatesIndex()
{
// Arrange
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateAscendingIndexAsync(fieldExpression);
// Assert
IndexHandler.Verify(
x => x.CreateAscendingIndexAsync<TestDocument, Guid>(fieldExpression, null, null, CancellationToken.None));
}
[Fact]
public async Task WithFieldExpressionAndCancellationToken_CreatesIndex()
{
// Arrange
var token = new CancellationToken(true);
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateAscendingIndexAsync(fieldExpression, token);
// Assert
IndexHandler.Verify(
x => x.CreateAscendingIndexAsync<TestDocument, Guid>(fieldExpression, null, null, token));
}
[Fact]
public async Task WithFieldExpressionAndOptions_CreatesIndex()
{
// Arrange
var indexName = Fixture.Create<string>();
var options = new IndexCreationOptions { Name = indexName };
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateAscendingIndexAsync(fieldExpression, options);
// Assert
IndexHandler.Verify(
x => x.CreateAscendingIndexAsync<TestDocument, Guid>(
fieldExpression, options, null, CancellationToken.None));
}
[Fact]
public async Task WithFieldExpressionAndOptionsAndCancellationToken_CreatesIndex()
{
// Arrange
var indexName = Fixture.Create<string>();
var options = new IndexCreationOptions { Name = indexName };
var token = new CancellationToken(true);
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateAscendingIndexAsync(fieldExpression, options, token);
// Assert
IndexHandler.Verify(
x => x.CreateAscendingIndexAsync<TestDocument, Guid>(
fieldExpression, options, null, token));
}
[Fact]
public async Task WithFieldExpressionAndPartitionKey_CreatesIndex()
{
// Arrange
var partitionKey = Fixture.Create<string>();
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateAscendingIndexAsync(fieldExpression, partitionKey);
// Assert
IndexHandler.Verify(
x => x.CreateAscendingIndexAsync<TestDocument, Guid>(
fieldExpression, null, partitionKey, CancellationToken.None));
}
[Fact]
public async Task WithFieldExpressionAndPartitionKeyAndCancellationToken_CreatesIndex()
{
// Arrange
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateAscendingIndexAsync(fieldExpression, partitionKey, token);
// Assert
IndexHandler.Verify(
x => x.CreateAscendingIndexAsync<TestDocument, Guid>(
fieldExpression, null, partitionKey, token));
}
[Fact]
public async Task WithFieldExpressionAndOptionsAndPartitionKey_CreatesIndex()
{
// Arrange
var partitionKey = Fixture.Create<string>();
var indexName = Fixture.Create<string>();
var options = new IndexCreationOptions { Name = indexName };
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateAscendingIndexAsync(fieldExpression, options, partitionKey);
// Assert
IndexHandler.Verify(
x => x.CreateAscendingIndexAsync<TestDocument, Guid>(
fieldExpression, options, partitionKey, CancellationToken.None));
}
[Fact]
public async Task WithFieldExpressionAndOptionsAndPartitionKeyAndCancellationToken_CreatesIndex()
{
// Arrange
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
var indexName = Fixture.Create<string>();
var options = new IndexCreationOptions { Name = indexName };
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateAscendingIndexAsync(fieldExpression, options, partitionKey, token);
// Assert
IndexHandler.Verify(
x => x.CreateAscendingIndexAsync<TestDocument, Guid>(
fieldExpression, options, partitionKey, token));
}
#region Keyed
[Fact]
public async Task Keyed_WithFieldExpression_CreatesIndex()
{
// Arrange
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateAscendingIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpression);
// Assert
IndexHandler.Verify(
x => x.CreateAscendingIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpression, null, null, CancellationToken.None));
}
[Fact]
public async Task Keyed_WithFieldExpressionAndCancellationToken_CreatesIndex()
{
// Arrange
var token = new CancellationToken(true);
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateAscendingIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpression, token);
// Assert
IndexHandler.Verify(
x => x.CreateAscendingIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpression, null, null, token));
}
[Fact]
public async Task Keyed_WithFieldExpressionAndOptions_CreatesIndex()
{
// Arrange
var indexName = Fixture.Create<string>();
var options = new IndexCreationOptions { Name = indexName };
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateAscendingIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpression, options);
// Assert
IndexHandler.Verify(
x => x.CreateAscendingIndexAsync<TestDocumentWithKey<int>, int>(
keyedFieldExpression, options, null, CancellationToken.None));
}
[Fact]
public async Task Keyed_WithFieldExpressionAndOptionsAndCancellationToken_CreatesIndex()
{
// Arrange
var indexName = Fixture.Create<string>();
var options = new IndexCreationOptions { Name = indexName };
var token = new CancellationToken(true);
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateAscendingIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpression, options, token);
// Assert
IndexHandler.Verify(
x => x.CreateAscendingIndexAsync<TestDocumentWithKey<int>, int>(
keyedFieldExpression, options, null, token));
}
[Fact]
public async Task Keyed_WithFieldExpressionAndPartitionKey_CreatesIndex()
{
// Arrange
var partitionKey = Fixture.Create<string>();
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateAscendingIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpression, partitionKey);
// Assert
IndexHandler.Verify(
x => x.CreateAscendingIndexAsync<TestDocumentWithKey<int>, int>(
keyedFieldExpression, null, partitionKey, CancellationToken.None));
}
[Fact]
public async Task Keyed_WithFieldExpressionAndPartitionKeyAndCancellationToken_CreatesIndex()
{
// Arrange
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateAscendingIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpression, partitionKey, token);
// Assert
IndexHandler.Verify(
x => x.CreateAscendingIndexAsync<TestDocumentWithKey<int>, int>(
keyedFieldExpression, null, partitionKey, token));
}
[Fact]
public async Task Keyed_WithFieldExpressionAndOptionsAndPartitionKey_CreatesIndex()
{
// Arrange
var partitionKey = Fixture.Create<string>();
var indexName = Fixture.Create<string>();
var options = new IndexCreationOptions { Name = indexName };
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateAscendingIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpression, options, partitionKey);
// Assert
IndexHandler.Verify(
x => x.CreateAscendingIndexAsync<TestDocumentWithKey<int>, int>(
keyedFieldExpression, options, partitionKey, CancellationToken.None));
}
[Fact]
public async Task Keyed_WithFieldExpressionAndOptionsAndPartitionKeyAndCancellationToken_CreatesIndex()
{
// Arrange
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
var indexName = Fixture.Create<string>();
var options = new IndexCreationOptions { Name = indexName };
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateAscendingIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpression, options, partitionKey, token);
// Assert
IndexHandler.Verify(
x => x.CreateAscendingIndexAsync<TestDocumentWithKey<int>, int>(
keyedFieldExpression, options, partitionKey, token));
}
#endregion
}
@@ -0,0 +1,295 @@
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading.Tasks;
using AutoFixture;
using CoreUnitTests.Infrastructure.Model;
using MongoDbGenericRepository.DataAccess.Index;
using MongoDbGenericRepository.Models;
using Moq;
using Xunit;
using CancellationToken = System.Threading.CancellationToken;
namespace CoreUnitTests.BaseMongoRepositoryTests.IndexTests;
public class CreateCombinedTextIndexAsyncTests : BaseIndexTests
{
private readonly List<Expression<Func<TestDocument, object>>> fieldExpressions = new() {t => t.SomeContent2, t => t.SomeContent3};
private readonly List<Expression<Func<TestDocumentWithKey<int>, object>>> keyedFieldExpressions = new() {t => t.SomeContent2, t => t.SomeContent3};
[Fact]
public async Task WithFieldExpression_CreatesIndex()
{
// Arrange
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateCombinedTextIndexAsync(fieldExpressions);
// Assert
IndexHandler.Verify(
x => x.CreateCombinedTextIndexAsync<TestDocument, Guid>(fieldExpressions, null, null, CancellationToken.None));
}
[Fact]
public async Task WithFieldExpressionAndCancellationToken_CreatesIndex()
{
// Arrange
var token = new CancellationToken(true);
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateCombinedTextIndexAsync(fieldExpressions, token);
// Assert
IndexHandler.Verify(
x => x.CreateCombinedTextIndexAsync<TestDocument, Guid>(fieldExpressions, null, null, token));
}
[Fact]
public async Task WithFieldExpressionAndOptions_CreatesIndex()
{
// Arrange
var indexName = Fixture.Create<string>();
var options = new IndexCreationOptions { Name = indexName };
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateCombinedTextIndexAsync(fieldExpressions, options);
// Assert
IndexHandler.Verify(
x => x.CreateCombinedTextIndexAsync<TestDocument, Guid>(
fieldExpressions, options, null, CancellationToken.None));
}
[Fact]
public async Task WithFieldExpressionAndOptionsAndCancellationToken_CreatesIndex()
{
// Arrange
var indexName = Fixture.Create<string>();
var options = new IndexCreationOptions { Name = indexName };
var token = new CancellationToken(true);
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateCombinedTextIndexAsync(fieldExpressions, options, token);
// Assert
IndexHandler.Verify(
x => x.CreateCombinedTextIndexAsync<TestDocument, Guid>(
fieldExpressions, options, null, token));
}
[Fact]
public async Task WithFieldExpressionAndPartitionKey_CreatesIndex()
{
// Arrange
var partitionKey = Fixture.Create<string>();
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateCombinedTextIndexAsync(fieldExpressions, partitionKey);
// Assert
IndexHandler.Verify(
x => x.CreateCombinedTextIndexAsync<TestDocument, Guid>(
fieldExpressions, null, partitionKey, CancellationToken.None));
}
[Fact]
public async Task WithFieldExpressionAndPartitionKeyAndCancellationToken_CreatesIndex()
{
// Arrange
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateCombinedTextIndexAsync(fieldExpressions, partitionKey, token);
// Assert
IndexHandler.Verify(
x => x.CreateCombinedTextIndexAsync<TestDocument, Guid>(
fieldExpressions, null, partitionKey, token));
}
[Fact]
public async Task WithFieldExpressionAndOptionsAndPartitionKey_CreatesIndex()
{
// Arrange
var partitionKey = Fixture.Create<string>();
var indexName = Fixture.Create<string>();
var options = new IndexCreationOptions { Name = indexName };
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateCombinedTextIndexAsync(fieldExpressions, options, partitionKey);
// Assert
IndexHandler.Verify(
x => x.CreateCombinedTextIndexAsync<TestDocument, Guid>(
fieldExpressions, options, partitionKey, CancellationToken.None));
}
[Fact]
public async Task WithFieldExpressionAndOptionsAndPartitionKeyAndCancellationToken_CreatesIndex()
{
// Arrange
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
var indexName = Fixture.Create<string>();
var options = new IndexCreationOptions { Name = indexName };
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateCombinedTextIndexAsync(fieldExpressions, options, partitionKey, token);
// Assert
IndexHandler.Verify(
x => x.CreateCombinedTextIndexAsync<TestDocument, Guid>(
fieldExpressions, options, partitionKey, token));
}
#region Keyed
[Fact]
public async Task Keyed_WithKeyedFieldExpression_CreatesIndex()
{
// Arrange
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateCombinedTextIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpressions);
// Assert
IndexHandler.Verify(
x => x.CreateCombinedTextIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpressions, null, null, CancellationToken.None));
}
[Fact]
public async Task Keyed_WithKeyedFieldExpressionAndCancellationToken_CreatesIndex()
{
// Arrange
var token = new CancellationToken(true);
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateCombinedTextIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpressions, token);
// Assert
IndexHandler.Verify(
x => x.CreateCombinedTextIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpressions, null, null, token));
}
[Fact]
public async Task Keyed_WithKeyedFieldExpressionAndOptions_CreatesIndex()
{
// Arrange
var indexName = Fixture.Create<string>();
var options = new IndexCreationOptions { Name = indexName };
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateCombinedTextIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpressions, options);
// Assert
IndexHandler.Verify(
x => x.CreateCombinedTextIndexAsync<TestDocumentWithKey<int>, int>(
keyedFieldExpressions, options, null, CancellationToken.None));
}
[Fact]
public async Task Keyed_WithKeyedFieldExpressionAndOptionsAndCancellationToken_CreatesIndex()
{
// Arrange
var indexName = Fixture.Create<string>();
var options = new IndexCreationOptions { Name = indexName };
var token = new CancellationToken(true);
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateCombinedTextIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpressions, options, token);
// Assert
IndexHandler.Verify(
x => x.CreateCombinedTextIndexAsync<TestDocumentWithKey<int>, int>(
keyedFieldExpressions, options, null, token));
}
[Fact]
public async Task Keyed_WithKeyedFieldExpressionAndPartitionKey_CreatesIndex()
{
// Arrange
var partitionKey = Fixture.Create<string>();
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateCombinedTextIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpressions, partitionKey);
// Assert
IndexHandler.Verify(
x => x.CreateCombinedTextIndexAsync<TestDocumentWithKey<int>, int>(
keyedFieldExpressions, null, partitionKey, CancellationToken.None));
}
[Fact]
public async Task Keyed_WithKeyedFieldExpressionAndPartitionKeyAndCancellationToken_CreatesIndex()
{
// Arrange
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateCombinedTextIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpressions, partitionKey, token);
// Assert
IndexHandler.Verify(
x => x.CreateCombinedTextIndexAsync<TestDocumentWithKey<int>, int>(
keyedFieldExpressions, null, partitionKey, token));
}
[Fact]
public async Task Keyed_WithKeyedFieldExpressionAndOptionsAndPartitionKey_CreatesIndex()
{
// Arrange
var partitionKey = Fixture.Create<string>();
var indexName = Fixture.Create<string>();
var options = new IndexCreationOptions { Name = indexName };
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateCombinedTextIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpressions, options, partitionKey);
// Assert
IndexHandler.Verify(
x => x.CreateCombinedTextIndexAsync<TestDocumentWithKey<int>, int>(
keyedFieldExpressions, options, partitionKey, CancellationToken.None));
}
[Fact]
public async Task Keyed_WithKeyedFieldExpressionAndOptionsAndPartitionKeyAndCancellationToken_CreatesIndex()
{
// Arrange
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
var indexName = Fixture.Create<string>();
var options = new IndexCreationOptions { Name = indexName };
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateCombinedTextIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpressions, options, partitionKey, token);
// Assert
IndexHandler.Verify(
x => x.CreateCombinedTextIndexAsync<TestDocumentWithKey<int>, int>(
keyedFieldExpressions, options, partitionKey, token));
}
#endregion
}
@@ -0,0 +1,294 @@
using System;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using AutoFixture;
using CoreUnitTests.Infrastructure.Model;
using MongoDbGenericRepository.DataAccess.Index;
using MongoDbGenericRepository.Models;
using Moq;
using Xunit;
namespace CoreUnitTests.BaseMongoRepositoryTests.IndexTests;
public class CreateDescendingIndexAsyncTests : BaseIndexTests
{
private readonly Expression<Func<TestDocumentWithKey<int>, object>> keyedFieldExpression = t => t.SomeContent2;
private readonly Expression<Func<TestDocument, object>> fieldExpression = t => t.SomeContent2;
[Fact]
public async Task WithFieldExpression_CreatesIndex()
{
// Arrange
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateDescendingIndexAsync(fieldExpression);
// Assert
IndexHandler.Verify(
x => x.CreateDescendingIndexAsync<TestDocument, Guid>(fieldExpression, null, null, CancellationToken.None));
}
[Fact]
public async Task WithFieldExpressionAndCancellationToken_CreatesIndex()
{
// Arrange
var token = new CancellationToken(true);
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateDescendingIndexAsync(fieldExpression, token);
// Assert
IndexHandler.Verify(
x => x.CreateDescendingIndexAsync<TestDocument, Guid>(fieldExpression, null, null, token));
}
[Fact]
public async Task WithFieldExpressionAndOptions_CreatesIndex()
{
// Arrange
var indexName = Fixture.Create<string>();
var options = new IndexCreationOptions { Name = indexName };
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateDescendingIndexAsync(fieldExpression, options);
// Assert
IndexHandler.Verify(
x => x.CreateDescendingIndexAsync<TestDocument, Guid>(
fieldExpression, options, null, CancellationToken.None));
}
[Fact]
public async Task WithFieldExpressionAndOptionsAndCancellationToken_CreatesIndex()
{
// Arrange
var indexName = Fixture.Create<string>();
var options = new IndexCreationOptions { Name = indexName };
var token = new CancellationToken(true);
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateDescendingIndexAsync(fieldExpression, options, token);
// Assert
IndexHandler.Verify(
x => x.CreateDescendingIndexAsync<TestDocument, Guid>(
fieldExpression, options, null, token));
}
[Fact]
public async Task WithFieldExpressionAndPartitionKey_CreatesIndex()
{
// Arrange
var partitionKey = Fixture.Create<string>();
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateDescendingIndexAsync(fieldExpression, partitionKey);
// Assert
IndexHandler.Verify(
x => x.CreateDescendingIndexAsync<TestDocument, Guid>(
fieldExpression, null, partitionKey, CancellationToken.None));
}
[Fact]
public async Task WithFieldExpressionAndPartitionKeyAndCancellationToken_CreatesIndex()
{
// Arrange
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateDescendingIndexAsync(fieldExpression, partitionKey, token);
// Assert
IndexHandler.Verify(
x => x.CreateDescendingIndexAsync<TestDocument, Guid>(
fieldExpression, null, partitionKey, token));
}
[Fact]
public async Task WithFieldExpressionAndOptionsAndPartitionKey_CreatesIndex()
{
// Arrange
var partitionKey = Fixture.Create<string>();
var indexName = Fixture.Create<string>();
var options = new IndexCreationOptions { Name = indexName };
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateDescendingIndexAsync(fieldExpression, options, partitionKey);
// Assert
IndexHandler.Verify(
x => x.CreateDescendingIndexAsync<TestDocument, Guid>(
fieldExpression, options, partitionKey, CancellationToken.None));
}
[Fact]
public async Task WithFieldExpressionAndOptionsAndPartitionKeyAndCancellationToken_CreatesIndex()
{
// Arrange
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
var indexName = Fixture.Create<string>();
var options = new IndexCreationOptions { Name = indexName };
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateDescendingIndexAsync(fieldExpression, options, partitionKey, token);
// Assert
IndexHandler.Verify(
x => x.CreateDescendingIndexAsync<TestDocument, Guid>(
fieldExpression, options, partitionKey, token));
}
#region Keyed
[Fact]
public async Task Keyed_WithFieldExpression_CreatesIndex()
{
// Arrange
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateDescendingIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpression);
// Assert
IndexHandler.Verify(
x => x.CreateDescendingIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpression, null, null, CancellationToken.None));
}
[Fact]
public async Task Keyed_WithFieldExpressionAndCancellationToken_CreatesIndex()
{
// Arrange
var token = new CancellationToken(true);
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateDescendingIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpression, token);
// Assert
IndexHandler.Verify(
x => x.CreateDescendingIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpression, null, null, token));
}
[Fact]
public async Task Keyed_WithFieldExpressionAndOptions_CreatesIndex()
{
// Arrange
var indexName = Fixture.Create<string>();
var options = new IndexCreationOptions { Name = indexName };
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateDescendingIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpression, options);
// Assert
IndexHandler.Verify(
x => x.CreateDescendingIndexAsync<TestDocumentWithKey<int>, int>(
keyedFieldExpression, options, null, CancellationToken.None));
}
[Fact]
public async Task Keyed_WithFieldExpressionAndOptionsAndCancellationToken_CreatesIndex()
{
// Arrange
var indexName = Fixture.Create<string>();
var options = new IndexCreationOptions { Name = indexName };
var token = new CancellationToken(true);
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateDescendingIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpression, options, token);
// Assert
IndexHandler.Verify(
x => x.CreateDescendingIndexAsync<TestDocumentWithKey<int>, int>(
keyedFieldExpression, options, null, token));
}
[Fact]
public async Task Keyed_WithFieldExpressionAndPartitionKey_CreatesIndex()
{
// Arrange
var partitionKey = Fixture.Create<string>();
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateDescendingIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpression, partitionKey);
// Assert
IndexHandler.Verify(
x => x.CreateDescendingIndexAsync<TestDocumentWithKey<int>, int>(
keyedFieldExpression, null, partitionKey, CancellationToken.None));
}
[Fact]
public async Task Keyed_WithFieldExpressionAndPartitionKeyAndCancellationToken_CreatesIndex()
{
// Arrange
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateDescendingIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpression, partitionKey, token);
// Assert
IndexHandler.Verify(
x => x.CreateDescendingIndexAsync<TestDocumentWithKey<int>, int>(
keyedFieldExpression, null, partitionKey, token));
}
[Fact]
public async Task Keyed_WithFieldExpressionAndOptionsAndPartitionKey_CreatesIndex()
{
// Arrange
var partitionKey = Fixture.Create<string>();
var indexName = Fixture.Create<string>();
var options = new IndexCreationOptions { Name = indexName };
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateDescendingIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpression, options, partitionKey);
// Assert
IndexHandler.Verify(
x => x.CreateDescendingIndexAsync<TestDocumentWithKey<int>, int>(
keyedFieldExpression, options, partitionKey, CancellationToken.None));
}
[Fact]
public async Task Keyed_WithFieldExpressionAndOptionsAndPartitionKeyAndCancellationToken_CreatesIndex()
{
// Arrange
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
var indexName = Fixture.Create<string>();
var options = new IndexCreationOptions { Name = indexName };
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateDescendingIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpression, options, partitionKey, token);
// Assert
IndexHandler.Verify(
x => x.CreateDescendingIndexAsync<TestDocumentWithKey<int>, int>(
keyedFieldExpression, options, partitionKey, token));
}
#endregion
}
@@ -0,0 +1,294 @@
using System;
using System.Linq.Expressions;
using System.Threading.Tasks;
using AutoFixture;
using CoreUnitTests.Infrastructure.Model;
using MongoDbGenericRepository.DataAccess.Index;
using MongoDbGenericRepository.Models;
using Moq;
using Xunit;
using CancellationToken = System.Threading.CancellationToken;
namespace CoreUnitTests.BaseMongoRepositoryTests.IndexTests;
public class CreateHashedIndexAsyncTests : BaseIndexTests
{
private readonly Expression<Func<TestDocument, object>> fieldExpression = t => t.SomeContent2;
private readonly Expression<Func<TestDocumentWithKey<int>, object>> keyedFieldExpression = t => t.SomeContent2;
[Fact]
public async Task WithFieldExpression_CreatesIndex()
{
// Arrange
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateHashedIndexAsync(fieldExpression);
// Assert
IndexHandler.Verify(
x => x.CreateHashedIndexAsync<TestDocument, Guid>(fieldExpression, null, null, CancellationToken.None));
}
[Fact]
public async Task WithFieldExpressionAndCancellationToken_CreatesIndex()
{
// Arrange
var token = new CancellationToken(true);
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateHashedIndexAsync(fieldExpression, token);
// Assert
IndexHandler.Verify(
x => x.CreateHashedIndexAsync<TestDocument, Guid>(fieldExpression, null, null, token));
}
[Fact]
public async Task WithFieldExpressionAndOptions_CreatesIndex()
{
// Arrange
var indexName = Fixture.Create<string>();
var options = new IndexCreationOptions { Name = indexName };
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateHashedIndexAsync(fieldExpression, options);
// Assert
IndexHandler.Verify(
x => x.CreateHashedIndexAsync<TestDocument, Guid>(
fieldExpression, options, null, CancellationToken.None));
}
[Fact]
public async Task WithFieldExpressionAndOptionsAndCancellationToken_CreatesIndex()
{
// Arrange
var indexName = Fixture.Create<string>();
var options = new IndexCreationOptions { Name = indexName };
var token = new CancellationToken(true);
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateHashedIndexAsync(fieldExpression, options, token);
// Assert
IndexHandler.Verify(
x => x.CreateHashedIndexAsync<TestDocument, Guid>(
fieldExpression, options, null, token));
}
[Fact]
public async Task WithFieldExpressionAndPartitionKey_CreatesIndex()
{
// Arrange
var partitionKey = Fixture.Create<string>();
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateHashedIndexAsync(fieldExpression, partitionKey);
// Assert
IndexHandler.Verify(
x => x.CreateHashedIndexAsync<TestDocument, Guid>(
fieldExpression, null, partitionKey, CancellationToken.None));
}
[Fact]
public async Task WithFieldExpressionAndPartitionKeyAndCancellationToken_CreatesIndex()
{
// Arrange
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateHashedIndexAsync(fieldExpression, partitionKey, token);
// Assert
IndexHandler.Verify(
x => x.CreateHashedIndexAsync<TestDocument, Guid>(
fieldExpression, null, partitionKey, token));
}
[Fact]
public async Task WithFieldExpressionAndOptionsAndPartitionKey_CreatesIndex()
{
// Arrange
var partitionKey = Fixture.Create<string>();
var indexName = Fixture.Create<string>();
var options = new IndexCreationOptions { Name = indexName };
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateHashedIndexAsync(fieldExpression, options, partitionKey);
// Assert
IndexHandler.Verify(
x => x.CreateHashedIndexAsync<TestDocument, Guid>(
fieldExpression, options, partitionKey, CancellationToken.None));
}
[Fact]
public async Task WithFieldExpressionAndOptionsAndPartitionKeyAndCancellationToken_CreatesIndex()
{
// Arrange
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
var indexName = Fixture.Create<string>();
var options = new IndexCreationOptions { Name = indexName };
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateHashedIndexAsync(fieldExpression, options, partitionKey, token);
// Assert
IndexHandler.Verify(
x => x.CreateHashedIndexAsync<TestDocument, Guid>(
fieldExpression, options, partitionKey, token));
}
#region Keyed
[Fact]
public async Task Keyed_WithKeyedFieldExpression_CreatesIndex()
{
// Arrange
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateHashedIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpression);
// Assert
IndexHandler.Verify(
x => x.CreateHashedIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpression, null, null, CancellationToken.None));
}
[Fact]
public async Task Keyed_WithKeyedFieldExpressionAndCancellationToken_CreatesIndex()
{
// Arrange
var token = new CancellationToken(true);
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateHashedIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpression, token);
// Assert
IndexHandler.Verify(
x => x.CreateHashedIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpression, null, null, token));
}
[Fact]
public async Task Keyed_WithKeyedFieldExpressionAndOptions_CreatesIndex()
{
// Arrange
var indexName = Fixture.Create<string>();
var options = new IndexCreationOptions { Name = indexName };
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateHashedIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpression, options);
// Assert
IndexHandler.Verify(
x => x.CreateHashedIndexAsync<TestDocumentWithKey<int>, int>(
keyedFieldExpression, options, null, CancellationToken.None));
}
[Fact]
public async Task Keyed_WithKeyedFieldExpressionAndOptionsAndCancellationToken_CreatesIndex()
{
// Arrange
var indexName = Fixture.Create<string>();
var options = new IndexCreationOptions { Name = indexName };
var token = new CancellationToken(true);
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateHashedIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpression, options, token);
// Assert
IndexHandler.Verify(
x => x.CreateHashedIndexAsync<TestDocumentWithKey<int>, int>(
keyedFieldExpression, options, null, token));
}
[Fact]
public async Task Keyed_WithKeyedFieldExpressionAndPartitionKey_CreatesIndex()
{
// Arrange
var partitionKey = Fixture.Create<string>();
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateHashedIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpression, partitionKey);
// Assert
IndexHandler.Verify(
x => x.CreateHashedIndexAsync<TestDocumentWithKey<int>, int>(
keyedFieldExpression, null, partitionKey, CancellationToken.None));
}
[Fact]
public async Task Keyed_WithKeyedFieldExpressionAndPartitionKeyAndCancellationToken_CreatesIndex()
{
// Arrange
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateHashedIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpression, partitionKey, token);
// Assert
IndexHandler.Verify(
x => x.CreateHashedIndexAsync<TestDocumentWithKey<int>, int>(
keyedFieldExpression, null, partitionKey, token));
}
[Fact]
public async Task Keyed_WithKeyedFieldExpressionAndOptionsAndPartitionKey_CreatesIndex()
{
// Arrange
var partitionKey = Fixture.Create<string>();
var indexName = Fixture.Create<string>();
var options = new IndexCreationOptions { Name = indexName };
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateHashedIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpression, options, partitionKey);
// Assert
IndexHandler.Verify(
x => x.CreateHashedIndexAsync<TestDocumentWithKey<int>, int>(
keyedFieldExpression, options, partitionKey, CancellationToken.None));
}
[Fact]
public async Task Keyed_WithKeyedFieldExpressionAndOptionsAndPartitionKeyAndCancellationToken_CreatesIndex()
{
// Arrange
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
var indexName = Fixture.Create<string>();
var options = new IndexCreationOptions { Name = indexName };
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateHashedIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpression, options, partitionKey, token);
// Assert
IndexHandler.Verify(
x => x.CreateHashedIndexAsync<TestDocumentWithKey<int>, int>(
keyedFieldExpression, options, partitionKey, token));
}
#endregion
}
@@ -0,0 +1,294 @@
using System;
using System.Linq.Expressions;
using System.Threading.Tasks;
using AutoFixture;
using CoreUnitTests.Infrastructure.Model;
using MongoDbGenericRepository.DataAccess.Index;
using MongoDbGenericRepository.Models;
using Moq;
using Xunit;
using CancellationToken = System.Threading.CancellationToken;
namespace CoreUnitTests.BaseMongoRepositoryTests.IndexTests;
public class CreateTextIndexAsyncTests : BaseIndexTests
{
private readonly Expression<Func<TestDocument, object>> fieldExpression = t => t.SomeContent2;
private readonly Expression<Func<TestDocumentWithKey<int>, object>> keyedFieldExpression = t => t.SomeContent2;
[Fact]
public async Task WithFieldExpression_CreatesIndex()
{
// Arrange
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateTextIndexAsync(fieldExpression);
// Assert
IndexHandler.Verify(
x => x.CreateTextIndexAsync<TestDocument, Guid>(fieldExpression, null, null, CancellationToken.None));
}
[Fact]
public async Task WithFieldExpressionAndCancellationToken_CreatesIndex()
{
// Arrange
var token = new CancellationToken(true);
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateTextIndexAsync(fieldExpression, token);
// Assert
IndexHandler.Verify(
x => x.CreateTextIndexAsync<TestDocument, Guid>(fieldExpression, null, null, token));
}
[Fact]
public async Task WithFieldExpressionAndOptions_CreatesIndex()
{
// Arrange
var indexName = Fixture.Create<string>();
var options = new IndexCreationOptions { Name = indexName };
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateTextIndexAsync(fieldExpression, options);
// Assert
IndexHandler.Verify(
x => x.CreateTextIndexAsync<TestDocument, Guid>(
fieldExpression, options, null, CancellationToken.None));
}
[Fact]
public async Task WithFieldExpressionAndOptionsAndCancellationToken_CreatesIndex()
{
// Arrange
var indexName = Fixture.Create<string>();
var options = new IndexCreationOptions { Name = indexName };
var token = new CancellationToken(true);
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateTextIndexAsync(fieldExpression, options, token);
// Assert
IndexHandler.Verify(
x => x.CreateTextIndexAsync<TestDocument, Guid>(
fieldExpression, options, null, token));
}
[Fact]
public async Task WithFieldExpressionAndPartitionKey_CreatesIndex()
{
// Arrange
var partitionKey = Fixture.Create<string>();
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateTextIndexAsync(fieldExpression, partitionKey);
// Assert
IndexHandler.Verify(
x => x.CreateTextIndexAsync<TestDocument, Guid>(
fieldExpression, null, partitionKey, CancellationToken.None));
}
[Fact]
public async Task WithFieldExpressionAndPartitionKeyAndCancellationToken_CreatesIndex()
{
// Arrange
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateTextIndexAsync(fieldExpression, partitionKey, token);
// Assert
IndexHandler.Verify(
x => x.CreateTextIndexAsync<TestDocument, Guid>(
fieldExpression, null, partitionKey, token));
}
[Fact]
public async Task WithFieldExpressionAndOptionsAndPartitionKey_CreatesIndex()
{
// Arrange
var partitionKey = Fixture.Create<string>();
var indexName = Fixture.Create<string>();
var options = new IndexCreationOptions { Name = indexName };
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateTextIndexAsync(fieldExpression, options, partitionKey);
// Assert
IndexHandler.Verify(
x => x.CreateTextIndexAsync<TestDocument, Guid>(
fieldExpression, options, partitionKey, CancellationToken.None));
}
[Fact]
public async Task WithFieldExpressionAndOptionsAndPartitionKeyAndCancellationToken_CreatesIndex()
{
// Arrange
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
var indexName = Fixture.Create<string>();
var options = new IndexCreationOptions { Name = indexName };
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateTextIndexAsync(fieldExpression, options, partitionKey, token);
// Assert
IndexHandler.Verify(
x => x.CreateTextIndexAsync<TestDocument, Guid>(
fieldExpression, options, partitionKey, token));
}
#region Keyed
[Fact]
public async Task Keyed_WithKeyedFieldExpression_CreatesIndex()
{
// Arrange
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateTextIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpression);
// Assert
IndexHandler.Verify(
x => x.CreateTextIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpression, null, null, CancellationToken.None));
}
[Fact]
public async Task Keyed_WithKeyedFieldExpressionAndCancellationToken_CreatesIndex()
{
// Arrange
var token = new CancellationToken(true);
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateTextIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpression, token);
// Assert
IndexHandler.Verify(
x => x.CreateTextIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpression, null, null, token));
}
[Fact]
public async Task Keyed_WithKeyedFieldExpressionAndOptions_CreatesIndex()
{
// Arrange
var indexName = Fixture.Create<string>();
var options = new IndexCreationOptions { Name = indexName };
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateTextIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpression, options);
// Assert
IndexHandler.Verify(
x => x.CreateTextIndexAsync<TestDocumentWithKey<int>, int>(
keyedFieldExpression, options, null, CancellationToken.None));
}
[Fact]
public async Task Keyed_WithKeyedFieldExpressionAndOptionsAndCancellationToken_CreatesIndex()
{
// Arrange
var indexName = Fixture.Create<string>();
var options = new IndexCreationOptions { Name = indexName };
var token = new CancellationToken(true);
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateTextIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpression, options, token);
// Assert
IndexHandler.Verify(
x => x.CreateTextIndexAsync<TestDocumentWithKey<int>, int>(
keyedFieldExpression, options, null, token));
}
[Fact]
public async Task Keyed_WithKeyedFieldExpressionAndPartitionKey_CreatesIndex()
{
// Arrange
var partitionKey = Fixture.Create<string>();
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateTextIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpression, partitionKey);
// Assert
IndexHandler.Verify(
x => x.CreateTextIndexAsync<TestDocumentWithKey<int>, int>(
keyedFieldExpression, null, partitionKey, CancellationToken.None));
}
[Fact]
public async Task Keyed_WithKeyedFieldExpressionAndPartitionKeyAndCancellationToken_CreatesIndex()
{
// Arrange
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateTextIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpression, partitionKey, token);
// Assert
IndexHandler.Verify(
x => x.CreateTextIndexAsync<TestDocumentWithKey<int>, int>(
keyedFieldExpression, null, partitionKey, token));
}
[Fact]
public async Task Keyed_WithKeyedFieldExpressionAndOptionsAndPartitionKey_CreatesIndex()
{
// Arrange
var partitionKey = Fixture.Create<string>();
var indexName = Fixture.Create<string>();
var options = new IndexCreationOptions { Name = indexName };
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateTextIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpression, options, partitionKey);
// Assert
IndexHandler.Verify(
x => x.CreateTextIndexAsync<TestDocumentWithKey<int>, int>(
keyedFieldExpression, options, partitionKey, CancellationToken.None));
}
[Fact]
public async Task Keyed_WithKeyedFieldExpressionAndOptionsAndPartitionKeyAndCancellationToken_CreatesIndex()
{
// Arrange
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
var indexName = Fixture.Create<string>();
var options = new IndexCreationOptions { Name = indexName };
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.CreateTextIndexAsync<TestDocumentWithKey<int>, int>(keyedFieldExpression, options, partitionKey, token);
// Assert
IndexHandler.Verify(
x => x.CreateTextIndexAsync<TestDocumentWithKey<int>, int>(
keyedFieldExpression, options, partitionKey, token));
}
#endregion
}
@@ -0,0 +1,145 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using AutoFixture;
using CoreUnitTests.Infrastructure.Model;
using MongoDbGenericRepository.DataAccess.Index;
using Moq;
using Xunit;
namespace CoreUnitTests.BaseMongoRepositoryTests.IndexTests;
public class DropIndexAsyncTests: BaseIndexTests
{
[Fact]
public async Task WitIndexName_DropsIndex()
{
// Arrange
var indexName = Fixture.Create<string>();
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.DropIndexAsync<TestDocument>(indexName);
// Assert
IndexHandler.Verify(
x => x.DropIndexAsync<TestDocument, Guid>(indexName, null, CancellationToken.None));
}
[Fact]
public async Task WitIndexNameAndCancellationToken_DropsIndex()
{
// Arrange
var indexName = Fixture.Create<string>();
var token = new CancellationToken(true);
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.DropIndexAsync<TestDocument>(indexName, token);
// Assert
IndexHandler.Verify(
x => x.DropIndexAsync<TestDocument, Guid>(indexName, null, token));
}
[Fact]
public async Task WitIndexNameAndPartitionKey_DropsIndex()
{
// Arrange
var indexName = Fixture.Create<string>();
var partitionKey = Fixture.Create<string>();
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.DropIndexAsync<TestDocument>(indexName, partitionKey);
// Assert
IndexHandler.Verify(
x => x.DropIndexAsync<TestDocument, Guid>(indexName, partitionKey, CancellationToken.None));
}
[Fact]
public async Task WitIndexNameAndPartitionKeyAndCancellationToken_DropsIndex()
{
// Arrange
var indexName = Fixture.Create<string>();
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.DropIndexAsync<TestDocument>(indexName, partitionKey, token);
// Assert
IndexHandler.Verify(
x => x.DropIndexAsync<TestDocument, Guid>(indexName, partitionKey, token));
}
#region Keyed
[Fact]
public async Task Keyed_WithIndexName_DropsIndex()
{
// Arrange
var indexName = Fixture.Create<string>();
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.DropIndexAsync<TestDocumentWithKey<int>, int>(indexName);
// Assert
IndexHandler.Verify(
x => x.DropIndexAsync<TestDocumentWithKey<int>, int>(indexName, null, CancellationToken.None));
}
[Fact]
public async Task Keyed_WithIndexNameAndCancellationToken_DropsIndex()
{
// Arrange
var indexName = Fixture.Create<string>();
var token = new CancellationToken(true);
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.DropIndexAsync<TestDocumentWithKey<int>, int>(indexName, token);
// Assert
IndexHandler.Verify(
x => x.DropIndexAsync<TestDocumentWithKey<int>, int>(indexName, null, token));
}
[Fact]
public async Task Keyed_WithIndexNameAndPartitionKey_DropsIndex()
{
// Arrange
var indexName = Fixture.Create<string>();
var partitionKey = Fixture.Create<string>();
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.DropIndexAsync<TestDocumentWithKey<int>, int>(indexName, partitionKey);
// Assert
IndexHandler.Verify(
x => x.DropIndexAsync<TestDocumentWithKey<int>, int>(indexName, partitionKey, CancellationToken.None));
}
[Fact]
public async Task Keyed_WithIndexNameAndPartitionKeyAndCancellationToken_DropsIndex()
{
// Arrange
var indexName = Fixture.Create<string>();
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
IndexHandler = new Mock<IMongoDbIndexHandler>();
// Act
await Sut.DropIndexAsync<TestDocumentWithKey<int>, int>(indexName, partitionKey, token);
// Assert
IndexHandler.Verify(
x => x.DropIndexAsync<TestDocumentWithKey<int>, int>(indexName, partitionKey, token));
}
#endregion
}
@@ -0,0 +1,182 @@
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using AutoFixture;
using CoreUnitTests.Infrastructure.Model;
using MongoDbGenericRepository.DataAccess.Index;
using Moq;
using Xunit;
namespace CoreUnitTests.BaseMongoRepositoryTests.IndexTests;
public class GetIndexNamesAsyncTests : BaseIndexTests
{
[Fact]
public async Task WithNoParameters_ReturnsIndexNames()
{
// Arrange
IndexHandler = new Mock<IMongoDbIndexHandler>();
var indexName = Fixture.Create<string>();
IndexHandler
.Setup(x => x.GetIndexesNamesAsync<TestDocument, Guid>(It.IsAny<string>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(new List<string> { indexName });
// Act
var result = await Sut.GetIndexesNamesAsync<TestDocument>();
// Assert
Assert.NotNull(result);
Assert.Contains(result, x => x == indexName);
IndexHandler.Verify(x => x.GetIndexesNamesAsync<TestDocument, Guid>(null, CancellationToken.None), Times.Once());
}
[Fact]
public async Task WithCancellationToken_ReturnsIndexNames()
{
// Arrange
IndexHandler = new Mock<IMongoDbIndexHandler>();
var indexName = Fixture.Create<string>();
var token = new CancellationToken(true);
IndexHandler
.Setup(x => x.GetIndexesNamesAsync<TestDocument, Guid>(It.IsAny<string>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(new List<string> { indexName });
// Act
var result = await Sut.GetIndexesNamesAsync<TestDocument>(token);
// Assert
Assert.NotNull(result);
Assert.Contains(result, x => x == indexName);
IndexHandler.Verify(x => x.GetIndexesNamesAsync<TestDocument, Guid>(null, token), Times.Once());
}
[Fact]
public async Task WithPartitionKey_ReturnsIndexNames()
{
// Arrange
IndexHandler = new Mock<IMongoDbIndexHandler>();
var indexName = Fixture.Create<string>();
var partitionKey = Fixture.Create<string>();
IndexHandler
.Setup(x => x.GetIndexesNamesAsync<TestDocument, Guid>(It.IsAny<string>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(new List<string> { indexName });
// Act
var result = await Sut.GetIndexesNamesAsync<TestDocument>(partitionKey);
// Assert
Assert.NotNull(result);
Assert.Contains(result, x => x == indexName);
IndexHandler.Verify(x => x.GetIndexesNamesAsync<TestDocument, Guid>(partitionKey, CancellationToken.None), Times.Once());
}
[Fact]
public async Task WithPartitionKeyAndCancellationToken_ReturnsIndexNames()
{
// Arrange
IndexHandler = new Mock<IMongoDbIndexHandler>();
var indexName = Fixture.Create<string>();
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
IndexHandler
.Setup(x => x.GetIndexesNamesAsync<TestDocument, Guid>(It.IsAny<string>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(new List<string> { indexName });
// Act
var result = await Sut.GetIndexesNamesAsync<TestDocument>(partitionKey, token);
// Assert
Assert.NotNull(result);
Assert.Contains(result, x => x == indexName);
IndexHandler.Verify(x => x.GetIndexesNamesAsync<TestDocument, Guid>(partitionKey, token), Times.Once());
}
[Fact]
public async Task Keyed_WithNoParameters_ReturnsIndexNames()
{
// Arrange
IndexHandler = new Mock<IMongoDbIndexHandler>();
var indexName = Fixture.Create<string>();
IndexHandler
.Setup(x => x.GetIndexesNamesAsync<TestDocumentWithKey<int>, int>(It.IsAny<string>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(new List<string> { indexName });
// Act
var result = await Sut.GetIndexesNamesAsync<TestDocumentWithKey<int>, int>();
// Assert
Assert.NotNull(result);
Assert.Contains(result, x => x == indexName);
IndexHandler.Verify(x => x.GetIndexesNamesAsync<TestDocumentWithKey<int>, int>(null, CancellationToken.None), Times.Once());
}
[Fact]
public async Task Keyed_WithCancellationToken_ReturnsIndexNames()
{
// Arrange
IndexHandler = new Mock<IMongoDbIndexHandler>();
var indexName = Fixture.Create<string>();
var token = new CancellationToken(true);
IndexHandler
.Setup(x => x.GetIndexesNamesAsync<TestDocumentWithKey<int>, int>(It.IsAny<string>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(new List<string> { indexName });
// Act
var result = await Sut.GetIndexesNamesAsync<TestDocumentWithKey<int>, int>(token);
// Assert
Assert.NotNull(result);
Assert.Contains(result, x => x == indexName);
IndexHandler.Verify(x => x.GetIndexesNamesAsync<TestDocumentWithKey<int>, int>(null, token), Times.Once());
}
[Fact]
public async Task Keyed_WithPartitionKey_ReturnsIndexNames()
{
// Arrange
IndexHandler = new Mock<IMongoDbIndexHandler>();
var indexName = Fixture.Create<string>();
var partitionKey = Fixture.Create<string>();
IndexHandler
.Setup(x => x.GetIndexesNamesAsync<TestDocumentWithKey<int>, int>(It.IsAny<string>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(new List<string> { indexName });
// Act
var result = await Sut.GetIndexesNamesAsync<TestDocumentWithKey<int>, int>(partitionKey);
// Assert
Assert.NotNull(result);
Assert.Contains(result, x => x == indexName);
IndexHandler.Verify(x => x.GetIndexesNamesAsync<TestDocumentWithKey<int>, int>(partitionKey, CancellationToken.None), Times.Once());
}
[Fact]
public async Task Keyed_WithPartitionKeyAndCancellationToken_ReturnsIndexNames()
{
// Arrange
IndexHandler = new Mock<IMongoDbIndexHandler>();
var indexName = Fixture.Create<string>();
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
IndexHandler
.Setup(x => x.GetIndexesNamesAsync<TestDocumentWithKey<int>, int>(It.IsAny<string>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(new List<string> { indexName });
// Act
var result = await Sut.GetIndexesNamesAsync<TestDocumentWithKey<int>, int>(partitionKey, token);
// Assert
Assert.NotNull(result);
Assert.Contains(result, x => x == indexName);
IndexHandler.Verify(x => x.GetIndexesNamesAsync<TestDocumentWithKey<int>, int>(partitionKey, token), Times.Once());
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+37
View File
@@ -0,0 +1,37 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>warnings</Nullable>
<IsPackable>false</IsPackable>
<EnableNETAnalyzers>true</EnableNETAnalyzers>
<AnalysisLevel>latest</AnalysisLevel>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoFixture" Version="4.18.0" />
<PackageReference Include="AutoFixture.AutoMoq" Version="4.18.0" />
<PackageReference Include="FluentAssertions" Version="6.11.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.6.3" />
<PackageReference Include="Moq" Version="4.18.4" />
<PackageReference Include="xunit" Version="2.5.0" />
<PackageReference Include="xunit.runner.console" Version="2.5.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="3.1.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\MongoDbGenericRepository\MongoDbGenericRepository.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,161 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AutoFixture;
using CoreUnitTests.Infrastructure;
using CoreUnitTests.Infrastructure.Model;
using FluentAssertions;
using MongoDB.Driver;
using MongoDbGenericRepository;
using MongoDbGenericRepository.DataAccess.Create;
using Moq;
using Xunit;
namespace CoreUnitTests.DataAccessTests.MongoDbCreatorTests;
public class AddManyAsyncTests : GenericTestContext<MongoDbCreator>
{
[Fact]
public async Task WithDocuments_AddsMany()
{
// Arrange
var documents = Fixture.CreateMany<TestDocument>().ToList();
var context = MockOf<IMongoDbContext>();
var collection = MockOf<IMongoCollection<TestDocument>>();
context
.Setup(x => x.GetCollection<TestDocument>(It.IsAny<string>()))
.Returns(collection.Object);
// Act
await Sut.AddManyAsync<TestDocument, Guid>(documents);
// Assert
collection.Verify(
x => x.InsertManyAsync(
It.Is<List<TestDocument>>(l => l.All(d => documents.Contains(d))),
null,
default),
Times.Once());
}
[Fact]
public async Task WithDocumentsHavingNoId_SetsId()
{
// Arrange
var documents = Fixture
.Build<TestDocumentWithKey<string>>()
.Without(x => x.Id)
.CreateMany()
.ToList();
var context = MockOf<IMongoDbContext>();
var collection = MockOf<IMongoCollection<TestDocumentWithKey<string>>>();
context
.Setup(x => x.GetCollection<TestDocumentWithKey<string>>(It.IsAny<string>()))
.Returns(collection.Object);
// Act
await Sut.AddManyAsync<TestDocumentWithKey<string>, string>(documents);
// Assert
collection.Verify(
x => x.InsertManyAsync(
It.Is<List<TestDocumentWithKey<string>>>(l => l.All(d => documents.Contains(d))),
null,
default),
Times.Once());
documents.Should().AllSatisfy(d => d.Id.Should().NotBeNull());
}
[Fact]
public async Task WithPartitionedDocument_AddsMany()
{
// Arrange
var partitionKey = Fixture.Create<string>();
var documents = Fixture.Build<PartitionedTestDocument>()
.With(x => x.PartitionKey, partitionKey)
.CreateMany()
.ToList();
var context = MockOf<IMongoDbContext>();
var collection = MockOf<IMongoCollection<PartitionedTestDocument>>();
context
.Setup(x => x.GetCollection<PartitionedTestDocument>(It.IsAny<string>()))
.Returns(collection.Object);
// Act
await Sut.AddManyAsync<PartitionedTestDocument, Guid>(documents);
// Assert
collection.Verify(
x => x.InsertManyAsync(
It.Is<List<PartitionedTestDocument>>(l => l.All(d => documents.Contains(d))),
null,
default),
Times.Once());
context.Verify(x => x.GetCollection<PartitionedTestDocument>(partitionKey), Times.Once());
}
[Fact]
public async Task WithDocumentsAndCancellationToken_AddsMany()
{
// Arrange
var documents = Fixture.CreateMany<TestDocument>().ToList();
var context = MockOf<IMongoDbContext>();
var collection = MockOf<IMongoCollection<TestDocument>>();
var token = new CancellationToken(true);
context
.Setup(x => x.GetCollection<TestDocument>(It.IsAny<string>()))
.Returns(collection.Object);
// Act
await Sut.AddManyAsync<TestDocument, Guid>(documents, token);
// Assert
collection.Verify(
x => x.InsertManyAsync(
It.Is<List<TestDocument>>(l => l.All(d => documents.Contains(d))),
null,
token),
Times.Once());
}
[Fact]
public async Task WithPartitionedDocumentAndCancellationToken_AddsOne()
{
// Arrange
var partitionKey = Fixture.Create<string>();
var documents = Fixture.Build<PartitionedTestDocument>()
.With(x => x.PartitionKey, partitionKey)
.CreateMany()
.ToList();
var token = new CancellationToken(true);
var context = MockOf<IMongoDbContext>();
var collection = MockOf<IMongoCollection<PartitionedTestDocument>>();
context
.Setup(x => x.GetCollection<PartitionedTestDocument>(It.IsAny<string>()))
.Returns(collection.Object);
// Act
await Sut.AddManyAsync<PartitionedTestDocument, Guid>(documents, token);
// Assert
collection.Verify(
x => x.InsertManyAsync(
It.Is<List<PartitionedTestDocument>>(l => l.All(d => documents.Contains(d))),
null,
token),
Times.Once());
context.Verify(x => x.GetCollection<PartitionedTestDocument>(partitionKey), Times.Once());
}
}
@@ -0,0 +1,161 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AutoFixture;
using CoreUnitTests.Infrastructure;
using CoreUnitTests.Infrastructure.Model;
using FluentAssertions;
using MongoDB.Driver;
using MongoDbGenericRepository;
using MongoDbGenericRepository.DataAccess.Create;
using Moq;
using Xunit;
namespace CoreUnitTests.DataAccessTests.MongoDbCreatorTests;
public class AddManyTests : GenericTestContext<MongoDbCreator>
{
[Fact]
public void WithDocuments_AddsMany()
{
// Arrange
var documents = Fixture.CreateMany<TestDocument>().ToList();
var context = MockOf<IMongoDbContext>();
var collection = MockOf<IMongoCollection<TestDocument>>();
context
.Setup(x => x.GetCollection<TestDocument>(It.IsAny<string>()))
.Returns(collection.Object);
// Act
Sut.AddMany<TestDocument, Guid>(documents);
// Assert
collection.Verify(
x => x.InsertMany(
It.Is<List<TestDocument>>(l => l.All(d => documents.Contains(d))),
null,
default),
Times.Once());
}
[Fact]
public void WithDocumentsHavingNoId_SetsId()
{
// Arrange
var documents = Fixture
.Build<TestDocumentWithKey<string>>()
.Without(x => x.Id)
.CreateMany()
.ToList();
var context = MockOf<IMongoDbContext>();
var collection = MockOf<IMongoCollection<TestDocumentWithKey<string>>>();
context
.Setup(x => x.GetCollection<TestDocumentWithKey<string>>(It.IsAny<string>()))
.Returns(collection.Object);
// Act
Sut.AddMany<TestDocumentWithKey<string>, string>(documents);
// Assert
collection.Verify(
x => x.InsertMany(
It.Is<List<TestDocumentWithKey<string>>>(l => l.All(d => documents.Contains(d))),
null,
default),
Times.Once());
documents.Should().AllSatisfy(d => d.Id.Should().NotBeNull());
}
[Fact]
public void WithPartitionedDocument_AddsMany()
{
// Arrange
var partitionKey = Fixture.Create<string>();
var documents = Fixture.Build<PartitionedTestDocument>()
.With(x => x.PartitionKey, partitionKey)
.CreateMany()
.ToList();
var context = MockOf<IMongoDbContext>();
var collection = MockOf<IMongoCollection<PartitionedTestDocument>>();
context
.Setup(x => x.GetCollection<PartitionedTestDocument>(It.IsAny<string>()))
.Returns(collection.Object);
// Act
Sut.AddMany<PartitionedTestDocument, Guid>(documents);
// Assert
collection.Verify(
x => x.InsertMany(
It.Is<List<PartitionedTestDocument>>(l => l.All(d => documents.Contains(d))),
null,
default),
Times.Once());
context.Verify(x => x.GetCollection<PartitionedTestDocument>(partitionKey), Times.Once());
}
[Fact]
public void WithDocumentsAndCancellationToken_AddsMany()
{
// Arrange
var documents = Fixture.CreateMany<TestDocument>().ToList();
var context = MockOf<IMongoDbContext>();
var collection = MockOf<IMongoCollection<TestDocument>>();
var token = new CancellationToken(true);
context
.Setup(x => x.GetCollection<TestDocument>(It.IsAny<string>()))
.Returns(collection.Object);
// Act
Sut.AddMany<TestDocument, Guid>(documents, token);
// Assert
collection.Verify(
x => x.InsertMany(
It.Is<List<TestDocument>>(l => l.All(d => documents.Contains(d))),
null,
token),
Times.Once());
}
[Fact]
public void WithPartitionedDocumentAndCancellationToken_AddsOne()
{
// Arrange
var partitionKey = Fixture.Create<string>();
var documents = Fixture.Build<PartitionedTestDocument>()
.With(x => x.PartitionKey, partitionKey)
.CreateMany()
.ToList();
var token = new CancellationToken(true);
var context = MockOf<IMongoDbContext>();
var collection = MockOf<IMongoCollection<PartitionedTestDocument>>();
context
.Setup(x => x.GetCollection<PartitionedTestDocument>(It.IsAny<string>()))
.Returns(collection.Object);
// Act
Sut.AddMany<PartitionedTestDocument, Guid>(documents, token);
// Assert
collection.Verify(
x => x.InsertMany(
It.Is<List<PartitionedTestDocument>>(l => l.All(d => documents.Contains(d))),
null,
token),
Times.Once());
context.Verify(x => x.GetCollection<PartitionedTestDocument>(partitionKey), Times.Once());
}
}
@@ -0,0 +1,153 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using AutoFixture;
using CoreUnitTests.Infrastructure;
using CoreUnitTests.Infrastructure.Model;
using FluentAssertions;
using MongoDB.Driver;
using MongoDbGenericRepository;
using MongoDbGenericRepository.DataAccess.Create;
using Moq;
using Xunit;
namespace CoreUnitTests.DataAccessTests.MongoDbCreatorTests;
public class AddOneAsyncTests : GenericTestContext<MongoDbCreator>
{
[Fact]
public async Task WithDocument_AddsOne()
{
// Arrange
var document = new TestDocument();
var context = MockOf<IMongoDbContext>();
var collection = MockOf<IMongoCollection<TestDocument>>();
context
.Setup(x => x.GetCollection<TestDocument>(It.IsAny<string>()))
.Returns(collection.Object);
// Act
await Sut.AddOneAsync<TestDocument, Guid>(document);
// Assert
collection.Verify(
x => x.InsertOneAsync(
It.Is<TestDocument>(d => d == document),
null,
default),
Times.Once());
}
[Fact]
public async Task WithDocumentHavingNoId_SetsId()
{
// Arrange
var document = new TestDocumentWithKey<string>();
var context = MockOf<IMongoDbContext>();
var collection = MockOf<IMongoCollection<TestDocumentWithKey<string>>>();
context
.Setup(x => x.GetCollection<TestDocumentWithKey<string>>(It.IsAny<string>()))
.Returns(collection.Object);
// Act
await Sut.AddOneAsync<TestDocumentWithKey<string>, string>(document);
// Assert
collection.Verify(
x => x.InsertOneAsync(
It.Is<TestDocumentWithKey<string>>(d => d == document),
null,
default),
Times.Once());
document.Id.Should().NotBeNull();
}
[Fact]
public async Task WithPartitionedDocument_AddsOne()
{
// Arrange
var partitionKey = Fixture.Create<string>();
var document = Fixture.Build<PartitionedTestDocument>()
.With(x => x.PartitionKey, partitionKey)
.Create();
var context = MockOf<IMongoDbContext>();
var collection = MockOf<IMongoCollection<PartitionedTestDocument>>();
context
.Setup(x => x.GetCollection<PartitionedTestDocument>(It.IsAny<string>()))
.Returns(collection.Object);
// Act
await Sut.AddOneAsync<PartitionedTestDocument, Guid>(document);
// Assert
collection.Verify(
x => x.InsertOneAsync(
It.Is<PartitionedTestDocument>(d => d == document),
null,
default),
Times.Once());
context.Verify(x => x.GetCollection<PartitionedTestDocument>(partitionKey), Times.Once());
}
[Fact]
public async Task WithDocumentAndCancellationToken_AddsOne()
{
// Arrange
var document = new TestDocument();
var context = MockOf<IMongoDbContext>();
var collection = MockOf<IMongoCollection<TestDocument>>();
var token = new CancellationToken(true);
context
.Setup(x => x.GetCollection<TestDocument>(It.IsAny<string>()))
.Returns(collection.Object);
// Act
await Sut.AddOneAsync<TestDocument, Guid>(document, token);
// Assert
collection.Verify(
x => x.InsertOneAsync(
It.Is<TestDocument>(d => d == document),
null,
token),
Times.Once());
}
[Fact]
public async Task WithPartitionedDocumentAndCancellationToken_AddsOne()
{
// Arrange
var partitionKey = Fixture.Create<string>();
var document = Fixture.Build<PartitionedTestDocument>()
.With(x => x.PartitionKey, partitionKey)
.Create();
var token = new CancellationToken(true);
var context = MockOf<IMongoDbContext>();
var collection = MockOf<IMongoCollection<PartitionedTestDocument>>();
context
.Setup(x => x.GetCollection<PartitionedTestDocument>(It.IsAny<string>()))
.Returns(collection.Object);
// Act
await Sut.AddOneAsync<PartitionedTestDocument, Guid>(document, token);
// Assert
collection.Verify(
x => x.InsertOneAsync(
It.Is<PartitionedTestDocument>(d => d == document),
null,
token),
Times.Once());
context.Verify(x => x.GetCollection<PartitionedTestDocument>(partitionKey), Times.Once());
}
}
@@ -0,0 +1,152 @@
using System;
using System.Threading;
using AutoFixture;
using CoreUnitTests.Infrastructure;
using CoreUnitTests.Infrastructure.Model;
using FluentAssertions;
using MongoDB.Driver;
using MongoDbGenericRepository;
using MongoDbGenericRepository.DataAccess.Create;
using Moq;
using Xunit;
namespace CoreUnitTests.DataAccessTests.MongoDbCreatorTests;
public class AddOneTests : GenericTestContext<MongoDbCreator>
{
[Fact]
public void WithDocument_AddsOne()
{
// Arrange
var document = new TestDocument();
var context = MockOf<IMongoDbContext>();
var collection = MockOf<IMongoCollection<TestDocument>>();
context
.Setup(x => x.GetCollection<TestDocument>(It.IsAny<string>()))
.Returns(collection.Object);
// Act
Sut.AddOne<TestDocument, Guid>(document);
// Assert
collection.Verify(
x => x.InsertOne(
It.Is<TestDocument>(d => d == document),
null,
default),
Times.Once());
}
[Fact]
public void WithDocumentHavingNoId_SetsId()
{
// Arrange
var document = new TestDocumentWithKey<string>();
var context = MockOf<IMongoDbContext>();
var collection = MockOf<IMongoCollection<TestDocumentWithKey<string>>>();
context
.Setup(x => x.GetCollection<TestDocumentWithKey<string>>(It.IsAny<string>()))
.Returns(collection.Object);
// Act
Sut.AddOne<TestDocumentWithKey<string>, string>(document);
// Assert
collection.Verify(
x => x.InsertOne(
It.Is<TestDocumentWithKey<string>>(d => d == document),
null,
default),
Times.Once());
document.Id.Should().NotBeNull();
}
[Fact]
public void WithPartitionedDocument_AddsOne()
{
// Arrange
var partitionKey = Fixture.Create<string>();
var document = Fixture.Build<PartitionedTestDocument>()
.With(x => x.PartitionKey, partitionKey)
.Create();
var context = MockOf<IMongoDbContext>();
var collection = MockOf<IMongoCollection<PartitionedTestDocument>>();
context
.Setup(x => x.GetCollection<PartitionedTestDocument>(It.IsAny<string>()))
.Returns(collection.Object);
// Act
Sut.AddOne<PartitionedTestDocument, Guid>(document);
// Assert
collection.Verify(
x => x.InsertOne(
It.Is<PartitionedTestDocument>(d => d == document),
null,
default),
Times.Once());
context.Verify(x => x.GetCollection<PartitionedTestDocument>(partitionKey), Times.Once());
}
[Fact]
public void WithDocumentAndCancellationToken_AddsOne()
{
// Arrange
var document = new TestDocument();
var context = MockOf<IMongoDbContext>();
var collection = MockOf<IMongoCollection<TestDocument>>();
var token = new CancellationToken(true);
context
.Setup(x => x.GetCollection<TestDocument>(It.IsAny<string>()))
.Returns(collection.Object);
// Act
Sut.AddOne<TestDocument, Guid>(document, token);
// Assert
collection.Verify(
x => x.InsertOne(
It.Is<TestDocument>(d => d == document),
null,
token),
Times.Once());
}
[Fact]
public void WithPartitionedDocumentAndCancellationToken_AddsOne()
{
// Arrange
var partitionKey = Fixture.Create<string>();
var document = Fixture.Build<PartitionedTestDocument>()
.With(x => x.PartitionKey, partitionKey)
.Create();
var token = new CancellationToken(true);
var context = MockOf<IMongoDbContext>();
var collection = MockOf<IMongoCollection<PartitionedTestDocument>>();
context
.Setup(x => x.GetCollection<PartitionedTestDocument>(It.IsAny<string>()))
.Returns(collection.Object);
// Act
Sut.AddOne<PartitionedTestDocument, Guid>(document, token);
// Assert
collection.Verify(
x => x.InsertOne(
It.Is<PartitionedTestDocument>(d => d == document),
null,
token),
Times.Once());
context.Verify(x => x.GetCollection<PartitionedTestDocument>(partitionKey), Times.Once());
}
}
@@ -0,0 +1,157 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using AutoFixture;
using CoreUnitTests.Infrastructure;
using CoreUnitTests.Infrastructure.Model;
using FluentAssertions;
using MongoDB.Driver;
using MongoDbGenericRepository;
using MongoDbGenericRepository.DataAccess.Delete;
using Moq;
using Xunit;
namespace CoreUnitTests.DataAccessTests.MongoDbEraserTests;
public class DeleteManyAsyncTests : GenericTestContext<MongoDbEraser>
{
[Fact]
public async Task WithEmptyDocuments_DeletesNothing()
{
// Arrange
var documents = new List<TestDocument>(0);
var token = new CancellationToken(true);
var collection = MockOf<IMongoCollection<TestDocument>>();
var dbContext = MockOf<IMongoDbContext>();
dbContext
.Setup(x => x.GetCollection<TestDocument>(null))
.Returns(collection.Object);
// Act
var result = await Sut.DeleteManyAsync<TestDocument, Guid>(documents, token);
// Assert
result.Should().Be(0);
var idsToDelete = documents.Select(e => e.Id).ToArray();
Expression<Func<TestDocument, bool>> expectedFilter = x => idsToDelete.Contains(x.Id);
collection.Verify(
x => x.DeleteManyAsync(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
token),
Times.Never);
}
[Fact]
public async Task WithDocumentsAndCancellationToken_DeletesMany()
{
// Arrange
var count = Fixture.Create<long>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var token = new CancellationToken(true);
var collection = MockOf<IMongoCollection<TestDocument>>();
collection
.Setup(x => x.DeleteManyAsync(It.IsAny<FilterDefinition<TestDocument>>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(new DeleteResult.Acknowledged(count));
var dbContext = MockOf<IMongoDbContext>();
dbContext
.Setup(x => x.GetCollection<TestDocument>(null))
.Returns(collection.Object);
// Act
var result = await Sut.DeleteManyAsync<TestDocument, Guid>(documents, token);
// Assert
result.Should().Be(count);
var idsToDelete = documents.Select(e => e.Id).ToArray();
Expression<Func<TestDocument, bool>> expectedFilter = x => idsToDelete.Contains(x.Id);
collection.Verify(
x => x.DeleteManyAsync(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
token),
Times.Once);
}
[Fact]
public async Task WithPartitionDocumentsAndCancellationToken_DeletesMany()
{
// Arrange
var count = Fixture.Create<long>();
var partitionKey = Fixture.Create<string>();
var documents = Fixture
.Build<PartitionedTestDocument>()
.With(x => x.PartitionKey, partitionKey)
.CreateMany()
.ToList();
var token = new CancellationToken(true);
var collection = MockOf<IMongoCollection<PartitionedTestDocument>>();
collection
.Setup(x => x.DeleteManyAsync(It.IsAny<FilterDefinition<PartitionedTestDocument>>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(new DeleteResult.Acknowledged(count));
var dbContext = MockOf<IMongoDbContext>();
dbContext
.Setup(x => x.GetCollection<PartitionedTestDocument>(It.IsAny<string>()))
.Returns(collection.Object);
// Act
var result = await Sut.DeleteManyAsync<PartitionedTestDocument, Guid>(documents, token);
// Assert
result.Should().Be(count);
var idsToDelete = documents.Select(e => e.Id).ToArray();
Expression<Func<PartitionedTestDocument, bool>> expectedFilter = x => idsToDelete.Contains(x.Id);
collection.Verify(
x => x.DeleteManyAsync(
It.Is<FilterDefinition<PartitionedTestDocument>>(f => f.EquivalentTo(expectedFilter)),
token),
Times.Once);
dbContext.Verify(x => x.GetCollection<PartitionedTestDocument>(partitionKey), Times.Once);
}
[Fact]
public async Task WithFilterAndPartitionKeyAndCancellationToken_DeletesOne()
{
// Arrange
var count = Fixture.Create<long>();
var id = Fixture.Create<Guid>();
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
var collection = MockOf<IMongoCollection<TestDocument>>();
collection
.Setup(x => x.DeleteManyAsync(It.IsAny<FilterDefinition<TestDocument>>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(new DeleteResult.Acknowledged(count));
var dbContext = MockOf<IMongoDbContext>();
dbContext
.Setup(x => x.GetCollection<TestDocument>(It.IsAny<string>()))
.Returns(collection.Object);
Expression<Func<TestDocument, bool>> filter = d => d.Id == id;
// Act
var result = await Sut.DeleteManyAsync<TestDocument, Guid>(filter, partitionKey, token);
// Assert
result.Should().Be(count);
collection.Verify(
x => x.DeleteManyAsync(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(filter)),
token),
Times.Once);
dbContext.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
}
}
@@ -0,0 +1,157 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using AutoFixture;
using CoreUnitTests.Infrastructure;
using CoreUnitTests.Infrastructure.Model;
using FluentAssertions;
using MongoDB.Driver;
using MongoDbGenericRepository;
using MongoDbGenericRepository.DataAccess.Delete;
using Moq;
using Xunit;
namespace CoreUnitTests.DataAccessTests.MongoDbEraserTests;
public class DeleteManyTests : GenericTestContext<MongoDbEraser>
{
[Fact]
public void WithEmptyDocuments_DeletesNothing()
{
// Arrange
var documents = new List<TestDocument>(0);
var token = new CancellationToken(true);
var collection = MockOf<IMongoCollection<TestDocument>>();
var dbContext = MockOf<IMongoDbContext>();
dbContext
.Setup(x => x.GetCollection<TestDocument>(null))
.Returns(collection.Object);
// Act
var result = Sut.DeleteMany<TestDocument, Guid>(documents, token);
// Assert
result.Should().Be(0);
var idsToDelete = documents.Select(e => e.Id).ToArray();
Expression<Func<TestDocument, bool>> expectedFilter = x => idsToDelete.Contains(x.Id);
collection.Verify(
x => x.DeleteMany(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
token),
Times.Never);
}
[Fact]
public void WithDocumentsAndCancellationToken_DeletesMany()
{
// Arrange
var count = Fixture.Create<long>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var token = new CancellationToken(true);
var collection = MockOf<IMongoCollection<TestDocument>>();
collection
.Setup(x => x.DeleteMany(It.IsAny<FilterDefinition<TestDocument>>(), It.IsAny<CancellationToken>()))
.Returns(new DeleteResult.Acknowledged(count));
var dbContext = MockOf<IMongoDbContext>();
dbContext
.Setup(x => x.GetCollection<TestDocument>(null))
.Returns(collection.Object);
// Act
var result = Sut.DeleteMany<TestDocument, Guid>(documents, token);
// Assert
result.Should().Be(count);
var idsToDelete = documents.Select(e => e.Id).ToArray();
Expression<Func<TestDocument, bool>> expectedFilter = x => idsToDelete.Contains(x.Id);
collection.Verify(
x => x.DeleteMany(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
token),
Times.Once);
}
[Fact]
public void WithPartitionDocumentsAndCancellationToken_DeletesMany()
{
// Arrange
var count = Fixture.Create<long>();
var partitionKey = Fixture.Create<string>();
var documents = Fixture
.Build<PartitionedTestDocument>()
.With(x => x.PartitionKey, partitionKey)
.CreateMany()
.ToList();
var token = new CancellationToken(true);
var collection = MockOf<IMongoCollection<PartitionedTestDocument>>();
collection
.Setup(x => x.DeleteMany(It.IsAny<FilterDefinition<PartitionedTestDocument>>(), It.IsAny<CancellationToken>()))
.Returns(new DeleteResult.Acknowledged(count));
var dbContext = MockOf<IMongoDbContext>();
dbContext
.Setup(x => x.GetCollection<PartitionedTestDocument>(It.IsAny<string>()))
.Returns(collection.Object);
// Act
var result = Sut.DeleteMany<PartitionedTestDocument, Guid>(documents, token);
// Assert
result.Should().Be(count);
var idsToDelete = documents.Select(e => e.Id).ToArray();
Expression<Func<PartitionedTestDocument, bool>> expectedFilter = x => idsToDelete.Contains(x.Id);
collection.Verify(
x => x.DeleteMany(
It.Is<FilterDefinition<PartitionedTestDocument>>(f => f.EquivalentTo(expectedFilter)),
token),
Times.Once);
dbContext.Verify(x => x.GetCollection<PartitionedTestDocument>(partitionKey), Times.Once);
}
[Fact]
public void WithFilterAndPartitionKeyAndCancellationToken_DeletesOne()
{
// Arrange
var count = Fixture.Create<long>();
var id = Fixture.Create<Guid>();
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
var collection = MockOf<IMongoCollection<TestDocument>>();
collection
.Setup(x => x.DeleteMany(It.IsAny<FilterDefinition<TestDocument>>(), It.IsAny<CancellationToken>()))
.Returns(new DeleteResult.Acknowledged(count));
var dbContext = MockOf<IMongoDbContext>();
dbContext
.Setup(x => x.GetCollection<TestDocument>(It.IsAny<string>()))
.Returns(collection.Object);
Expression<Func<TestDocument, bool>> filter = d => d.Id == id;
// Act
var result = Sut.DeleteMany<TestDocument, Guid>(filter, partitionKey, token);
// Assert
result.Should().Be(count);
collection.Verify(
x => x.DeleteMany(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(filter)),
token),
Times.Once);
dbContext.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
}
}
@@ -0,0 +1,85 @@
using System;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using AutoFixture;
using CoreUnitTests.Infrastructure;
using CoreUnitTests.Infrastructure.Model;
using FluentAssertions;
using MongoDB.Driver;
using MongoDbGenericRepository;
using MongoDbGenericRepository.DataAccess.Delete;
using Moq;
using Xunit;
namespace CoreUnitTests.DataAccessTests.MongoDbEraserTests;
public class DeleteOneAsyncTests : GenericTestContext<MongoDbEraser>
{
[Fact]
public async Task WithDocumentAndCancellationToken_DeletesOne()
{
// Arrange
var count = Fixture.Create<long>();
var document = Fixture.Create<TestDocument>();
var token = new CancellationToken(true);
var collection = MockOf<IMongoCollection<TestDocument>>();
collection
.Setup(x => x.DeleteOneAsync(It.IsAny<FilterDefinition<TestDocument>>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(new DeleteResult.Acknowledged(count));
var dbContext = MockOf<IMongoDbContext>();
dbContext
.Setup(x => x.GetCollection<TestDocument>(null))
.Returns(collection.Object);
// Act
var result = await Sut.DeleteOneAsync<TestDocument, Guid>(document, token);
// Assert
result.Should().Be(count);
var expectedFilter = Builders<TestDocument>.Filter.Eq("Id", document.Id);
collection.Verify(
x => x.DeleteOneAsync(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
token),
Times.Once());
}
[Fact]
public async Task WithFilterAndPartitionKeyAndCancellationToken_DeletesOne()
{
// Arrange
var count = Fixture.Create<long>();
var document = Fixture.Create<TestDocument>();
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
var collection = MockOf<IMongoCollection<TestDocument>>();
collection
.Setup(x => x.DeleteOneAsync(It.IsAny<FilterDefinition<TestDocument>>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(new DeleteResult.Acknowledged(count));
var dbContext = MockOf<IMongoDbContext>();
dbContext
.Setup(x => x.GetCollection<TestDocument>(It.IsAny<string>()))
.Returns(collection.Object);
Expression<Func<TestDocument, bool>> filter = d => d.Id == document.Id;
// Act
var result = await Sut.DeleteOneAsync<TestDocument, Guid>(filter, partitionKey, token);
// Assert
result.Should().Be(count);
collection.Verify(
x => x.DeleteOneAsync(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(filter)),
token),
Times.Once());
dbContext.Verify(x => x.GetCollection<TestDocument>(partitionKey));
}
}
@@ -0,0 +1,84 @@
using System;
using System.Linq.Expressions;
using System.Threading;
using AutoFixture;
using CoreUnitTests.Infrastructure;
using CoreUnitTests.Infrastructure.Model;
using FluentAssertions;
using MongoDB.Driver;
using MongoDbGenericRepository;
using MongoDbGenericRepository.DataAccess.Delete;
using Moq;
using Xunit;
namespace CoreUnitTests.DataAccessTests.MongoDbEraserTests;
public class DeleteOneTests : GenericTestContext<MongoDbEraser>
{
[Fact]
public void WithDocumentAndCancellationToken_DeletesOne()
{
// Arrange
var count = Fixture.Create<long>();
var document = Fixture.Create<TestDocument>();
var token = new CancellationToken(true);
var collection = MockOf<IMongoCollection<TestDocument>>();
collection
.Setup(x => x.DeleteOne(It.IsAny<FilterDefinition<TestDocument>>(), It.IsAny<CancellationToken>()))
.Returns(new DeleteResult.Acknowledged(count));
var dbContext = MockOf<IMongoDbContext>();
dbContext
.Setup(x => x.GetCollection<TestDocument>(null))
.Returns(collection.Object);
// Act
var result = Sut.DeleteOne<TestDocument, Guid>(document, token);
// Assert
result.Should().Be(count);
var expectedFilter = Builders<TestDocument>.Filter.Eq("Id", document.Id);
collection.Verify(
x => x.DeleteOne(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
token),
Times.Once());
}
[Fact]
public void WithFilterAndPartitionKeyAndCancellationToken_DeletesOne()
{
// Arrange
var count = Fixture.Create<long>();
var document = Fixture.Create<TestDocument>();
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
var collection = MockOf<IMongoCollection<TestDocument>>();
collection
.Setup(x => x.DeleteOne(It.IsAny<FilterDefinition<TestDocument>>(), It.IsAny<CancellationToken>()))
.Returns(new DeleteResult.Acknowledged(count));
var dbContext = MockOf<IMongoDbContext>();
dbContext
.Setup(x => x.GetCollection<TestDocument>(It.IsAny<string>()))
.Returns(collection.Object);
Expression<Func<TestDocument, bool>> filter = d => d.Id == document.Id;
// Act
var result = Sut.DeleteOne<TestDocument, Guid>(filter, partitionKey, token);
// Assert
result.Should().Be(count);
collection.Verify(
x => x.DeleteOne(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(filter)),
token),
Times.Once());
dbContext.Verify(x => x.GetCollection<TestDocument>(partitionKey));
}
}
@@ -0,0 +1,43 @@
using System.Collections.Generic;
using System.Threading;
using CoreUnitTests.Infrastructure;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDbGenericRepository.DataAccess.Index;
using Moq;
namespace CoreUnitTests.DataAccessTests.MongoDbIndexHandlerTests;
public class BaseIndexTests : GenericTestContext<MongoDbIndexHandler>
{
protected (Mock<IAsyncCursor<BsonDocument>>, Mock<IMongoIndexManager<TDocument>>) SetupIndexes<TDocument>(
List<BsonDocument> indexes,
Mock<IMongoCollection<TDocument>> collection)
{
var asyncCursor = MockOf<IAsyncCursor<BsonDocument>>();
var moveNextSequence = asyncCursor
.SetupSequence(x => x.MoveNextAsync(It.IsAny<CancellationToken>()));
var currentSequence = asyncCursor
.SetupSequence(x => x.Current);
foreach (var bsonDocument in indexes)
{
moveNextSequence.ReturnsAsync(true);
currentSequence.Returns(new[] {bsonDocument});
}
moveNextSequence.ReturnsAsync(false);
var indexManager = MockOf<IMongoIndexManager<TDocument>>();
indexManager
.Setup(x => x.ListAsync(It.IsAny<CancellationToken>()))
.ReturnsAsync(asyncCursor.Object);
collection
.SetupGet(x => x.Indexes)
.Returns(indexManager.Object);
return (asyncCursor, indexManager);
}
}
@@ -0,0 +1,180 @@
using System;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using AutoFixture;
using CoreUnitTests.Infrastructure;
using CoreUnitTests.Infrastructure.Model;
using FluentAssertions;
using MongoDB.Driver;
using MongoDbGenericRepository;
using MongoDbGenericRepository.Models;
using Moq;
using Xunit;
namespace CoreUnitTests.DataAccessTests.MongoDbIndexHandlerTests;
public class CreateAscendingIndexAsyncTests : BaseIndexTests
{
private readonly Expression<Func<TestDocument, object>> fieldExpression = t => t.SomeContent2;
[Fact]
public async Task WithFieldExpression_CreatesIndex()
{
// Arrange
var expectedIndexName = Fixture.Create<string>();
var collection = MockOf<IMongoCollection<TestDocument>>();
SetupContext(collection);
var indexManger = SetupIndexManager(collection, expectedIndexName);
// Act
var result = await Sut.CreateAscendingIndexAsync<TestDocument, Guid>(fieldExpression);
// Assert
result.Should().Be(expectedIndexName);
indexManger.Verify(
x => x.CreateOneAsync(
It.Is<CreateIndexModel<TestDocument>>(t => t.Keys.EqualToJson("{\"SomeContent2\":1}")),
null,
CancellationToken.None),
Times.Once);
}
[Fact]
public async Task WithFieldExpressionAndOptions_CreatesIndex()
{
// Arrange
var expectedIndexName = Fixture.Create<string>();
var collection = MockOf<IMongoCollection<TestDocument>>();
var options = Fixture.Create<IndexCreationOptions>();
SetupContext(collection);
var indexManger = SetupIndexManager(collection, expectedIndexName);
// Act
var result = await Sut.CreateAscendingIndexAsync<TestDocument, Guid>(fieldExpression, options);
// Assert
result.Should().Be(expectedIndexName);
indexManger.Verify(
x => x.CreateOneAsync(
It.Is<CreateIndexModel<TestDocument>>(
t => t.Keys.EqualToJson("{\"SomeContent2\":1}") &&
t.Options.EqualTo(options)),
null,
CancellationToken.None),
Times.Once);
}
[Fact]
public async Task WithFieldExpressionAndPartitionKey_CreatesIndex()
{
// Arrange
var expectedIndexName = Fixture.Create<string>();
var collection = MockOf<IMongoCollection<TestDocument>>();
var partitionKey = Fixture.Create<string>();
var context = SetupContext(collection);
var indexManger = SetupIndexManager(collection, expectedIndexName);
// Act
var result = await Sut.CreateAscendingIndexAsync<TestDocument, Guid>(fieldExpression, partitionKey: partitionKey);
// Assert
result.Should().Be(expectedIndexName);
indexManger.Verify(
x => x.CreateOneAsync(
It.Is<CreateIndexModel<TestDocument>>(
t => t.Keys.EqualToJson("{\"SomeContent2\":1}") ),
null,
CancellationToken.None),
Times.Once);
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
}
[Fact]
public async Task WithFieldExpressionAndCancellationToken_CreatesIndex()
{
// Arrange
var expectedIndexName = Fixture.Create<string>();
var collection = MockOf<IMongoCollection<TestDocument>>();
var token = new CancellationToken(true);
SetupContext(collection);
var indexManger = SetupIndexManager(collection, expectedIndexName);
// Act
var result = await Sut.CreateAscendingIndexAsync<TestDocument, Guid>(fieldExpression, cancellationToken: token);
// Assert
result.Should().Be(expectedIndexName);
indexManger.Verify(
x => x.CreateOneAsync(
It.Is<CreateIndexModel<TestDocument>>(
t => t.Keys.EqualToJson("{\"SomeContent2\":1}") ),
null,
token),
Times.Once);
}
[Fact]
public async Task WithFieldExpressionAndOptionsAndPartitionKeyAndCancellationToken_CreatesIndex()
{
// Arrange
var expectedIndexName = Fixture.Create<string>();
var collection = MockOf<IMongoCollection<TestDocument>>();
var token = new CancellationToken(true);
var partitionKey = Fixture.Create<string>();
var options = Fixture.Create<IndexCreationOptions>();
var context = SetupContext(collection);
var indexManger = SetupIndexManager(collection, expectedIndexName);
// Act
var result = await Sut.CreateAscendingIndexAsync<TestDocument, Guid>(fieldExpression, options, partitionKey, token);
// Assert
result.Should().Be(expectedIndexName);
indexManger.Verify(
x => x.CreateOneAsync(
It.Is<CreateIndexModel<TestDocument>>(
t => t.Keys.EqualToJson("{\"SomeContent2\":1}") &&
t.Options.EqualTo(options)),
null,
token),
Times.Once);
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
}
private Mock<IMongoDbContext> SetupContext<TDocument>(IMock<IMongoCollection<TDocument>> collection)
{
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TDocument>(It.IsAny<string>()))
.Returns(collection.Object);
return context;
}
private Mock<IMongoIndexManager<TDocument>> SetupIndexManager<TDocument>(Mock<IMongoCollection<TDocument>> collection, string indexName)
{
var indexManager = MockOf<IMongoIndexManager<TDocument>>();
indexManager
.Setup(
x => x.CreateOneAsync(
It.IsAny<CreateIndexModel<TDocument>>(),
It.IsAny<CreateOneIndexOptions>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(indexName);
collection
.SetupGet(x => x.Indexes)
.Returns(indexManager.Object);
return indexManager;
}
}
@@ -0,0 +1,190 @@
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using AutoFixture;
using CoreUnitTests.Infrastructure;
using CoreUnitTests.Infrastructure.Model;
using FluentAssertions;
using MongoDB.Driver;
using MongoDbGenericRepository;
using MongoDbGenericRepository.Models;
using Moq;
using Xunit;
using Xunit.Abstractions;
namespace CoreUnitTests.DataAccessTests.MongoDbIndexHandlerTests;
public class CreateCombinedTextIndexAsyncTests : BaseIndexTests
{
private readonly ITestOutputHelper testOutputHelper;
private readonly List<Expression<Func<TestDocument, object>>> fieldExpressions = new()
{
t => t.SomeContent2,
t => t.GroupingKey
};
public CreateCombinedTextIndexAsyncTests(ITestOutputHelper testOutputHelper)
=> this.testOutputHelper = testOutputHelper;
[Fact]
public async Task WithFieldExpression_CreatesIndex()
{
// Arrange
var expectedIndexName = Fixture.Create<string>();
var collection = MockOf<IMongoCollection<TestDocument>>();
SetupContext(collection);
var indexManger = SetupIndexManager(collection, expectedIndexName);
// Act
var result = await Sut.CreateCombinedTextIndexAsync<TestDocument, Guid>(fieldExpressions);
// Assert
result.Should().Be(expectedIndexName);
indexManger.Verify(
x => x.CreateOneAsync(
It.Is<CreateIndexModel<TestDocument>>(t => t.Keys.EqualToJson("{\"SomeContent2\":\"text\",\"GroupingKey\":\"text\"}", testOutputHelper)),
null,
CancellationToken.None),
Times.Once);
}
[Fact]
public async Task WithFieldExpressionAndOptions_CreatesIndex()
{
// Arrange
var expectedIndexName = Fixture.Create<string>();
var collection = MockOf<IMongoCollection<TestDocument>>();
var options = Fixture.Create<IndexCreationOptions>();
SetupContext(collection);
var indexManger = SetupIndexManager(collection, expectedIndexName);
// Act
var result = await Sut.CreateCombinedTextIndexAsync<TestDocument, Guid>(fieldExpressions, options);
// Assert
result.Should().Be(expectedIndexName);
indexManger.Verify(
x => x.CreateOneAsync(
It.Is<CreateIndexModel<TestDocument>>(
t => t.Keys.EqualToJson("{\"SomeContent2\":\"text\",\"GroupingKey\":\"text\"}") &&
t.Options.EqualTo(options)),
null,
CancellationToken.None),
Times.Once);
}
[Fact]
public async Task WithFieldExpressionAndPartitionKey_CreatesIndex()
{
// Arrange
var expectedIndexName = Fixture.Create<string>();
var collection = MockOf<IMongoCollection<TestDocument>>();
var partitionKey = Fixture.Create<string>();
var context = SetupContext(collection);
var indexManger = SetupIndexManager(collection, expectedIndexName);
// Act
var result = await Sut.CreateCombinedTextIndexAsync<TestDocument, Guid>(fieldExpressions, partitionKey: partitionKey);
// Assert
result.Should().Be(expectedIndexName);
indexManger.Verify(
x => x.CreateOneAsync(
It.Is<CreateIndexModel<TestDocument>>(
t => t.Keys.EqualToJson("{\"SomeContent2\":\"text\",\"GroupingKey\":\"text\"}") ),
null,
CancellationToken.None),
Times.Once);
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
}
[Fact]
public async Task WithFieldExpressionAndCancellationToken_CreatesIndex()
{
// Arrange
var expectedIndexName = Fixture.Create<string>();
var collection = MockOf<IMongoCollection<TestDocument>>();
var token = new CancellationToken(true);
SetupContext(collection);
var indexManger = SetupIndexManager(collection, expectedIndexName);
// Act
var result = await Sut.CreateCombinedTextIndexAsync<TestDocument, Guid>(fieldExpressions, cancellationToken: token);
// Assert
result.Should().Be(expectedIndexName);
indexManger.Verify(
x => x.CreateOneAsync(
It.Is<CreateIndexModel<TestDocument>>(
t => t.Keys.EqualToJson("{\"SomeContent2\":\"text\",\"GroupingKey\":\"text\"}") ),
null,
token),
Times.Once);
}
[Fact]
public async Task WithFieldExpressionAndOptionsAndPartitionKeyAndCancellationToken_CreatesIndex()
{
// Arrange
var expectedIndexName = Fixture.Create<string>();
var collection = MockOf<IMongoCollection<TestDocument>>();
var token = new CancellationToken(true);
var partitionKey = Fixture.Create<string>();
var options = Fixture.Create<IndexCreationOptions>();
var context = SetupContext(collection);
var indexManger = SetupIndexManager(collection, expectedIndexName);
// Act
var result = await Sut.CreateCombinedTextIndexAsync<TestDocument, Guid>(fieldExpressions, options, partitionKey, token);
// Assert
result.Should().Be(expectedIndexName);
indexManger.Verify(
x => x.CreateOneAsync(
It.Is<CreateIndexModel<TestDocument>>(
t => t.Keys.EqualToJson("{\"SomeContent2\":\"text\",\"GroupingKey\":\"text\"}") &&
t.Options.EqualTo(options)),
null,
token),
Times.Once);
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
}
private Mock<IMongoDbContext> SetupContext<TDocument>(IMock<IMongoCollection<TDocument>> collection)
{
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TDocument>(It.IsAny<string>()))
.Returns(collection.Object);
return context;
}
private Mock<IMongoIndexManager<TDocument>> SetupIndexManager<TDocument>(Mock<IMongoCollection<TDocument>> collection, string indexName)
{
var indexManager = MockOf<IMongoIndexManager<TDocument>>();
indexManager
.Setup(
x => x.CreateOneAsync(
It.IsAny<CreateIndexModel<TDocument>>(),
It.IsAny<CreateOneIndexOptions>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(indexName);
collection
.SetupGet(x => x.Indexes)
.Returns(indexManager.Object);
return indexManager;
}
}
@@ -0,0 +1,180 @@
using System;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using AutoFixture;
using CoreUnitTests.Infrastructure;
using CoreUnitTests.Infrastructure.Model;
using FluentAssertions;
using MongoDB.Driver;
using MongoDbGenericRepository;
using MongoDbGenericRepository.Models;
using Moq;
using Xunit;
namespace CoreUnitTests.DataAccessTests.MongoDbIndexHandlerTests;
public class CreateDescendingIndexAsyncTests : BaseIndexTests
{
private readonly Expression<Func<TestDocument, object>> fieldExpression = t => t.SomeContent2;
[Fact]
public async Task WithFieldExpression_CreatesIndex()
{
// Arrange
var expectedIndexName = Fixture.Create<string>();
var collection = MockOf<IMongoCollection<TestDocument>>();
SetupContext(collection);
var indexManger = SetupIndexManager(collection, expectedIndexName);
// Act
var result = await Sut.CreateDescendingIndexAsync<TestDocument, Guid>(fieldExpression);
// Assert
result.Should().Be(expectedIndexName);
indexManger.Verify(
x => x.CreateOneAsync(
It.Is<CreateIndexModel<TestDocument>>(t => t.Keys.EqualToJson("{\"SomeContent2\":-1}")),
null,
CancellationToken.None),
Times.Once);
}
[Fact]
public async Task WithFieldExpressionAndOptions_CreatesIndex()
{
// Arrange
var expectedIndexName = Fixture.Create<string>();
var collection = MockOf<IMongoCollection<TestDocument>>();
var options = Fixture.Create<IndexCreationOptions>();
SetupContext(collection);
var indexManger = SetupIndexManager(collection, expectedIndexName);
// Act
var result = await Sut.CreateDescendingIndexAsync<TestDocument, Guid>(fieldExpression, options);
// Assert
result.Should().Be(expectedIndexName);
indexManger.Verify(
x => x.CreateOneAsync(
It.Is<CreateIndexModel<TestDocument>>(
t => t.Keys.EqualToJson("{\"SomeContent2\":-1}") &&
t.Options.EqualTo(options)),
null,
CancellationToken.None),
Times.Once);
}
[Fact]
public async Task WithFieldExpressionAndPartitionKey_CreatesIndex()
{
// Arrange
var expectedIndexName = Fixture.Create<string>();
var collection = MockOf<IMongoCollection<TestDocument>>();
var partitionKey = Fixture.Create<string>();
var context = SetupContext(collection);
var indexManger = SetupIndexManager(collection, expectedIndexName);
// Act
var result = await Sut.CreateDescendingIndexAsync<TestDocument, Guid>(fieldExpression, partitionKey: partitionKey);
// Assert
result.Should().Be(expectedIndexName);
indexManger.Verify(
x => x.CreateOneAsync(
It.Is<CreateIndexModel<TestDocument>>(
t => t.Keys.EqualToJson("{\"SomeContent2\":-1}") ),
null,
CancellationToken.None),
Times.Once);
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
}
[Fact]
public async Task WithFieldExpressionAndCancellationToken_CreatesIndex()
{
// Arrange
var expectedIndexName = Fixture.Create<string>();
var collection = MockOf<IMongoCollection<TestDocument>>();
var token = new CancellationToken(true);
SetupContext(collection);
var indexManger = SetupIndexManager(collection, expectedIndexName);
// Act
var result = await Sut.CreateDescendingIndexAsync<TestDocument, Guid>(fieldExpression, cancellationToken: token);
// Assert
result.Should().Be(expectedIndexName);
indexManger.Verify(
x => x.CreateOneAsync(
It.Is<CreateIndexModel<TestDocument>>(
t => t.Keys.EqualToJson("{\"SomeContent2\":-1}") ),
null,
token),
Times.Once);
}
[Fact]
public async Task WithFieldExpressionAndOptionsAndPartitionKeyAndCancellationToken_CreatesIndex()
{
// Arrange
var expectedIndexName = Fixture.Create<string>();
var collection = MockOf<IMongoCollection<TestDocument>>();
var token = new CancellationToken(true);
var partitionKey = Fixture.Create<string>();
var options = Fixture.Create<IndexCreationOptions>();
var context = SetupContext(collection);
var indexManger = SetupIndexManager(collection, expectedIndexName);
// Act
var result = await Sut.CreateDescendingIndexAsync<TestDocument, Guid>(fieldExpression, options, partitionKey, token);
// Assert
result.Should().Be(expectedIndexName);
indexManger.Verify(
x => x.CreateOneAsync(
It.Is<CreateIndexModel<TestDocument>>(
t => t.Keys.EqualToJson("{\"SomeContent2\":-1}") &&
t.Options.EqualTo(options)),
null,
token),
Times.Once);
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
}
private Mock<IMongoDbContext> SetupContext<TDocument>(IMock<IMongoCollection<TDocument>> collection)
{
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TDocument>(It.IsAny<string>()))
.Returns(collection.Object);
return context;
}
private Mock<IMongoIndexManager<TDocument>> SetupIndexManager<TDocument>(Mock<IMongoCollection<TDocument>> collection, string indexName)
{
var indexManager = MockOf<IMongoIndexManager<TDocument>>();
indexManager
.Setup(
x => x.CreateOneAsync(
It.IsAny<CreateIndexModel<TDocument>>(),
It.IsAny<CreateOneIndexOptions>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(indexName);
collection
.SetupGet(x => x.Indexes)
.Returns(indexManager.Object);
return indexManager;
}
}
@@ -0,0 +1,185 @@
using System;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using AutoFixture;
using CoreUnitTests.Infrastructure;
using CoreUnitTests.Infrastructure.Model;
using FluentAssertions;
using MongoDB.Driver;
using MongoDbGenericRepository;
using MongoDbGenericRepository.Models;
using Moq;
using Xunit;
using Xunit.Abstractions;
namespace CoreUnitTests.DataAccessTests.MongoDbIndexHandlerTests;
public class CreateHashedIndexAsyncTests : BaseIndexTests
{
private readonly ITestOutputHelper testOutputHelper;
private readonly Expression<Func<TestDocument, object>> fieldExpression = t => t.SomeContent2;
public CreateHashedIndexAsyncTests(ITestOutputHelper testOutputHelper)
=> this.testOutputHelper = testOutputHelper;
[Fact]
public async Task WithFieldExpression_CreatesIndex()
{
// Arrange
var expectedIndexName = Fixture.Create<string>();
var collection = MockOf<IMongoCollection<TestDocument>>();
SetupContext(collection);
var indexManger = SetupIndexManager(collection, expectedIndexName);
// Act
var result = await Sut.CreateHashedIndexAsync<TestDocument, Guid>(fieldExpression);
// Assert
result.Should().Be(expectedIndexName);
indexManger.Verify(
x => x.CreateOneAsync(
It.Is<CreateIndexModel<TestDocument>>(t => t.Keys.EqualToJson("{\"SomeContent2\":\"hashed\"}", testOutputHelper)),
null,
CancellationToken.None),
Times.Once);
}
[Fact]
public async Task WithFieldExpressionAndOptions_CreatesIndex()
{
// Arrange
var expectedIndexName = Fixture.Create<string>();
var collection = MockOf<IMongoCollection<TestDocument>>();
var options = Fixture.Create<IndexCreationOptions>();
SetupContext(collection);
var indexManger = SetupIndexManager(collection, expectedIndexName);
// Act
var result = await Sut.CreateHashedIndexAsync<TestDocument, Guid>(fieldExpression, options);
// Assert
result.Should().Be(expectedIndexName);
indexManger.Verify(
x => x.CreateOneAsync(
It.Is<CreateIndexModel<TestDocument>>(
t => t.Keys.EqualToJson("{\"SomeContent2\":\"hashed\"}") &&
t.Options.EqualTo(options)),
null,
CancellationToken.None),
Times.Once);
}
[Fact]
public async Task WithFieldExpressionAndPartitionKey_CreatesIndex()
{
// Arrange
var expectedIndexName = Fixture.Create<string>();
var collection = MockOf<IMongoCollection<TestDocument>>();
var partitionKey = Fixture.Create<string>();
var context = SetupContext(collection);
var indexManger = SetupIndexManager(collection, expectedIndexName);
// Act
var result = await Sut.CreateHashedIndexAsync<TestDocument, Guid>(fieldExpression, partitionKey: partitionKey);
// Assert
result.Should().Be(expectedIndexName);
indexManger.Verify(
x => x.CreateOneAsync(
It.Is<CreateIndexModel<TestDocument>>(
t => t.Keys.EqualToJson("{\"SomeContent2\":\"hashed\"}") ),
null,
CancellationToken.None),
Times.Once);
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
}
[Fact]
public async Task WithFieldExpressionAndCancellationToken_CreatesIndex()
{
// Arrange
var expectedIndexName = Fixture.Create<string>();
var collection = MockOf<IMongoCollection<TestDocument>>();
var token = new CancellationToken(true);
SetupContext(collection);
var indexManger = SetupIndexManager(collection, expectedIndexName);
// Act
var result = await Sut.CreateHashedIndexAsync<TestDocument, Guid>(fieldExpression, cancellationToken: token);
// Assert
result.Should().Be(expectedIndexName);
indexManger.Verify(
x => x.CreateOneAsync(
It.Is<CreateIndexModel<TestDocument>>(
t => t.Keys.EqualToJson("{\"SomeContent2\":\"hashed\"}") ),
null,
token),
Times.Once);
}
[Fact]
public async Task WithFieldExpressionAndOptionsAndPartitionKeyAndCancellationToken_CreatesIndex()
{
// Arrange
var expectedIndexName = Fixture.Create<string>();
var collection = MockOf<IMongoCollection<TestDocument>>();
var token = new CancellationToken(true);
var partitionKey = Fixture.Create<string>();
var options = Fixture.Create<IndexCreationOptions>();
var context = SetupContext(collection);
var indexManger = SetupIndexManager(collection, expectedIndexName);
// Act
var result = await Sut.CreateHashedIndexAsync<TestDocument, Guid>(fieldExpression, options, partitionKey, token);
// Assert
result.Should().Be(expectedIndexName);
indexManger.Verify(
x => x.CreateOneAsync(
It.Is<CreateIndexModel<TestDocument>>(
t => t.Keys.EqualToJson("{\"SomeContent2\":\"hashed\"}") &&
t.Options.EqualTo(options)),
null,
token),
Times.Once);
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
}
private Mock<IMongoDbContext> SetupContext<TDocument>(IMock<IMongoCollection<TDocument>> collection)
{
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TDocument>(It.IsAny<string>()))
.Returns(collection.Object);
return context;
}
private Mock<IMongoIndexManager<TDocument>> SetupIndexManager<TDocument>(Mock<IMongoCollection<TDocument>> collection, string indexName)
{
var indexManager = MockOf<IMongoIndexManager<TDocument>>();
indexManager
.Setup(
x => x.CreateOneAsync(
It.IsAny<CreateIndexModel<TDocument>>(),
It.IsAny<CreateOneIndexOptions>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(indexName);
collection
.SetupGet(x => x.Indexes)
.Returns(indexManager.Object);
return indexManager;
}
}
@@ -0,0 +1,180 @@
using System;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using AutoFixture;
using CoreUnitTests.Infrastructure;
using CoreUnitTests.Infrastructure.Model;
using FluentAssertions;
using MongoDB.Driver;
using MongoDbGenericRepository;
using MongoDbGenericRepository.Models;
using Moq;
using Xunit;
namespace CoreUnitTests.DataAccessTests.MongoDbIndexHandlerTests;
public class CreateTextIndexAsyncTests : BaseIndexTests
{
private readonly Expression<Func<TestDocument, object>> fieldExpression = t => t.SomeContent2;
[Fact]
public async Task WithFieldExpression_CreatesIndex()
{
// Arrange
var expectedIndexName = Fixture.Create<string>();
var collection = MockOf<IMongoCollection<TestDocument>>();
SetupContext(collection);
var indexManger = SetupIndexManager(collection, expectedIndexName);
// Act
var result = await Sut.CreateTextIndexAsync<TestDocument, Guid>(fieldExpression);
// Assert
result.Should().Be(expectedIndexName);
indexManger.Verify(
x => x.CreateOneAsync(
It.Is<CreateIndexModel<TestDocument>>(t => t.Keys.EqualToJson("{\"SomeContent2\":\"text\"}")),
null,
CancellationToken.None),
Times.Once);
}
[Fact]
public async Task WithFieldExpressionAndOptions_CreatesIndex()
{
// Arrange
var expectedIndexName = Fixture.Create<string>();
var collection = MockOf<IMongoCollection<TestDocument>>();
var options = Fixture.Create<IndexCreationOptions>();
SetupContext(collection);
var indexManger = SetupIndexManager(collection, expectedIndexName);
// Act
var result = await Sut.CreateTextIndexAsync<TestDocument, Guid>(fieldExpression, options);
// Assert
result.Should().Be(expectedIndexName);
indexManger.Verify(
x => x.CreateOneAsync(
It.Is<CreateIndexModel<TestDocument>>(
t => t.Keys.EqualToJson("{\"SomeContent2\":\"text\"}") &&
t.Options.EqualTo(options)),
null,
CancellationToken.None),
Times.Once);
}
[Fact]
public async Task WithFieldExpressionAndPartitionKey_CreatesIndex()
{
// Arrange
var expectedIndexName = Fixture.Create<string>();
var collection = MockOf<IMongoCollection<TestDocument>>();
var partitionKey = Fixture.Create<string>();
var context = SetupContext(collection);
var indexManger = SetupIndexManager(collection, expectedIndexName);
// Act
var result = await Sut.CreateTextIndexAsync<TestDocument, Guid>(fieldExpression, partitionKey: partitionKey);
// Assert
result.Should().Be(expectedIndexName);
indexManger.Verify(
x => x.CreateOneAsync(
It.Is<CreateIndexModel<TestDocument>>(
t => t.Keys.EqualToJson("{\"SomeContent2\":\"text\"}") ),
null,
CancellationToken.None),
Times.Once);
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
}
[Fact]
public async Task WithFieldExpressionAndCancellationToken_CreatesIndex()
{
// Arrange
var expectedIndexName = Fixture.Create<string>();
var collection = MockOf<IMongoCollection<TestDocument>>();
var token = new CancellationToken(true);
SetupContext(collection);
var indexManger = SetupIndexManager(collection, expectedIndexName);
// Act
var result = await Sut.CreateTextIndexAsync<TestDocument, Guid>(fieldExpression, cancellationToken: token);
// Assert
result.Should().Be(expectedIndexName);
indexManger.Verify(
x => x.CreateOneAsync(
It.Is<CreateIndexModel<TestDocument>>(
t => t.Keys.EqualToJson("{\"SomeContent2\":\"text\"}") ),
null,
token),
Times.Once);
}
[Fact]
public async Task WithFieldExpressionAndOptionsAndPartitionKeyAndCancellationToken_CreatesIndex()
{
// Arrange
var expectedIndexName = Fixture.Create<string>();
var collection = MockOf<IMongoCollection<TestDocument>>();
var token = new CancellationToken(true);
var partitionKey = Fixture.Create<string>();
var options = Fixture.Create<IndexCreationOptions>();
var context = SetupContext(collection);
var indexManger = SetupIndexManager(collection, expectedIndexName);
// Act
var result = await Sut.CreateTextIndexAsync<TestDocument, Guid>(fieldExpression, options, partitionKey, token);
// Assert
result.Should().Be(expectedIndexName);
indexManger.Verify(
x => x.CreateOneAsync(
It.Is<CreateIndexModel<TestDocument>>(
t => t.Keys.EqualToJson("{\"SomeContent2\":\"text\"}") &&
t.Options.EqualTo(options)),
null,
token),
Times.Once);
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
}
private Mock<IMongoDbContext> SetupContext<TDocument>(Mock<IMongoCollection<TDocument>> collection)
{
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TDocument>(It.IsAny<string>()))
.Returns(collection.Object);
return context;
}
private Mock<IMongoIndexManager<TDocument>> SetupIndexManager<TDocument>(Mock<IMongoCollection<TDocument>> collection, string indexName)
{
var indexManager = MockOf<IMongoIndexManager<TDocument>>();
indexManager
.Setup(
x => x.CreateOneAsync(
It.IsAny<CreateIndexModel<TDocument>>(),
It.IsAny<CreateOneIndexOptions>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(indexName);
collection
.SetupGet(x => x.Indexes)
.Returns(indexManager.Object);
return indexManager;
}
}
@@ -0,0 +1,119 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using AutoFixture;
using CoreUnitTests.Infrastructure.Model;
using MongoDB.Driver;
using MongoDbGenericRepository;
using Moq;
using Xunit;
namespace CoreUnitTests.DataAccessTests.MongoDbIndexHandlerTests;
public class DropIndexAsyncTests : BaseIndexTests
{
[Fact]
public async Task WithIndexName_DropsIndex()
{
// Arrange
var expectedIndexName = Fixture.Create<string>();
var collection = MockOf<IMongoCollection<TestDocument>>();
SetupContext(collection);
var indexManger = SetupIndexManager(collection, expectedIndexName);
// Act
await Sut.DropIndexAsync<TestDocument, Guid>(expectedIndexName);
// Assert
indexManger.Verify(x => x.DropOneAsync(expectedIndexName, CancellationToken.None), Times.Once);
}
[Fact]
public async Task WithIndexNameAndPartitionKey_DropsIndex()
{
// Arrange
var expectedIndexName = Fixture.Create<string>();
var collection = MockOf<IMongoCollection<TestDocument>>();
var partitionKey = Fixture.Create<string>();
var context = SetupContext(collection);
var indexManger = SetupIndexManager(collection, expectedIndexName);
// Act
await Sut.DropIndexAsync<TestDocument, Guid>(expectedIndexName, partitionKey);
// Assert
indexManger.Verify(x => x.DropOneAsync(expectedIndexName, CancellationToken.None), Times.Once);
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
}
[Fact]
public async Task WithIndexNameAndCancellationToken_DropsIndex()
{
// Arrange
var expectedIndexName = Fixture.Create<string>();
var collection = MockOf<IMongoCollection<TestDocument>>();
var token = new CancellationToken(true);
SetupContext(collection);
var indexManger = SetupIndexManager(collection, expectedIndexName);
// Act
await Sut.DropIndexAsync<TestDocument, Guid>(expectedIndexName, cancellationToken: token);
// Assert
indexManger.Verify(x => x.DropOneAsync(expectedIndexName, token), Times.Once);
}
[Fact]
public async Task WithIndexNameAndPartitionKeyAndCancellationToken_DropsIndex()
{
// Arrange
var expectedIndexName = Fixture.Create<string>();
var collection = MockOf<IMongoCollection<TestDocument>>();
var token = new CancellationToken(true);
var partitionKey = Fixture.Create<string>();
var context = SetupContext(collection);
var indexManger = SetupIndexManager(collection, expectedIndexName);
// Act
await Sut.DropIndexAsync<TestDocument, Guid>(expectedIndexName, partitionKey, token);
// Assert
indexManger.Verify(x => x.DropOneAsync(expectedIndexName, token), Times.Once);
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
}
private Mock<IMongoDbContext> SetupContext<TDocument>(IMock<IMongoCollection<TDocument>> collection)
{
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TDocument>(It.IsAny<string>()))
.Returns(collection.Object);
return context;
}
private Mock<IMongoIndexManager<TDocument>> SetupIndexManager<TDocument>(Mock<IMongoCollection<TDocument>> collection, string indexName)
{
var indexManager = MockOf<IMongoIndexManager<TDocument>>();
indexManager
.Setup(
x => x.CreateOneAsync(
It.IsAny<CreateIndexModel<TDocument>>(),
It.IsAny<CreateOneIndexOptions>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(indexName);
collection
.SetupGet(x => x.Indexes)
.Returns(indexManager.Object);
return indexManager;
}
}
@@ -0,0 +1,129 @@
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AutoFixture;
using CoreUnitTests.Infrastructure.Model;
using FluentAssertions;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDbGenericRepository;
using Moq;
using Xunit;
namespace CoreUnitTests.DataAccessTests.MongoDbIndexHandlerTests;
public class GetIndexNamesAsyncTests : BaseIndexTests
{
[Fact]
public async Task WithNoParameters_ReturnsAllIndexNames()
{
// Arrange
var indexNames = Fixture.CreateMany<string>().ToList();
var indexes = indexNames.Select(x => new BsonDocument {{"name", x}}).ToList();
var collection = MockOf<IMongoCollection<TestDocument>>();
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TestDocument>(It.IsAny<string>()))
.Returns(collection.Object);
var (cursor, manager) = SetupIndexes(indexes, collection);
// Act
var result = await Sut.GetIndexesNamesAsync<TestDocument, Guid>();
// Assert
result.Should().NotBeNull();
result.Should().BeEquivalentTo(indexNames);
context.Verify(x => x.GetCollection<TestDocument>(null));
manager.Verify(x => x.ListAsync(CancellationToken.None));
cursor.Verify(x => x.MoveNextAsync(CancellationToken.None));
}
[Fact]
public async Task WithPartitionKey_ReturnsAllIndexNames()
{
// Arrange
var partitionKey = Fixture.Create<string>();
var indexNames = Fixture.CreateMany<string>().ToList();
var indexes = indexNames.Select(x => new BsonDocument {{"name", x}}).ToList();
var collection = MockOf<IMongoCollection<TestDocument>>();
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TestDocument>(It.IsAny<string>()))
.Returns(collection.Object);
var (cursor, manager) = SetupIndexes(indexes, collection);
// Act
var result = await Sut.GetIndexesNamesAsync<TestDocument, Guid>(partitionKey);
// Assert
result.Should().NotBeNull();
result.Should().BeEquivalentTo(indexNames);
context.Verify(x => x.GetCollection<TestDocument>(partitionKey));
manager.Verify(x => x.ListAsync(CancellationToken.None));
cursor.Verify(x => x.MoveNextAsync(CancellationToken.None));
}
[Fact]
public async Task WithCancellationToken_ReturnsAllIndexNames()
{
// Arrange
var token = new CancellationToken();
var indexNames = Fixture.CreateMany<string>().ToList();
var indexes = indexNames.Select(x => new BsonDocument {{"name", x}}).ToList();
var collection = MockOf<IMongoCollection<TestDocument>>();
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TestDocument>(It.IsAny<string>()))
.Returns(collection.Object);
var (cursor, manager) = SetupIndexes(indexes, collection);
// Act
var result = await Sut.GetIndexesNamesAsync<TestDocument, Guid>(cancellationToken:token);
// Assert
result.Should().NotBeNull();
result.Should().BeEquivalentTo(indexNames);
context.Verify(x => x.GetCollection<TestDocument>(null));
manager.Verify(x => x.ListAsync(token));
cursor.Verify(x => x.MoveNextAsync(token));
}
[Fact]
public async Task WithPartitionKeyCancellationToken_ReturnsAllIndexNames()
{
// Arrange
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken();
var indexNames = Fixture.CreateMany<string>().ToList();
var indexes = indexNames.Select(x => new BsonDocument {{"name", x}}).ToList();
var collection = MockOf<IMongoCollection<TestDocument>>();
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TestDocument>(It.IsAny<string>()))
.Returns(collection.Object);
var (cursor, manager) = SetupIndexes(indexes, collection);
// Act
var result = await Sut.GetIndexesNamesAsync<TestDocument, Guid>(partitionKey, token);
// Assert
result.Should().NotBeNull();
result.Should().BeEquivalentTo(indexNames);
context.Verify(x => x.GetCollection<TestDocument>(partitionKey));
manager.Verify(x => x.ListAsync(token));
cursor.Verify(x => x.MoveNextAsync(token));
}
}
@@ -0,0 +1,282 @@
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using AutoFixture;
using CoreUnitTests.Infrastructure.Model;
using FluentAssertions;
using MongoDB.Driver;
using MongoDbGenericRepository;
using Moq;
using Xunit;
namespace CoreUnitTests.DataAccessTests.MongoDbReaderTests;
public class AnyAsyncTests : BaseReaderTests
{
private readonly Expression<Func<TestDocument, bool>> filter = x => x.SomeContent == "SomeContent";
[Fact]
public async Task WithFilter_ReturnsResult()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TestDocument>(null))
.Returns(collection.Object);
collection
.Setup(
x => x.CountDocumentsAsync(
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<CountOptions>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(documents.Count);
// Act
var result = await Sut.AnyAsync<TestDocument, Guid>(filter);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
collection.Verify(
x => x.CountDocumentsAsync(It.Is<ExpressionFilterDefinition<TestDocument>>(y => y.Expression == filter), null, CancellationToken.None),
Times.Once);
result.Should().BeTrue();
}
[Fact]
public async Task WithFilterAndCancellationToken_ReturnsResult()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var token = new CancellationToken(true);
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TestDocument>(null))
.Returns(collection.Object);
collection
.Setup(
x => x.CountDocumentsAsync(
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<CountOptions>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(documents.Count);
// Act
var result = await Sut.AnyAsync<TestDocument, Guid>(filter, cancellationToken: token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
collection.Verify(
x => x.CountDocumentsAsync(It.Is<ExpressionFilterDefinition<TestDocument>>(y => y.Expression == filter), null, token),
Times.Once);
result.Should().BeTrue();
}
[Fact]
public async Task WithFilterAndPartitionKey_ReturnsResult()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var partitionKey = Fixture.Create<string>();
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TestDocument>(partitionKey))
.Returns(collection.Object);
collection
.Setup(
x => x.CountDocumentsAsync(
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<CountOptions>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(documents.Count);
// Act
var result = await Sut.AnyAsync<TestDocument, Guid>(filter, partitionKey);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
collection.Verify(
x => x.CountDocumentsAsync(It.Is<ExpressionFilterDefinition<TestDocument>>(y => y.Expression == filter), null, CancellationToken.None),
Times.Once);
result.Should().BeTrue();
}
[Fact]
public async Task WithFilterAndPartitionKeyAndCancellationToken_ReturnsResult()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TestDocument>(partitionKey))
.Returns(collection.Object);
collection
.Setup(
x => x.CountDocumentsAsync(
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<CountOptions>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(documents.Count);
// Act
var result = await Sut.AnyAsync<TestDocument, Guid>(filter, partitionKey, token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
collection.Verify(
x => x.CountDocumentsAsync(It.Is<ExpressionFilterDefinition<TestDocument>>(y => y.Expression == filter), null, token),
Times.Once);
result.Should().BeTrue();
}
[Fact]
public async Task WithCondition_ReturnsResult()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var condition = Builders<TestDocument>.Filter.Eq("Id", documents[0].Id);
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TestDocument>(null))
.Returns(collection.Object);
collection
.Setup(
x => x.CountDocumentsAsync(
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<CountOptions>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(documents.Count);
// Act
var result = await Sut.AnyAsync<TestDocument, Guid>(condition);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
collection.Verify(
x => x.CountDocumentsAsync(condition, null, CancellationToken.None),
Times.Once);
result.Should().BeTrue();
}
[Fact]
public async Task WithConditionAndCancellationToken_ReturnsResult()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var condition = Builders<TestDocument>.Filter.Eq("Id", documents[0].Id);
var token = new CancellationToken(true);
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TestDocument>(null))
.Returns(collection.Object);
collection
.Setup(
x => x.CountDocumentsAsync(
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<CountOptions>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(documents.Count);
// Act
var result = await Sut.AnyAsync<TestDocument, Guid>(condition, cancellationToken: token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
collection.Verify(
x => x.CountDocumentsAsync(condition, null, token),
Times.Once);
result.Should().BeTrue();
}
[Fact]
public async Task WithConditionAndPartitionKey_ReturnsResult()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var condition = Builders<TestDocument>.Filter.Eq("Id", documents[0].Id);
var partitionKey = Fixture.Create<string>();
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TestDocument>(partitionKey))
.Returns(collection.Object);
collection
.Setup(
x => x.CountDocumentsAsync(
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<CountOptions>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(documents.Count);
// Act
var result = await Sut.AnyAsync<TestDocument, Guid>(condition, partitionKey: partitionKey);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
collection.Verify(
x => x.CountDocumentsAsync(condition, null, CancellationToken.None),
Times.Once);
result.Should().BeTrue();
}
[Fact]
public async Task WithConditionAndPartitionKeyAndCancellationToken_ReturnsResult()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var condition = Builders<TestDocument>.Filter.Eq("Id", documents[0].Id);
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TestDocument>(partitionKey))
.Returns(collection.Object);
collection
.Setup(
x => x.CountDocumentsAsync(
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<CountOptions>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(documents.Count);
// Act
var result = await Sut.AnyAsync<TestDocument, Guid>(condition, partitionKey: partitionKey, cancellationToken:token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
collection.Verify(
x => x.CountDocumentsAsync(condition, null, token),
Times.Once);
result.Should().BeTrue();
}
}
@@ -0,0 +1,281 @@
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using AutoFixture;
using CoreUnitTests.Infrastructure.Model;
using FluentAssertions;
using MongoDB.Driver;
using MongoDbGenericRepository;
using Moq;
using Xunit;
namespace CoreUnitTests.DataAccessTests.MongoDbReaderTests;
public class AnyTests : BaseReaderTests
{
private readonly Expression<Func<TestDocument, bool>> filter = x => x.SomeContent == "SomeContent";
[Fact]
public void WithFilter_ReturnsResult()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TestDocument>(null))
.Returns(collection.Object);
collection
.Setup(
x => x.CountDocuments(
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<CountOptions>(),
It.IsAny<CancellationToken>()))
.Returns(documents.Count);
// Act
var result = Sut.Any<TestDocument, Guid>(filter);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
collection.Verify(
x => x.CountDocuments(It.Is<ExpressionFilterDefinition<TestDocument>>(y => y.Expression == filter), null, CancellationToken.None),
Times.Once);
result.Should().BeTrue();
}
[Fact]
public void WithFilterAndCancellationToken_ReturnsResult()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var token = new CancellationToken(true);
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TestDocument>(null))
.Returns(collection.Object);
collection
.Setup(
x => x.CountDocuments(
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<CountOptions>(),
It.IsAny<CancellationToken>()))
.Returns(documents.Count);
// Act
var result = Sut.Any<TestDocument, Guid>(filter, cancellationToken: token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
collection.Verify(
x => x.CountDocuments(It.Is<ExpressionFilterDefinition<TestDocument>>(y => y.Expression == filter), null, token),
Times.Once);
result.Should().BeTrue();
}
[Fact]
public void WithFilterAndPartitionKey_ReturnsResult()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var partitionKey = Fixture.Create<string>();
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TestDocument>(partitionKey))
.Returns(collection.Object);
collection
.Setup(
x => x.CountDocuments(
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<CountOptions>(),
It.IsAny<CancellationToken>()))
.Returns(documents.Count);
// Act
var result = Sut.Any<TestDocument, Guid>(filter, partitionKey);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
collection.Verify(
x => x.CountDocuments(It.Is<ExpressionFilterDefinition<TestDocument>>(y => y.Expression == filter), null, CancellationToken.None),
Times.Once);
result.Should().BeTrue();
}
[Fact]
public void WithFilterAndPartitionKeyAndCancellationToken_ReturnsResult()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TestDocument>(partitionKey))
.Returns(collection.Object);
collection
.Setup(
x => x.CountDocuments(
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<CountOptions>(),
It.IsAny<CancellationToken>()))
.Returns(documents.Count);
// Act
var result = Sut.Any<TestDocument, Guid>(filter, partitionKey, token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
collection.Verify(
x => x.CountDocuments(It.Is<ExpressionFilterDefinition<TestDocument>>(y => y.Expression == filter), null, token),
Times.Once);
result.Should().BeTrue();
}
[Fact]
public void WithCondition_ReturnsResult()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var condition = Builders<TestDocument>.Filter.Eq("Id", documents[0].Id);
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TestDocument>(null))
.Returns(collection.Object);
collection
.Setup(
x => x.CountDocuments(
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<CountOptions>(),
It.IsAny<CancellationToken>()))
.Returns(documents.Count);
// Act
var result = Sut.Any<TestDocument, Guid>(condition);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
collection.Verify(
x => x.CountDocuments(condition, null, CancellationToken.None),
Times.Once);
result.Should().BeTrue();
}
[Fact]
public void WithConditionAndCancellationToken_ReturnsResult()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var condition = Builders<TestDocument>.Filter.Eq("Id", documents[0].Id);
var token = new CancellationToken(true);
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TestDocument>(null))
.Returns(collection.Object);
collection
.Setup(
x => x.CountDocuments(
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<CountOptions>(),
It.IsAny<CancellationToken>()))
.Returns(documents.Count);
// Act
var result = Sut.Any<TestDocument, Guid>(condition, cancellationToken: token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
collection.Verify(
x => x.CountDocuments(condition, null, token),
Times.Once);
result.Should().BeTrue();
}
[Fact]
public void WithConditionAndPartitionKey_ReturnsResult()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var condition = Builders<TestDocument>.Filter.Eq("Id", documents[0].Id);
var partitionKey = Fixture.Create<string>();
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TestDocument>(partitionKey))
.Returns(collection.Object);
collection
.Setup(
x => x.CountDocuments(
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<CountOptions>(),
It.IsAny<CancellationToken>()))
.Returns(documents.Count);
// Act
var result = Sut.Any<TestDocument, Guid>(condition, partitionKey: partitionKey);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
collection.Verify(
x => x.CountDocuments(condition, null, CancellationToken.None),
Times.Once);
result.Should().BeTrue();
}
[Fact]
public void WithConditionAndPartitionKeyAndCancellationToken_ReturnsResult()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var condition = Builders<TestDocument>.Filter.Eq("Id", documents[0].Id);
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TestDocument>(partitionKey))
.Returns(collection.Object);
collection
.Setup(
x => x.CountDocuments(
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<CountOptions>(),
It.IsAny<CancellationToken>()))
.Returns(documents.Count);
// Act
var result = Sut.Any<TestDocument, Guid>(condition, partitionKey: partitionKey, cancellationToken: token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
collection.Verify(
x => x.CountDocuments(condition, null, token),
Times.Once);
result.Should().BeTrue();
}
}
@@ -0,0 +1,69 @@
using System.Collections.Generic;
using System.Threading;
using CoreUnitTests.Infrastructure;
using MongoDB.Driver;
using MongoDbGenericRepository.DataAccess.Read;
using Moq;
namespace CoreUnitTests.DataAccessTests.MongoDbReaderTests;
public class BaseReaderTests : GenericTestContext<MongoDbReader>
{
protected Mock<IAsyncCursor<TDocument>> SetupSyncCursor<TDocument>(List<TDocument> documents)
{
var asyncCursor = MockOf<IAsyncCursor<TDocument>>();
var moveNextSequence = asyncCursor
.SetupSequence(x => x.MoveNext(It.IsAny<CancellationToken>()));
var currentSequence = asyncCursor
.SetupSequence(x => x.Current);
foreach (var projection in documents)
{
moveNextSequence.Returns(true);
currentSequence.Returns(new[] {projection});
}
moveNextSequence.Returns(false);
return asyncCursor;
}
protected Mock<IAsyncCursor<TDocument>> SetupAsyncCursor<TDocument>(List<TDocument> documents)
{
var asyncCursor = MockOf<IAsyncCursor<TDocument>>();
var moveNextSequence = asyncCursor
.SetupSequence(x => x.MoveNextAsync(It.IsAny<CancellationToken>()));
var currentSequence = asyncCursor
.SetupSequence(x => x.Current);
foreach (var projection in documents)
{
moveNextSequence.ReturnsAsync(true);
currentSequence.Returns(new[] {projection});
}
moveNextSequence.ReturnsAsync(false);
return asyncCursor;
}
protected static void SetupFindAsync<TDocument, TProjection>(Mock<IMongoCollection<TDocument>> collection, Mock<IAsyncCursor<TProjection>> asyncCursor) =>
collection
.Setup(
x => x.FindAsync(
It.IsAny<FilterDefinition<TDocument>>(),
It.IsAny<FindOptions<TDocument, TProjection>>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(asyncCursor.Object);
protected static void SetupFindSync<TDocument, TProjection>(Mock<IMongoCollection<TDocument>> collection, Mock<IAsyncCursor<TProjection>> asyncCursor) =>
collection
.Setup(
x => x.FindSync(
It.IsAny<FilterDefinition<TDocument>>(),
It.IsAny<FindOptions<TDocument, TProjection>>(),
It.IsAny<CancellationToken>()))
.Returns(asyncCursor.Object);
}
@@ -0,0 +1,282 @@
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using AutoFixture;
using CoreUnitTests.Infrastructure.Model;
using FluentAssertions;
using MongoDB.Driver;
using MongoDbGenericRepository;
using Moq;
using Xunit;
namespace CoreUnitTests.DataAccessTests.MongoDbReaderTests;
public class CountAsyncTests : BaseReaderTests
{
private readonly Expression<Func<TestDocument, bool>> filter = x => x.SomeContent == "SomeContent";
[Fact]
public async Task WithFilter_ReturnsResult()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TestDocument>(null))
.Returns(collection.Object);
collection
.Setup(
x => x.CountDocumentsAsync(
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<CountOptions>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(documents.Count);
// Act
var result = await Sut.CountAsync<TestDocument, Guid>(filter);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
collection.Verify(
x => x.CountDocumentsAsync(It.Is<ExpressionFilterDefinition<TestDocument>>(y => y.Expression == filter), null, CancellationToken.None),
Times.Once);
result.Should().Be(documents.Count);
}
[Fact]
public async Task WithFilterAndCancellationToken_ReturnsResult()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var token = new CancellationToken(true);
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TestDocument>(null))
.Returns(collection.Object);
collection
.Setup(
x => x.CountDocumentsAsync(
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<CountOptions>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(documents.Count);
// Act
var result = await Sut.CountAsync<TestDocument, Guid>(filter, cancellationToken: token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
collection.Verify(
x => x.CountDocumentsAsync(It.Is<ExpressionFilterDefinition<TestDocument>>(y => y.Expression == filter), null, token),
Times.Once);
result.Should().Be(documents.Count);
}
[Fact]
public async Task WithFilterAndPartitionKey_ReturnsResult()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var partitionKey = Fixture.Create<string>();
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TestDocument>(partitionKey))
.Returns(collection.Object);
collection
.Setup(
x => x.CountDocumentsAsync(
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<CountOptions>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(documents.Count);
// Act
var result = await Sut.CountAsync<TestDocument, Guid>(filter, partitionKey);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
collection.Verify(
x => x.CountDocumentsAsync(It.Is<ExpressionFilterDefinition<TestDocument>>(y => y.Expression == filter), null, CancellationToken.None),
Times.Once);
result.Should().Be(documents.Count);
}
[Fact]
public async Task WithFilterAndPartitionKeyAndCancellationToken_ReturnsResult()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TestDocument>(partitionKey))
.Returns(collection.Object);
collection
.Setup(
x => x.CountDocumentsAsync(
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<CountOptions>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(documents.Count);
// Act
var result = await Sut.CountAsync<TestDocument, Guid>(filter, partitionKey, token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
collection.Verify(
x => x.CountDocumentsAsync(It.Is<ExpressionFilterDefinition<TestDocument>>(y => y.Expression == filter), null, token),
Times.Once);
result.Should().Be(documents.Count);
}
[Fact]
public async Task WithCondition_ReturnsResult()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var condition = Builders<TestDocument>.Filter.Eq("Id", documents[0].Id);
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TestDocument>(null))
.Returns(collection.Object);
collection
.Setup(
x => x.CountDocumentsAsync(
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<CountOptions>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(documents.Count);
// Act
var result = await Sut.CountAsync<TestDocument, Guid>(condition);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
collection.Verify(
x => x.CountDocumentsAsync(condition, null, CancellationToken.None),
Times.Once);
result.Should().Be(documents.Count);
}
[Fact]
public async Task WithConditionAndCancellationToken_ReturnsResult()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var condition = Builders<TestDocument>.Filter.Eq("Id", documents[0].Id);
var token = new CancellationToken(true);
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TestDocument>(null))
.Returns(collection.Object);
collection
.Setup(
x => x.CountDocumentsAsync(
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<CountOptions>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(documents.Count);
// Act
var result = await Sut.CountAsync<TestDocument, Guid>(condition, cancellationToken: token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
collection.Verify(
x => x.CountDocumentsAsync(condition, null, token),
Times.Once);
result.Should().Be(documents.Count);
}
[Fact]
public async Task WithConditionAndPartitionKey_ReturnsResult()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var condition = Builders<TestDocument>.Filter.Eq("Id", documents[0].Id);
var partitionKey = Fixture.Create<string>();
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TestDocument>(partitionKey))
.Returns(collection.Object);
collection
.Setup(
x => x.CountDocumentsAsync(
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<CountOptions>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(documents.Count);
// Act
var result = await Sut.CountAsync<TestDocument, Guid>(condition, partitionKey: partitionKey);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
collection.Verify(
x => x.CountDocumentsAsync(condition, null, CancellationToken.None),
Times.Once);
result.Should().Be(documents.Count);
}
[Fact]
public async Task WithConditionAndPartitionKeyAndCancellationToken_ReturnsResult()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var condition = Builders<TestDocument>.Filter.Eq("Id", documents[0].Id);
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TestDocument>(partitionKey))
.Returns(collection.Object);
collection
.Setup(
x => x.CountDocumentsAsync(
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<CountOptions>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(documents.Count);
// Act
var result = await Sut.CountAsync<TestDocument, Guid>(condition, partitionKey: partitionKey, cancellationToken:token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
collection.Verify(
x => x.CountDocumentsAsync(condition, null, token),
Times.Once);
result.Should().Be(documents.Count);
}
}
@@ -0,0 +1,281 @@
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using AutoFixture;
using CoreUnitTests.Infrastructure.Model;
using FluentAssertions;
using MongoDB.Driver;
using MongoDbGenericRepository;
using Moq;
using Xunit;
namespace CoreUnitTests.DataAccessTests.MongoDbReaderTests;
public class CountTests : BaseReaderTests
{
private readonly Expression<Func<TestDocument, bool>> filter = x => x.SomeContent == "SomeContent";
[Fact]
public void WithFilter_ReturnsResult()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TestDocument>(null))
.Returns(collection.Object);
collection
.Setup(
x => x.CountDocuments(
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<CountOptions>(),
It.IsAny<CancellationToken>()))
.Returns(documents.Count);
// Act
var result = Sut.Count<TestDocument, Guid>(filter);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
collection.Verify(
x => x.CountDocuments(It.Is<ExpressionFilterDefinition<TestDocument>>(y => y.Expression == filter), It.IsAny<CountOptions>(), CancellationToken.None),
Times.Once);
result.Should().Be(documents.Count);
}
[Fact]
public void WithFilterAndCancellationToken_ReturnsResult()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var token = new CancellationToken(true);
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TestDocument>(null))
.Returns(collection.Object);
collection
.Setup(
x => x.CountDocuments(
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<CountOptions>(),
It.IsAny<CancellationToken>()))
.Returns(documents.Count);
// Act
var result = Sut.Count<TestDocument, Guid>(filter, cancellationToken: token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
collection.Verify(
x => x.CountDocuments(It.Is<ExpressionFilterDefinition<TestDocument>>(y => y.Expression == filter), It.IsAny<CountOptions>(), token),
Times.Once);
result.Should().Be(documents.Count);
}
[Fact]
public void WithFilterAndPartitionKey_ReturnsResult()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var partitionKey = Fixture.Create<string>();
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TestDocument>(partitionKey))
.Returns(collection.Object);
collection
.Setup(
x => x.CountDocuments(
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<CountOptions>(),
It.IsAny<CancellationToken>()))
.Returns(documents.Count);
// Act
var result = Sut.Count<TestDocument, Guid>(filter, partitionKey);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
collection.Verify(
x => x.CountDocuments(It.Is<ExpressionFilterDefinition<TestDocument>>(y => y.Expression == filter), It.IsAny<CountOptions>(), CancellationToken.None),
Times.Once);
result.Should().Be(documents.Count);
}
[Fact]
public void WithFilterAndPartitionKeyAndCancellationToken_ReturnsResult()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TestDocument>(partitionKey))
.Returns(collection.Object);
collection
.Setup(
x => x.CountDocuments(
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<CountOptions>(),
It.IsAny<CancellationToken>()))
.Returns(documents.Count);
// Act
var result = Sut.Count<TestDocument, Guid>(filter, partitionKey, token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
collection.Verify(
x => x.CountDocuments(It.Is<ExpressionFilterDefinition<TestDocument>>(y => y.Expression == filter), It.IsAny<CountOptions>(), token),
Times.Once);
result.Should().Be(documents.Count);
}
[Fact]
public void WithCondition_ReturnsResult()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var condition = Builders<TestDocument>.Filter.Eq("Id", documents[0].Id);
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TestDocument>(null))
.Returns(collection.Object);
collection
.Setup(
x => x.CountDocuments(
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<CountOptions>(),
It.IsAny<CancellationToken>()))
.Returns(documents.Count);
// Act
var result = Sut.Count<TestDocument, Guid>(condition);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
collection.Verify(
x => x.CountDocuments(condition, null, CancellationToken.None),
Times.Once);
result.Should().Be(documents.Count);
}
[Fact]
public void WithConditionAndCancellationToken_ReturnsResult()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var condition = Builders<TestDocument>.Filter.Eq("Id", documents[0].Id);
var token = new CancellationToken(true);
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TestDocument>(null))
.Returns(collection.Object);
collection
.Setup(
x => x.CountDocuments(
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<CountOptions>(),
It.IsAny<CancellationToken>()))
.Returns(documents.Count);
// Act
var result = Sut.Count<TestDocument, Guid>(condition, cancellationToken: token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
collection.Verify(
x => x.CountDocuments(condition, null, token),
Times.Once);
result.Should().Be(documents.Count);
}
[Fact]
public void WithConditionAndPartitionKey_ReturnsResult()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var condition = Builders<TestDocument>.Filter.Eq("Id", documents[0].Id);
var partitionKey = Fixture.Create<string>();
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TestDocument>(partitionKey))
.Returns(collection.Object);
collection
.Setup(
x => x.CountDocuments(
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<CountOptions>(),
It.IsAny<CancellationToken>()))
.Returns(documents.Count);
// Act
var result = Sut.Count<TestDocument, Guid>(condition, partitionKey: partitionKey);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
collection.Verify(
x => x.CountDocuments(condition, null, CancellationToken.None),
Times.Once);
result.Should().Be(documents.Count);
}
[Fact]
public void WithConditionAndPartitionKeyAndCancellationToken_ReturnsResult()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var condition = Builders<TestDocument>.Filter.Eq("Id", documents[0].Id);
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TestDocument>(partitionKey))
.Returns(collection.Object);
collection
.Setup(
x => x.CountDocuments(
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<CountOptions>(),
It.IsAny<CancellationToken>()))
.Returns(documents.Count);
// Act
var result = Sut.Count<TestDocument, Guid>(condition, partitionKey: partitionKey, cancellationToken: token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
collection.Verify(
x => x.CountDocuments(condition, null, token),
Times.Once);
result.Should().Be(documents.Count);
}
}
@@ -0,0 +1,283 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using AutoFixture;
using CoreUnitTests.Infrastructure.Model;
using FluentAssertions;
using MongoDB.Driver;
using MongoDbGenericRepository;
using Moq;
using Xunit;
namespace CoreUnitTests.DataAccessTests.MongoDbReaderTests;
public class GetAllAsyncTests : BaseReaderTests
{
[Fact]
public async Task WithFilter_GetsMatchingDocuments()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
Expression<Func<TestDocument, bool>> filter = x => x.Id == documents[0].Id;
var (context, cursor) = SetupAsyncGet(documents, collection);
// Act
var result = await Sut.GetAllAsync<TestDocument, Guid>(filter);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.Current, Times.Exactly(documents.Count));
cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.Exactly(documents.Count + 1));
result.Should().NotBeNull();
result.Should().OnlyContain(x => documents.Contains(x));
}
[Fact]
public async Task WithFilterAndCancellationToken_GetsMatchingDocuments()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var token = new CancellationToken(false);
Expression<Func<TestDocument, bool>> filter = x => x.Id == documents[0].Id;
var (context, cursor) = SetupAsyncGet(documents, collection);
// Act
var result = await Sut.GetAllAsync<TestDocument, Guid>(filter, cancellationToken: token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.Current, Times.Exactly(documents.Count));
cursor.Verify(x => x.MoveNextAsync(token), Times.Exactly(documents.Count + 1));
result.Should().NotBeNull();
result.Should().OnlyContain(x => documents.Contains(x));
}
[Fact]
public async Task WithFilterAndPartitionKey_GetsMatchingDocuments()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var partitionKey = Fixture.Create<string>();
Expression<Func<TestDocument, bool>> filter = x => x.Id == documents[0].Id;
var (context, cursor) = SetupAsyncGet(documents, collection, partitionKey);
// Act
var result = await Sut.GetAllAsync<TestDocument, Guid>(filter, partitionKey);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.Current, Times.Exactly(documents.Count));
cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.Exactly(documents.Count + 1));
result.Should().NotBeNull();
result.Should().OnlyContain(x => documents.Contains(x));
}
[Fact]
public async Task WithFilterAndPartitionKeyAndCancellationToken_GetsMatchingDocuments()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(false);
Expression<Func<TestDocument, bool>> filter = x => x.Id == documents[0].Id;
var (context, cursor) = SetupAsyncGet(documents, collection, partitionKey);
// Act
var result = await Sut.GetAllAsync<TestDocument, Guid>(filter, partitionKey, token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.Current, Times.Exactly(documents.Count));
cursor.Verify(x => x.MoveNextAsync(token), Times.Exactly(documents.Count + 1));
result.Should().NotBeNull();
result.Should().OnlyContain(x => documents.Contains(x));
}
[Fact]
public async Task WithCondition_GetsMatchingDocuments()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var condition = Builders<TestDocument>.Filter.Eq("Id", documents[0].Id);
var (context, cursor) = SetupAsyncGet(documents, collection);
// Act
var result = await Sut.GetAllAsync<TestDocument, Guid>(condition);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.Current, Times.Exactly(documents.Count));
cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.Exactly(documents.Count + 1));
result.Should().NotBeNull();
result.Should().OnlyContain(x => documents.Contains(x));
}
[Fact]
public async Task WithConditionAndCancellationToken_GetsMatchingDocuments()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var condition = Builders<TestDocument>.Filter.Eq("Id", documents[0].Id);
var token = new CancellationToken(false);
var (context, cursor) = SetupAsyncGet(documents, collection);
// Act
var result = await Sut.GetAllAsync<TestDocument, Guid>(condition, cancellationToken: token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.Current, Times.Exactly(documents.Count));
cursor.Verify(x => x.MoveNextAsync(token), Times.Exactly(documents.Count + 1));
result.Should().NotBeNull();
result.Should().OnlyContain(x => documents.Contains(x));
}
[Fact]
public async Task WithConditionAndPartitionKey_GetsMatchingDocuments()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var condition = Builders<TestDocument>.Filter.Eq("Id", documents[0].Id);
var partitionKey = Fixture.Create<string>();
var (context, cursor) = SetupAsyncGet(documents, collection, partitionKey);
// Act
var result = await Sut.GetAllAsync<TestDocument, Guid>(condition, partitionKey: partitionKey);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.Exactly(documents.Count + 1));
cursor.Verify(x => x.Current, Times.Exactly(documents.Count));
result.Should().NotBeNull();
result.Should().OnlyContain(x => documents.Contains(x));
}
[Fact]
public async Task WithConditionAndPartitionKeyAndCancellationToken_GetsMatchingDocuments()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var condition = Builders<TestDocument>.Filter.Eq("Id", documents[0].Id);
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(false);
var (context, cursor) = SetupAsyncGet(documents, collection, partitionKey);
// Act
var result = await Sut.GetAllAsync<TestDocument, Guid>(condition, partitionKey: partitionKey, cancellationToken: token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.Current, Times.Exactly(documents.Count));
cursor.Verify(x => x.MoveNextAsync(token), Times.Exactly(documents.Count + 1));
result.Should().NotBeNull();
result.Should().OnlyContain(x => documents.Contains(x));
}
[Fact]
public async Task WithConditionAndFindOptions_GetsMatchingDocuments()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var options = Fixture
.Build<FindOptions>()
.Without(x => x.Comment)
.Without(x => x.Hint)
.Create();
var condition = Builders<TestDocument>.Filter.Eq("Id", documents[0].Id);
var (context, cursor) = SetupAsyncGet(documents, collection);
// Act
var result = await Sut.GetAllAsync<TestDocument, Guid>(condition, options);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.Current, Times.Exactly(documents.Count));
cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.Exactly(documents.Count + 1));
result.Should().NotBeNull();
result.Should().OnlyContain(x => documents.Contains(x));
}
[Fact]
public async Task WithConditionAndFindOptionsAndCancellationToken_GetsMatchingDocuments()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var options = Fixture
.Build<FindOptions>()
.Without(x => x.Comment)
.Without(x => x.Hint)
.Create();
var condition = Builders<TestDocument>.Filter.Eq("Id", documents[0].Id);
var token = new CancellationToken(false);
var (context, cursor) = SetupAsyncGet(documents, collection);
// Act
var result = await Sut.GetAllAsync<TestDocument, Guid>(condition, options, cancellationToken: token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.Current, Times.Exactly(documents.Count));
cursor.Verify(x => x.MoveNextAsync(token), Times.Exactly(documents.Count + 1));
result.Should().NotBeNull();
result.Should().OnlyContain(x => documents.Contains(x));
}
[Fact]
public async Task WithConditionAndFindOptionsAndPartitionKeyAndCancellationToken_GetsMatchingDocuments()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var options = Fixture
.Build<FindOptions>()
.Without(x => x.Comment)
.Without(x => x.Hint)
.Create();
var condition = Builders<TestDocument>.Filter.Eq("Id", documents[0].Id);
var token = new CancellationToken(false);
var partitionKey = Fixture.Create<string>();
var (context, cursor) = SetupAsyncGet(documents, collection, partitionKey);
// Act
var result = await Sut.GetAllAsync<TestDocument, Guid>(condition, options, partitionKey, token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.Current, Times.Exactly(documents.Count));
cursor.Verify(x => x.MoveNextAsync(token), Times.Exactly(documents.Count + 1));
result.Should().NotBeNull();
result.Should().OnlyContain(x => documents.Contains(x));
}
private (Mock<IMongoDbContext>, Mock<IAsyncCursor<TDocument>>) SetupAsyncGet<TDocument>(
List<TDocument> documents,
Mock<IMongoCollection<TDocument>> collection,
string partitionKey = null)
{
var asyncCursor = SetupAsyncCursor(documents);
SetupFindAsync(collection, asyncCursor);
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TDocument>(partitionKey))
.Returns(collection.Object);
return (context, asyncCursor);
}
}
@@ -0,0 +1,282 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using AutoFixture;
using CoreUnitTests.Infrastructure.Model;
using FluentAssertions;
using MongoDB.Driver;
using MongoDbGenericRepository;
using Moq;
using Xunit;
namespace CoreUnitTests.DataAccessTests.MongoDbReaderTests;
public class GetAllTests : BaseReaderTests
{
[Fact]
public void WithFilter_GetsMatchingDocuments()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
Expression<Func<TestDocument, bool>> filter = x => x.Id == documents[0].Id;
var (context, cursor) = SetupGet(documents, collection);
// Act
var result = Sut.GetAll<TestDocument, Guid>(filter);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.Current, Times.Exactly(documents.Count));
cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.Exactly(documents.Count + 1));
result.Should().NotBeNull();
result.Should().OnlyContain(x => documents.Contains(x));
}
[Fact]
public void WithFilterAndCancellationToken_GetsMatchingDocuments()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var token = new CancellationToken(false);
Expression<Func<TestDocument, bool>> filter = x => x.Id == documents[0].Id;
var (context, cursor) = SetupGet(documents, collection);
// Act
var result = Sut.GetAll<TestDocument, Guid>(filter, cancellationToken: token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.Current, Times.Exactly(documents.Count));
cursor.Verify(x => x.MoveNext(token), Times.Exactly(documents.Count + 1));
result.Should().NotBeNull();
result.Should().OnlyContain(x => documents.Contains(x));
}
[Fact]
public void WithFilterAndPartitionKey_GetsMatchingDocuments()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var partitionKey = Fixture.Create<string>();
Expression<Func<TestDocument, bool>> filter = x => x.Id == documents[0].Id;
var (context, cursor) = SetupGet(documents, collection, partitionKey);
// Act
var result = Sut.GetAll<TestDocument, Guid>(filter, partitionKey);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.Current, Times.Exactly(documents.Count));
cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.Exactly(documents.Count + 1));
result.Should().NotBeNull();
result.Should().OnlyContain(x => documents.Contains(x));
}
[Fact]
public void WithFilterAndPartitionKeyAndCancellationToken_GetsMatchingDocuments()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(false);
Expression<Func<TestDocument, bool>> filter = x => x.Id == documents[0].Id;
var (context, cursor) = SetupGet(documents, collection, partitionKey);
// Act
var result = Sut.GetAll<TestDocument, Guid>(filter, partitionKey, token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.Current, Times.Exactly(documents.Count));
cursor.Verify(x => x.MoveNext(token), Times.Exactly(documents.Count + 1));
result.Should().NotBeNull();
result.Should().OnlyContain(x => documents.Contains(x));
}
[Fact]
public void WithCondition_GetsMatchingDocuments()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var condition = Builders<TestDocument>.Filter.Eq("Id", documents[0].Id);
var (context, cursor) = SetupGet(documents, collection);
// Act
var result = Sut.GetAll<TestDocument, Guid>(condition);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.Current, Times.Exactly(documents.Count));
cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.Exactly(documents.Count + 1));
result.Should().NotBeNull();
result.Should().OnlyContain(x => documents.Contains(x));
}
[Fact]
public void WithConditionAndCancellationToken_GetsMatchingDocuments()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var condition = Builders<TestDocument>.Filter.Eq("Id", documents[0].Id);
var token = new CancellationToken(false);
var (context, cursor) = SetupGet(documents, collection);
// Act
var result = Sut.GetAll<TestDocument, Guid>(condition, cancellationToken: token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.Current, Times.Exactly(documents.Count));
cursor.Verify(x => x.MoveNext(token), Times.Exactly(documents.Count + 1));
result.Should().NotBeNull();
result.Should().OnlyContain(x => documents.Contains(x));
}
[Fact]
public void WithConditionAndPartitionKey_GetsMatchingDocuments()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var condition = Builders<TestDocument>.Filter.Eq("Id", documents[0].Id);
var partitionKey = Fixture.Create<string>();
var (context, cursor) = SetupGet(documents, collection, partitionKey);
// Act
var result = Sut.GetAll<TestDocument, Guid>(condition, partitionKey: partitionKey);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.Exactly(documents.Count + 1));
cursor.Verify(x => x.Current, Times.Exactly(documents.Count));
result.Should().NotBeNull();
result.Should().OnlyContain(x => documents.Contains(x));
}
[Fact]
public void WithConditionAndPartitionKeyAndCancellationToken_GetsMatchingDocuments()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var condition = Builders<TestDocument>.Filter.Eq("Id", documents[0].Id);
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(false);
var (context, cursor) = SetupGet(documents, collection, partitionKey);
// Act
var result = Sut.GetAll<TestDocument, Guid>(condition, partitionKey: partitionKey, cancellationToken: token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.Current, Times.Exactly(documents.Count));
cursor.Verify(x => x.MoveNext(token), Times.Exactly(documents.Count + 1));
result.Should().NotBeNull();
result.Should().OnlyContain(x => documents.Contains(x));
}
[Fact]
public void WithConditionAndFindOptions_GetsMatchingDocuments()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var options = Fixture
.Build<FindOptions>()
.Without(x => x.Comment)
.Without(x => x.Hint)
.Create();
var condition = Builders<TestDocument>.Filter.Eq("Id", documents[0].Id);
var (context, cursor) = SetupGet(documents, collection);
// Act
var result = Sut.GetAll<TestDocument, Guid>(condition, options);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.Current, Times.Exactly(documents.Count));
cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.Exactly(documents.Count + 1));
result.Should().NotBeNull();
result.Should().OnlyContain(x => documents.Contains(x));
}
[Fact]
public void WithConditionAndFindOptionsAndCancellationToken_GetsMatchingDocuments()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var options = Fixture
.Build<FindOptions>()
.Without(x => x.Comment)
.Without(x => x.Hint)
.Create();
var condition = Builders<TestDocument>.Filter.Eq("Id", documents[0].Id);
var token = new CancellationToken(false);
var (context, cursor) = SetupGet(documents, collection);
// Act
var result = Sut.GetAll<TestDocument, Guid>(condition, options, cancellationToken: token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.Current, Times.Exactly(documents.Count));
cursor.Verify(x => x.MoveNext(token), Times.Exactly(documents.Count + 1));
result.Should().NotBeNull();
result.Should().OnlyContain(x => documents.Contains(x));
}
[Fact]
public void WithConditionAndFindOptionsAndPartitionKeyAndCancellationToken_GetsMatchingDocuments()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var options = Fixture
.Build<FindOptions>()
.Without(x => x.Comment)
.Without(x => x.Hint)
.Create();
var condition = Builders<TestDocument>.Filter.Eq("Id", documents[0].Id);
var token = new CancellationToken(false);
var partitionKey = Fixture.Create<string>();
var (context, cursor) = SetupGet(documents, collection, partitionKey);
// Act
var result = Sut.GetAll<TestDocument, Guid>(condition, options, partitionKey, token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.Current, Times.Exactly(documents.Count));
cursor.Verify(x => x.MoveNext(token), Times.Exactly(documents.Count + 1));
result.Should().NotBeNull();
result.Should().OnlyContain(x => documents.Contains(x));
}
private (Mock<IMongoDbContext>, Mock<IAsyncCursor<TDocument>>) SetupGet<TDocument>(
List<TDocument> documents,
Mock<IMongoCollection<TDocument>> collection,
string partitionKey = null)
{
var asyncCursor = SetupSyncCursor(documents);
SetupFindSync(collection, asyncCursor);
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TDocument>(partitionKey))
.Returns(collection.Object);
return (context, asyncCursor);
}
}
@@ -0,0 +1,115 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AutoFixture;
using CoreUnitTests.Infrastructure.Model;
using FluentAssertions;
using MongoDB.Driver;
using MongoDbGenericRepository;
using Moq;
using Xunit;
namespace CoreUnitTests.DataAccessTests.MongoDbReaderTests;
public class GetByIdAsyncTests : BaseReaderTests
{
[Fact]
public async Task WithId_GetsMatchingDocument()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var (context, cursor) = SetupAsyncGet(documents, collection);
// Act
var result = await Sut.GetByIdAsync<TestDocument, Guid>(documents[0].Id);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.Once);
result.Should().NotBeNull();
result.Should().Be(documents[0]);
}
[Fact]
public async Task WithIdAndCancellationToken_GetsMatchingDocument()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var token = new CancellationToken(true);
var (context, cursor) = SetupAsyncGet(documents, collection);
// Act
var result = await Sut.GetByIdAsync<TestDocument, Guid>(documents[0].Id, cancellationToken: token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNextAsync(token), Times.Once);
result.Should().NotBeNull();
result.Should().Be(documents[0]);
}
[Fact]
public async Task WithIdAndPartitionKey_GetsMatchingDocument()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var partitionKey = Fixture.Create<string>();
var (context, cursor) = SetupAsyncGet(documents, collection, partitionKey);
// Act
var result = await Sut.GetByIdAsync<TestDocument, Guid>(documents[0].Id, partitionKey);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.Once);
result.Should().NotBeNull();
result.Should().Be(documents[0]);
}
[Fact]
public async Task WithIdAndPartitionKeyAndCancellationToken_GetsMatchingDocument()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
var (context, cursor) = SetupAsyncGet(documents, collection, partitionKey);
// Act
var result = await Sut.GetByIdAsync<TestDocument, Guid>(documents[0].Id, partitionKey, token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNextAsync(token), Times.Once);
result.Should().NotBeNull();
result.Should().Be(documents[0]);
}
private (Mock<IMongoDbContext>, Mock<IAsyncCursor<TDocument>>) SetupAsyncGet<TDocument>(
List<TDocument> documents,
Mock<IMongoCollection<TDocument>> collection,
string partitionKey = null)
{
var asyncCursor = SetupAsyncCursor(documents);
SetupFindAsync(collection, asyncCursor);
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TDocument>(partitionKey))
.Returns(collection.Object);
return (context, asyncCursor);
}
}
@@ -0,0 +1,114 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using AutoFixture;
using CoreUnitTests.Infrastructure.Model;
using FluentAssertions;
using MongoDB.Driver;
using MongoDbGenericRepository;
using Moq;
using Xunit;
namespace CoreUnitTests.DataAccessTests.MongoDbReaderTests;
public class GetByIdTests : BaseReaderTests
{
[Fact]
public void WithId_GetsMatchingDocument()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var (context, cursor) = SetupAsyncGet(documents, collection);
// Act
var result = Sut.GetById<TestDocument, Guid>(documents[0].Id);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.Once);
result.Should().NotBeNull();
result.Should().Be(documents[0]);
}
[Fact]
public void WithIdAndCancellationToken_GetsMatchingDocument()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var token = new CancellationToken(true);
var (context, cursor) = SetupAsyncGet(documents, collection);
// Act
var result = Sut.GetById<TestDocument, Guid>(documents[0].Id, cancellationToken: token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNext(token), Times.Once);
result.Should().NotBeNull();
result.Should().Be(documents[0]);
}
[Fact]
public void WithIdAndPartitionKey_GetsMatchingDocument()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var partitionKey = Fixture.Create<string>();
var (context, cursor) = SetupAsyncGet(documents, collection, partitionKey);
// Act
var result = Sut.GetById<TestDocument, Guid>(documents[0].Id, partitionKey);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.Once);
result.Should().NotBeNull();
result.Should().Be(documents[0]);
}
[Fact]
public void WithIdAndPartitionKeyAndCancellationToken_GetsMatchingDocument()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
var (context, cursor) = SetupAsyncGet(documents, collection, partitionKey);
// Act
var result = Sut.GetById<TestDocument, Guid>(documents[0].Id, partitionKey, token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNext(token), Times.Once);
result.Should().NotBeNull();
result.Should().Be(documents[0]);
}
private (Mock<IMongoDbContext>, Mock<IAsyncCursor<TDocument>>) SetupAsyncGet<TDocument>(
List<TDocument> documents,
Mock<IMongoCollection<TDocument>> collection,
string partitionKey = null)
{
var asyncCursor = SetupSyncCursor(documents);
SetupFindSync(collection, asyncCursor);
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TDocument>(partitionKey))
.Returns(collection.Object);
return (context, asyncCursor);
}
}
@@ -0,0 +1,119 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using AutoFixture;
using CoreUnitTests.Infrastructure.Model;
using FluentAssertions;
using MongoDB.Driver;
using MongoDbGenericRepository;
using Moq;
using Xunit;
namespace CoreUnitTests.DataAccessTests.MongoDbReaderTests;
public class GetByMaxAsyncTests : BaseReaderTests
{
private readonly Expression<Func<TestDocument, bool>> filter = x => x.SomeContent == "SomeContent";
private readonly Expression<Func<TestDocument, object>> selector = x => x.SomeValue;
[Fact]
public async Task WithFilterAndSelector_GetsMatchingDocument()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var (context, cursor) = SetupAsyncGet(documents, collection);
// Act
var result = await Sut.GetByMaxAsync<TestDocument, Guid>(filter, selector);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.Once);
result.Should().NotBeNull();
result.Should().Be(documents[0]);
}
[Fact]
public async Task WithFilterAndSelectorAndCancellationToken_GetsMatchingDocument()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var token = new CancellationToken(true);
var (context, cursor) = SetupAsyncGet(documents, collection);
// Act
var result = await Sut.GetByMaxAsync<TestDocument, Guid>(filter, selector, cancellationToken: token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNextAsync(token), Times.Once);
result.Should().NotBeNull();
result.Should().Be(documents[0]);
}
[Fact]
public async Task WithFilterAndSelectorAndPartitionKey_GetsMatchingDocument()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var partitionKey = Fixture.Create<string>();
var (context, cursor) = SetupAsyncGet(documents, collection, partitionKey);
// Act
var result = await Sut.GetByMaxAsync<TestDocument, Guid>(filter, selector, partitionKey);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.Once);
result.Should().NotBeNull();
result.Should().Be(documents[0]);
}
[Fact]
public async Task WithFilterAndSelectorAndPartitionKeyAndCancellationToken_GetsMatchingDocument()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
var (context, cursor) = SetupAsyncGet(documents, collection, partitionKey);
// Act
var result = await Sut.GetByMaxAsync<TestDocument, Guid>(filter, selector, partitionKey, token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNextAsync(token), Times.Once);
result.Should().NotBeNull();
result.Should().Be(documents[0]);
}
private (Mock<IMongoDbContext>, Mock<IAsyncCursor<TDocument>>) SetupAsyncGet<TDocument>(
List<TDocument> documents,
Mock<IMongoCollection<TDocument>> collection,
string partitionKey = null)
{
var asyncCursor = SetupAsyncCursor(documents);
SetupFindAsync(collection, asyncCursor);
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TDocument>(partitionKey))
.Returns(collection.Object);
return (context, asyncCursor);
}
}
@@ -0,0 +1,119 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using AutoFixture;
using CoreUnitTests.Infrastructure.Model;
using FluentAssertions;
using MongoDB.Driver;
using MongoDbGenericRepository;
using Moq;
using Xunit;
namespace CoreUnitTests.DataAccessTests.MongoDbReaderTests;
public class GetByMaxTests : BaseReaderTests
{
private readonly Expression<Func<TestDocument, bool>> filter = x => x.SomeContent == "SomeContent";
private readonly Expression<Func<TestDocument, object>> selector = x => x.SomeValue;
[Fact]
public void WithFilterAndSelector_GetsMatchingDocument()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var (context, cursor) = SetupSyncGet(documents, collection);
// Act
var result = Sut.GetByMax<TestDocument, Guid>(filter, selector);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.Once);
result.Should().NotBeNull();
result.Should().Be(documents[0]);
}
[Fact]
public void WithFilterAndSelectorAndCancellationToken_GetsMatchingDocument()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var token = new CancellationToken(true);
var (context, cursor) = SetupSyncGet(documents, collection);
// Act
var result = Sut.GetByMax<TestDocument, Guid>(filter, selector, cancellationToken: token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNext(token), Times.Once);
result.Should().NotBeNull();
result.Should().Be(documents[0]);
}
[Fact]
public void WithFilterAndSelectorAndPartitionKey_GetsMatchingDocument()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var partitionKey = Fixture.Create<string>();
var (context, cursor) = SetupSyncGet(documents, collection, partitionKey);
// Act
var result = Sut.GetByMax<TestDocument, Guid>(filter, selector, partitionKey);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.Once);
result.Should().NotBeNull();
result.Should().Be(documents[0]);
}
[Fact]
public void WithFilterAndSelectorAndPartitionKeyAndCancellationToken_GetsMatchingDocument()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
var (context, cursor) = SetupSyncGet(documents, collection, partitionKey);
// Act
var result = Sut.GetByMax<TestDocument, Guid>(filter, selector, partitionKey, token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNext(token), Times.Once);
result.Should().NotBeNull();
result.Should().Be(documents[0]);
}
private (Mock<IMongoDbContext>, Mock<IAsyncCursor<TDocument>>) SetupSyncGet<TDocument>(
List<TDocument> documents,
Mock<IMongoCollection<TDocument>> collection,
string partitionKey = null)
{
var asyncCursor = SetupSyncCursor(documents);
SetupFindSync(collection, asyncCursor);
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TDocument>(partitionKey))
.Returns(collection.Object);
return (context, asyncCursor);
}
}
@@ -0,0 +1,119 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using AutoFixture;
using CoreUnitTests.Infrastructure.Model;
using FluentAssertions;
using MongoDB.Driver;
using MongoDbGenericRepository;
using Moq;
using Xunit;
namespace CoreUnitTests.DataAccessTests.MongoDbReaderTests;
public class GetByMinAsyncTests : BaseReaderTests
{
private readonly Expression<Func<TestDocument, bool>> filter = x => x.SomeContent == "SomeContent";
private readonly Expression<Func<TestDocument, object>> selector = x => x.SomeValue;
[Fact]
public async Task WithFilterAndSelector_GetsMatchingDocument()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var (context, cursor) = SetupAsyncGet(documents, collection);
// Act
var result = await Sut.GetByMinAsync<TestDocument, Guid>(filter, selector);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.Once);
result.Should().NotBeNull();
result.Should().Be(documents[0]);
}
[Fact]
public async Task WithFilterAndSelectorAndCancellationToken_GetsMatchingDocument()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var token = new CancellationToken(true);
var (context, cursor) = SetupAsyncGet(documents, collection);
// Act
var result = await Sut.GetByMinAsync<TestDocument, Guid>(filter, selector, cancellationToken: token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNextAsync(token), Times.Once);
result.Should().NotBeNull();
result.Should().Be(documents[0]);
}
[Fact]
public async Task WithFilterAndSelectorAndPartitionKey_GetsMatchingDocument()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var partitionKey = Fixture.Create<string>();
var (context, cursor) = SetupAsyncGet(documents, collection, partitionKey);
// Act
var result = await Sut.GetByMinAsync<TestDocument, Guid>(filter, selector, partitionKey);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.Once);
result.Should().NotBeNull();
result.Should().Be(documents[0]);
}
[Fact]
public async Task WithFilterAndSelectorAndPartitionKeyAndCancellationToken_GetsMatchingDocument()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
var (context, cursor) = SetupAsyncGet(documents, collection, partitionKey);
// Act
var result = await Sut.GetByMinAsync<TestDocument, Guid>(filter, selector, partitionKey, token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNextAsync(token), Times.Once);
result.Should().NotBeNull();
result.Should().Be(documents[0]);
}
private (Mock<IMongoDbContext>, Mock<IAsyncCursor<TDocument>>) SetupAsyncGet<TDocument>(
List<TDocument> documents,
Mock<IMongoCollection<TDocument>> collection,
string partitionKey = null)
{
var asyncCursor = SetupAsyncCursor(documents);
SetupFindAsync(collection, asyncCursor);
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TDocument>(partitionKey))
.Returns(collection.Object);
return (context, asyncCursor);
}
}
@@ -0,0 +1,119 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using AutoFixture;
using CoreUnitTests.Infrastructure.Model;
using FluentAssertions;
using MongoDB.Driver;
using MongoDbGenericRepository;
using Moq;
using Xunit;
namespace CoreUnitTests.DataAccessTests.MongoDbReaderTests;
public class GetByMinTests : BaseReaderTests
{
private readonly Expression<Func<TestDocument, bool>> filter = x => x.SomeContent == "SomeContent";
private readonly Expression<Func<TestDocument, object>> selector = x => x.SomeValue;
[Fact]
public void WithFilterAndSelector_GetsMatchingDocument()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var (context, cursor) = SetupSyncGet(documents, collection);
// Act
var result = Sut.GetByMin<TestDocument, Guid>(filter, selector);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.Once);
result.Should().NotBeNull();
result.Should().Be(documents[0]);
}
[Fact]
public void WithFilterAndSelectorAndCancellationToken_GetsMatchingDocument()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var token = new CancellationToken(true);
var (context, cursor) = SetupSyncGet(documents, collection);
// Act
var result = Sut.GetByMin<TestDocument, Guid>(filter, selector, cancellationToken: token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNext(token), Times.Once);
result.Should().NotBeNull();
result.Should().Be(documents[0]);
}
[Fact]
public void WithFilterAndSelectorAndPartitionKey_GetsMatchingDocument()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var partitionKey = Fixture.Create<string>();
var (context, cursor) = SetupSyncGet(documents, collection, partitionKey);
// Act
var result = Sut.GetByMin<TestDocument, Guid>(filter, selector, partitionKey);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.Once);
result.Should().NotBeNull();
result.Should().Be(documents[0]);
}
[Fact]
public void WithFilterAndSelectorAndPartitionKeyAndCancellationToken_GetsMatchingDocument()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
var (context, cursor) = SetupSyncGet(documents, collection, partitionKey);
// Act
var result = Sut.GetByMin<TestDocument, Guid>(filter, selector, partitionKey, token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNext(token), Times.Once);
result.Should().NotBeNull();
result.Should().Be(documents[0]);
}
private (Mock<IMongoDbContext>, Mock<IAsyncCursor<TDocument>>) SetupSyncGet<TDocument>(
List<TDocument> documents,
Mock<IMongoCollection<TDocument>> collection,
string partitionKey = null)
{
var asyncCursor = SetupSyncCursor(documents);
SetupFindSync(collection, asyncCursor);
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TDocument>(partitionKey))
.Returns(collection.Object);
return (context, asyncCursor);
}
}
@@ -0,0 +1,114 @@
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using AutoFixture;
using CoreUnitTests.Infrastructure.Model;
using FluentAssertions;
using MongoDB.Driver;
using MongoDbGenericRepository;
using Moq;
using Xunit;
namespace CoreUnitTests.DataAccessTests.MongoDbReaderTests;
public class GetMaxValueAsyncTests : BaseReaderTests
{
private readonly Expression<Func<TestDocument, bool>> filter = x => x.SomeContent == "SomeContent";
private readonly Expression<Func<TestDocument, int>> selector = x => x.SomeValue;
[Fact]
public async Task WithFilterAndSelector_GetsMatchingDocument()
{
// Arrange
var value = Fixture.Create<int>();
var collection = MockOf<IMongoCollection<TestDocument>>();
var (context, cursor) = SetupAsyncGet(value, collection);
// Act
var result = await Sut.GetMaxValueAsync<TestDocument, Guid, int>(filter, selector);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.Once);
result.Should().Be(value);
}
[Fact]
public async Task WithFilterAndSelectorAndCancellationToken_GetsMatchingDocument()
{
// Arrange
var value = Fixture.Create<int>();
var collection = MockOf<IMongoCollection<TestDocument>>();
var token = new CancellationToken(true);
var (context, cursor) = SetupAsyncGet(value, collection);
// Act
var result = await Sut.GetMaxValueAsync<TestDocument, Guid, int>(filter, selector, cancellationToken: token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNextAsync(token), Times.Once);
result.Should().Be(value);
}
[Fact]
public async Task WithFilterAndSelectorAndPartitionKey_GetsMatchingDocument()
{
// Arrange
var value = Fixture.Create<int>();
var collection = MockOf<IMongoCollection<TestDocument>>();
var partitionKey = Fixture.Create<string>();
var (context, cursor) = SetupAsyncGet(value, collection, partitionKey);
// Act
var result = await Sut.GetMaxValueAsync<TestDocument, Guid, int>(filter, selector, partitionKey);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.Once);
result.Should().Be(value);
}
[Fact]
public async Task WithFilterAndSelectorAndPartitionKeyAndCancellationToken_GetsMatchingDocument()
{
// Arrange
var value = Fixture.Create<int>();
var collection = MockOf<IMongoCollection<TestDocument>>();
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
var (context, cursor) = SetupAsyncGet(value, collection, partitionKey);
// Act
var result = await Sut.GetMaxValueAsync<TestDocument, Guid, int>(filter, selector, partitionKey, token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNextAsync(token), Times.Once);
result.Should().Be(value);
}
private (Mock<IMongoDbContext>, Mock<IAsyncCursor<TValue>>) SetupAsyncGet<TDocument, TValue>(
TValue result,
Mock<IMongoCollection<TDocument>> collection,
string partitionKey = null)
{
var asyncCursor = SetupAsyncCursor(new List<TValue> {result});
SetupFindAsync(collection, asyncCursor);
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TDocument>(partitionKey))
.Returns(collection.Object);
return (context, asyncCursor);
}
}
@@ -0,0 +1,114 @@
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using AutoFixture;
using CoreUnitTests.Infrastructure.Model;
using FluentAssertions;
using MongoDB.Driver;
using MongoDbGenericRepository;
using Moq;
using Xunit;
namespace CoreUnitTests.DataAccessTests.MongoDbReaderTests;
public class GetMaxValueTests : BaseReaderTests
{
private readonly Expression<Func<TestDocument, bool>> filter = x => x.SomeContent == "SomeContent";
private readonly Expression<Func<TestDocument, int>> selector = x => x.SomeValue;
[Fact]
public void WithFilterAndSelector_GetsMatchingDocument()
{
// Arrange
var value = Fixture.Create<int>();
var collection = MockOf<IMongoCollection<TestDocument>>();
var (context, cursor) = SetupSyncGet(value, collection);
// Act
var result = Sut.GetMaxValue<TestDocument, Guid, int>(filter, selector);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.Once);
result.Should().Be(value);
}
[Fact]
public void WithFilterAndSelectorAndCancellationToken_GetsMatchingDocument()
{
// Arrange
var value = Fixture.Create<int>();
var collection = MockOf<IMongoCollection<TestDocument>>();
var token = new CancellationToken(true);
var (context, cursor) = SetupSyncGet(value, collection);
// Act
var result = Sut.GetMaxValue<TestDocument, Guid, int>(filter, selector, cancellationToken: token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNext(token), Times.Once);
result.Should().Be(value);
}
[Fact]
public void WithFilterAndSelectorAndPartitionKey_GetsMatchingDocument()
{
// Arrange
var value = Fixture.Create<int>();
var collection = MockOf<IMongoCollection<TestDocument>>();
var partitionKey = Fixture.Create<string>();
var (context, cursor) = SetupSyncGet(value, collection, partitionKey);
// Act
var result = Sut.GetMaxValue<TestDocument, Guid, int>(filter, selector, partitionKey);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.Once);
result.Should().Be(value);
}
[Fact]
public void WithFilterAndSelectorAndPartitionKeyAndCancellationToken_GetsMatchingDocument()
{
// Arrange
var value = Fixture.Create<int>();
var collection = MockOf<IMongoCollection<TestDocument>>();
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
var (context, cursor) = SetupSyncGet(value, collection, partitionKey);
// Act
var result = Sut.GetMaxValue<TestDocument, Guid, int>(filter, selector, partitionKey, token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNext(token), Times.Once);
result.Should().Be(value);
}
private (Mock<IMongoDbContext>, Mock<IAsyncCursor<TValue>>) SetupSyncGet<TDocument, TValue>(
TValue result,
Mock<IMongoCollection<TDocument>> collection,
string partitionKey = null)
{
var asyncCursor = SetupSyncCursor(new List<TValue> {result});
SetupFindSync(collection, asyncCursor);
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TDocument>(partitionKey))
.Returns(collection.Object);
return (context, asyncCursor);
}
}
@@ -0,0 +1,114 @@
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using AutoFixture;
using CoreUnitTests.Infrastructure.Model;
using FluentAssertions;
using MongoDB.Driver;
using MongoDbGenericRepository;
using Moq;
using Xunit;
namespace CoreUnitTests.DataAccessTests.MongoDbReaderTests;
public class GetMinValueAsyncTests : BaseReaderTests
{
private readonly Expression<Func<TestDocument, bool>> filter = x => x.SomeContent == "SomeContent";
private readonly Expression<Func<TestDocument, int>> selector = x => x.SomeValue;
[Fact]
public async Task WithFilterAndSelector_GetsMatchingDocument()
{
// Arrange
var value = Fixture.Create<int>();
var collection = MockOf<IMongoCollection<TestDocument>>();
var (context, cursor) = SetupAsyncGet(value, collection);
// Act
var result = await Sut.GetMinValueAsync<TestDocument, Guid, int>(filter, selector);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.Once);
result.Should().Be(value);
}
[Fact]
public async Task WithFilterAndSelectorAndCancellationToken_GetsMatchingDocument()
{
// Arrange
var value = Fixture.Create<int>();
var collection = MockOf<IMongoCollection<TestDocument>>();
var token = new CancellationToken(true);
var (context, cursor) = SetupAsyncGet(value, collection);
// Act
var result = await Sut.GetMinValueAsync<TestDocument, Guid, int>(filter, selector, cancellationToken: token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNextAsync(token), Times.Once);
result.Should().Be(value);
}
[Fact]
public async Task WithFilterAndSelectorAndPartitionKey_GetsMatchingDocument()
{
// Arrange
var value = Fixture.Create<int>();
var collection = MockOf<IMongoCollection<TestDocument>>();
var partitionKey = Fixture.Create<string>();
var (context, cursor) = SetupAsyncGet(value, collection, partitionKey);
// Act
var result = await Sut.GetMinValueAsync<TestDocument, Guid, int>(filter, selector, partitionKey);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.Once);
result.Should().Be(value);
}
[Fact]
public async Task WithFilterAndSelectorAndPartitionKeyAndCancellationToken_GetsMatchingDocument()
{
// Arrange
var value = Fixture.Create<int>();
var collection = MockOf<IMongoCollection<TestDocument>>();
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
var (context, cursor) = SetupAsyncGet(value, collection, partitionKey);
// Act
var result = await Sut.GetMinValueAsync<TestDocument, Guid, int>(filter, selector, partitionKey, token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNextAsync(token), Times.Once);
result.Should().Be(value);
}
private (Mock<IMongoDbContext>, Mock<IAsyncCursor<TValue>>) SetupAsyncGet<TDocument, TValue>(
TValue result,
Mock<IMongoCollection<TDocument>> collection,
string partitionKey = null)
{
var asyncCursor = SetupAsyncCursor(new List<TValue> {result});
SetupFindAsync(collection, asyncCursor);
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TDocument>(partitionKey))
.Returns(collection.Object);
return (context, asyncCursor);
}
}
@@ -0,0 +1,114 @@
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using AutoFixture;
using CoreUnitTests.Infrastructure.Model;
using FluentAssertions;
using MongoDB.Driver;
using MongoDbGenericRepository;
using Moq;
using Xunit;
namespace CoreUnitTests.DataAccessTests.MongoDbReaderTests;
public class GetMinValueTests : BaseReaderTests
{
private readonly Expression<Func<TestDocument, bool>> filter = x => x.SomeContent == "SomeContent";
private readonly Expression<Func<TestDocument, int>> selector = x => x.SomeValue;
[Fact]
public void WithFilterAndSelector_GetsMatchingDocument()
{
// Arrange
var value = Fixture.Create<int>();
var collection = MockOf<IMongoCollection<TestDocument>>();
var (context, cursor) = SetupSyncGet(value, collection);
// Act
var result = Sut.GetMinValue<TestDocument, Guid, int>(filter, selector);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.Once);
result.Should().Be(value);
}
[Fact]
public void WithFilterAndSelectorAndCancellationToken_GetsMatchingDocument()
{
// Arrange
var value = Fixture.Create<int>();
var collection = MockOf<IMongoCollection<TestDocument>>();
var token = new CancellationToken(true);
var (context, cursor) = SetupSyncGet(value, collection);
// Act
var result = Sut.GetMinValue<TestDocument, Guid, int>(filter, selector, cancellationToken: token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNext(token), Times.Once);
result.Should().Be(value);
}
[Fact]
public void WithFilterAndSelectorAndPartitionKey_GetsMatchingDocument()
{
// Arrange
var value = Fixture.Create<int>();
var collection = MockOf<IMongoCollection<TestDocument>>();
var partitionKey = Fixture.Create<string>();
var (context, cursor) = SetupSyncGet(value, collection, partitionKey);
// Act
var result = Sut.GetMinValue<TestDocument, Guid, int>(filter, selector, partitionKey);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.Once);
result.Should().Be(value);
}
[Fact]
public void WithFilterAndSelectorAndPartitionKeyAndCancellationToken_GetsMatchingDocument()
{
// Arrange
var value = Fixture.Create<int>();
var collection = MockOf<IMongoCollection<TestDocument>>();
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
var (context, cursor) = SetupSyncGet(value, collection, partitionKey);
// Act
var result = Sut.GetMinValue<TestDocument, Guid, int>(filter, selector, partitionKey, token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNext(token), Times.Once);
result.Should().Be(value);
}
private (Mock<IMongoDbContext>, Mock<IAsyncCursor<TValue>>) SetupSyncGet<TDocument, TValue>(
TValue result,
Mock<IMongoCollection<TDocument>> collection,
string partitionKey = null)
{
var asyncCursor = SetupSyncCursor(new List<TValue> {result});
SetupFindSync(collection, asyncCursor);
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TDocument>(partitionKey))
.Returns(collection.Object);
return (context, asyncCursor);
}
}
@@ -0,0 +1,283 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using AutoFixture;
using CoreUnitTests.Infrastructure.Model;
using FluentAssertions;
using MongoDB.Driver;
using MongoDbGenericRepository;
using Moq;
using Xunit;
namespace CoreUnitTests.DataAccessTests.MongoDbReaderTests;
public class GetOneAsyncTests : BaseReaderTests
{
[Fact]
public async Task WithFilter_GetsMatchingDocuments()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
Expression<Func<TestDocument, bool>> filter = x => x.Id == documents[0].Id;
var (context, cursor) = SetupAsyncGet(documents, collection);
// Act
var result = await Sut.GetOneAsync<TestDocument, Guid>(filter);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.Once);
result.Should().NotBeNull();
result.Should().Be(documents[0]);
}
[Fact]
public async Task WithFilterAndCancellationToken_GetsMatchingDocuments()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var token = new CancellationToken(true);
Expression<Func<TestDocument, bool>> filter = x => x.Id == documents[0].Id;
var (context, cursor) = SetupAsyncGet(documents, collection);
// Act
var result = await Sut.GetOneAsync<TestDocument, Guid>(filter, cancellationToken: token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNextAsync(token), Times.Once);
result.Should().NotBeNull();
result.Should().Be(documents[0]);
}
[Fact]
public async Task WithFilterAndPartitionKey_GetsMatchingDocuments()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var partitionKey = Fixture.Create<string>();
Expression<Func<TestDocument, bool>> filter = x => x.Id == documents[0].Id;
var (context, cursor) = SetupAsyncGet(documents, collection, partitionKey);
// Act
var result = await Sut.GetOneAsync<TestDocument, Guid>(filter, partitionKey);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.Once);
result.Should().NotBeNull();
result.Should().Be(documents[0]);
}
[Fact]
public async Task WithFilterAndPartitionKeyAndCancellationToken_GetsMatchingDocuments()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
Expression<Func<TestDocument, bool>> filter = x => x.Id == documents[0].Id;
var (context, cursor) = SetupAsyncGet(documents, collection, partitionKey);
// Act
var result = await Sut.GetOneAsync<TestDocument, Guid>(filter, partitionKey, token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNextAsync(token), Times.Once);
result.Should().NotBeNull();
result.Should().Be(documents[0]);
}
[Fact]
public async Task WithCondition_GetsMatchingDocuments()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var condition = Builders<TestDocument>.Filter.Eq("Id", documents[0].Id);
var (context, cursor) = SetupAsyncGet(documents, collection);
// Act
var result = await Sut.GetOneAsync<TestDocument, Guid>(condition);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.Once);
result.Should().NotBeNull();
result.Should().Be(documents[0]);
}
[Fact]
public async Task WithConditionAndCancellationToken_GetsMatchingDocuments()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var condition = Builders<TestDocument>.Filter.Eq("Id", documents[0].Id);
var token = new CancellationToken(true);
var (context, cursor) = SetupAsyncGet(documents, collection);
// Act
var result = await Sut.GetOneAsync<TestDocument, Guid>(condition, cancellationToken: token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNextAsync(token), Times.Once);
result.Should().NotBeNull();
result.Should().Be(documents[0]);
}
[Fact]
public async Task WithConditionAndPartitionKey_GetsMatchingDocuments()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var condition = Builders<TestDocument>.Filter.Eq("Id", documents[0].Id);
var partitionKey = Fixture.Create<string>();
var (context, cursor) = SetupAsyncGet(documents, collection, partitionKey);
// Act
var result = await Sut.GetOneAsync<TestDocument, Guid>(condition, partitionKey: partitionKey);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
result.Should().NotBeNull();
result.Should().Be(documents[0]);
}
[Fact]
public async Task WithConditionAndPartitionKeyAndCancellationToken_GetsMatchingDocuments()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var condition = Builders<TestDocument>.Filter.Eq("Id", documents[0].Id);
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
var (context, cursor) = SetupAsyncGet(documents, collection, partitionKey);
// Act
var result = await Sut.GetOneAsync<TestDocument, Guid>(condition, partitionKey: partitionKey, cancellationToken: token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNextAsync(token), Times.Once);
result.Should().NotBeNull();
result.Should().Be(documents[0]);
}
[Fact]
public async Task WithConditionAndFindOptions_GetsMatchingDocuments()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var options = Fixture
.Build<FindOptions>()
.Without(x => x.Comment)
.Without(x => x.Hint)
.Create();
var condition = Builders<TestDocument>.Filter.Eq("Id", documents[0].Id);
var (context, cursor) = SetupAsyncGet(documents, collection);
// Act
var result = await Sut.GetOneAsync<TestDocument, Guid>(condition, options);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.Once);
result.Should().NotBeNull();
result.Should().Be(documents[0]);
}
[Fact]
public async Task WithConditionAndFindOptionsAndCancellationToken_GetsMatchingDocuments()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var options = Fixture
.Build<FindOptions>()
.Without(x => x.Comment)
.Without(x => x.Hint)
.Create();
var condition = Builders<TestDocument>.Filter.Eq("Id", documents[0].Id);
var token = new CancellationToken(true);
var (context, cursor) = SetupAsyncGet(documents, collection);
// Act
var result = await Sut.GetOneAsync<TestDocument, Guid>(condition, options, cancellationToken: token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNextAsync(token), Times.Once);
result.Should().NotBeNull();
result.Should().Be(documents[0]);
}
[Fact]
public async Task WithConditionAndFindOptionsAndPartitionKeyAndCancellationToken_GetsMatchingDocuments()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var options = Fixture
.Build<FindOptions>()
.Without(x => x.Comment)
.Without(x => x.Hint)
.Create();
var condition = Builders<TestDocument>.Filter.Eq("Id", documents[0].Id);
var token = new CancellationToken(true);
var partitionKey = Fixture.Create<string>();
var (context, cursor) = SetupAsyncGet(documents, collection, partitionKey);
// Act
var result = await Sut.GetOneAsync<TestDocument, Guid>(condition, options, partitionKey, token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNextAsync(token), Times.Once);
result.Should().NotBeNull();
result.Should().Be(documents[0]);
}
private (Mock<IMongoDbContext>, Mock<IAsyncCursor<TDocument>>) SetupAsyncGet<TDocument>(
List<TDocument> documents,
Mock<IMongoCollection<TDocument>> collection,
string partitionKey = null)
{
var asyncCursor = SetupAsyncCursor(documents);
SetupFindAsync(collection, asyncCursor);
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TDocument>(partitionKey))
.Returns(collection.Object);
return (context, asyncCursor);
}
}
@@ -0,0 +1,282 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using AutoFixture;
using CoreUnitTests.Infrastructure.Model;
using FluentAssertions;
using MongoDB.Driver;
using MongoDbGenericRepository;
using Moq;
using Xunit;
namespace CoreUnitTests.DataAccessTests.MongoDbReaderTests;
public class GetOneTests : BaseReaderTests
{
[Fact]
public void WithFilter_GetsMatchingDocuments()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
Expression<Func<TestDocument, bool>> filter = x => x.Id == documents[0].Id;
var (context, cursor) = SetupSyncGet(documents, collection);
// Act
var result = Sut.GetOne<TestDocument, Guid>(filter);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
result.Should().NotBeNull();
result.Should().Be(documents[0]);
}
[Fact]
public void WithFilterAndCancellationToken_GetsMatchingDocuments()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var token = new CancellationToken(true);
Expression<Func<TestDocument, bool>> filter = x => x.Id == documents[0].Id;
var (context, cursor) = SetupSyncGet(documents, collection);
// Act
var result = Sut.GetOne<TestDocument, Guid>(filter, cancellationToken: token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNext(token), Times.Once);
result.Should().NotBeNull();
result.Should().Be(documents[0]);
}
[Fact]
public void WithFilterAndPartitionKey_GetsMatchingDocuments()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var partitionKey = Fixture.Create<string>();
Expression<Func<TestDocument, bool>> filter = x => x.Id == documents[0].Id;
var (context, cursor) = SetupSyncGet(documents, collection, partitionKey);
// Act
var result = Sut.GetOne<TestDocument, Guid>(filter, partitionKey);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.Once);
result.Should().NotBeNull();
result.Should().Be(documents[0]);
}
[Fact]
public void WithFilterAndPartitionKeyAndCancellationToken_GetsMatchingDocuments()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
Expression<Func<TestDocument, bool>> filter = x => x.Id == documents[0].Id;
var (context, cursor) = SetupSyncGet(documents, collection, partitionKey);
// Act
var result = Sut.GetOne<TestDocument, Guid>(filter, partitionKey, token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNext(token), Times.Once);
result.Should().NotBeNull();
result.Should().Be(documents[0]);
}
[Fact]
public void WithCondition_GetsMatchingDocuments()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var condition = Builders<TestDocument>.Filter.Eq("Id", documents[0].Id);
var (context, cursor) = SetupSyncGet(documents, collection);
// Act
var result = Sut.GetOne<TestDocument, Guid>(condition);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.Once);
result.Should().NotBeNull();
result.Should().Be(documents[0]);
}
[Fact]
public void WithConditionAndCancellationToken_GetsMatchingDocuments()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var condition = Builders<TestDocument>.Filter.Eq("Id", documents[0].Id);
var token = new CancellationToken(true);
var (context, cursor) = SetupSyncGet(documents, collection);
// Act
var result = Sut.GetOne<TestDocument, Guid>(condition, cancellationToken: token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNext(token), Times.Once);
result.Should().NotBeNull();
result.Should().Be(documents[0]);
}
[Fact]
public void WithConditionAndPartitionKey_GetsMatchingDocuments()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var condition = Builders<TestDocument>.Filter.Eq("Id", documents[0].Id);
var partitionKey = Fixture.Create<string>();
var (context, cursor) = SetupSyncGet(documents, collection, partitionKey);
// Act
var result = Sut.GetOne<TestDocument, Guid>(condition, partitionKey: partitionKey);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
result.Should().NotBeNull();
result.Should().Be(documents[0]);
}
[Fact]
public void WithConditionAndPartitionKeyAndCancellationToken_GetsMatchingDocuments()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var condition = Builders<TestDocument>.Filter.Eq("Id", documents[0].Id);
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
var (context, cursor) = SetupSyncGet(documents, collection, partitionKey);
// Act
var result = Sut.GetOne<TestDocument, Guid>(condition, partitionKey: partitionKey, cancellationToken: token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNext(token), Times.Once);
result.Should().NotBeNull();
result.Should().Be(documents[0]);
}
[Fact]
public void WithConditionAndFindOptions_GetsMatchingDocuments()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var options = Fixture
.Build<FindOptions>()
.Without(x => x.Comment)
.Without(x => x.Hint)
.Create();
var condition = Builders<TestDocument>.Filter.Eq("Id", documents[0].Id);
var (context, cursor) = SetupSyncGet(documents, collection);
// Act
var result = Sut.GetOne<TestDocument, Guid>(condition, options);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.Once);
result.Should().NotBeNull();
result.Should().Be(documents[0]);
}
[Fact]
public void WithConditionAndFindOptionsAndCancellationToken_GetsMatchingDocuments()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var options = Fixture
.Build<FindOptions>()
.Without(x => x.Comment)
.Without(x => x.Hint)
.Create();
var condition = Builders<TestDocument>.Filter.Eq("Id", documents[0].Id);
var token = new CancellationToken(true);
var (context, cursor) = SetupSyncGet(documents, collection);
// Act
var result = Sut.GetOne<TestDocument, Guid>(condition, options, cancellationToken: token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNext(token), Times.Once);
result.Should().NotBeNull();
result.Should().Be(documents[0]);
}
[Fact]
public void WithConditionAndFindOptionsAndPartitionKeyAndCancellationToken_GetsMatchingDocuments()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var documents = Fixture.CreateMany<TestDocument>().ToList();
var options = Fixture
.Build<FindOptions>()
.Without(x => x.Comment)
.Without(x => x.Hint)
.Create();
var condition = Builders<TestDocument>.Filter.Eq("Id", documents[0].Id);
var token = new CancellationToken(true);
var partitionKey = Fixture.Create<string>();
var (context, cursor) = SetupSyncGet(documents, collection, partitionKey);
// Act
var result = Sut.GetOne<TestDocument, Guid>(condition, options, partitionKey, token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNext(token), Times.Once);
result.Should().NotBeNull();
result.Should().Be(documents[0]);
}
private (Mock<IMongoDbContext>, Mock<IAsyncCursor<TDocument>>) SetupSyncGet<TDocument>(
List<TDocument> documents,
Mock<IMongoCollection<TDocument>> collection,
string partitionKey = null)
{
var asyncCursor = SetupSyncCursor(documents);
SetupFindSync(collection, asyncCursor);
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TDocument>(partitionKey))
.Returns(collection.Object);
return (context, asyncCursor);
}
}
@@ -0,0 +1,123 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using AutoFixture;
using CoreUnitTests.Infrastructure.Model;
using FluentAssertions;
using MongoDB.Driver;
using MongoDbGenericRepository;
using Moq;
using Xunit;
namespace CoreUnitTests.DataAccessTests.MongoDbReaderTests;
public class ProjectManyAsyncTests : BaseReaderTests
{
private readonly Expression<Func<TestDocument, bool>> filter = t => string.IsNullOrWhiteSpace(t.SomeContent2);
private readonly Expression<Func<TestDocument, TestProjection>>
projectionExpression = t => new TestProjection {TestDocumentId = t.Id, NestedData = t.Nested.SomeDate};
[Fact]
public async Task WithFilterAndProjection_Projects()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var projections = Fixture.CreateMany<TestProjection>().ToList();
var (context, cursor) = SetupAsyncProjection(projections, collection);
// Act
var result = await Sut.ProjectManyAsync<TestDocument, TestProjection, Guid>(filter, projectionExpression);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.AtLeast(1));
result.Should().NotBeNull();
result.Should().OnlyContain(x => projections.Contains(x));
}
[Fact]
public async Task WithFilterAndProjectionAndCancellationToken_Projects()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var projections = Fixture.CreateMany<TestProjection>().ToList();
var token = new CancellationToken(false);
var (context, cursor) = SetupAsyncProjection(projections, collection);
// Act
var result = await Sut.ProjectManyAsync<TestDocument, TestProjection, Guid>(filter, projectionExpression, cancellationToken: token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.MoveNextAsync(token), Times.AtLeast(1));
result.Should().NotBeNull();
result.Should().OnlyContain(x => projections.Contains(x));
}
[Fact]
public async Task WithFilterAndProjectionAndPartitionKey_Projects()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var projections = Fixture.CreateMany<TestProjection>().ToList();
var partitionKey = Fixture.Create<string>();
var (context, cursor) = SetupAsyncProjection(projections, collection, partitionKey);
// Act
var result = await Sut.ProjectManyAsync<TestDocument, TestProjection, Guid>(filter, projectionExpression, partitionKey);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.AtLeast(1));
result.Should().NotBeNull();
result.Should().OnlyContain(x => projections.Contains(x));
}
[Fact]
public async Task WithFilterAndProjectionAndPartitionKeyAndCancellationToken_Projects()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var projections = Fixture.CreateMany<TestProjection>().ToList();
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(false);
var (context, cursor) = SetupAsyncProjection(projections, collection, partitionKey);
// Act
var result = await Sut.ProjectManyAsync<TestDocument, TestProjection, Guid>(filter, projectionExpression, partitionKey, token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.MoveNextAsync(token), Times.AtLeast(1));
result.Should().NotBeNull();
result.Should().OnlyContain(x => projections.Contains(x));
}
private (Mock<IMongoDbContext>, Mock<IAsyncCursor<TProjection>>) SetupAsyncProjection<TDocument, TProjection>(
List<TProjection> projections,
Mock<IMongoCollection<TDocument>> collection,
string partitionKey = null)
{
var asyncCursor = SetupAsyncCursor(projections);
collection
.Setup(
x => x.FindAsync(
It.IsAny<FilterDefinition<TDocument>>(),
It.IsAny<FindOptions<TDocument, TProjection>>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(asyncCursor.Object);
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TDocument>(partitionKey))
.Returns(collection.Object);
return (context, asyncCursor);
}
}
@@ -0,0 +1,117 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using AutoFixture;
using CoreUnitTests.Infrastructure.Model;
using FluentAssertions;
using MongoDB.Driver;
using MongoDbGenericRepository;
using Moq;
using Xunit;
namespace CoreUnitTests.DataAccessTests.MongoDbReaderTests;
public class ProjectManyTests : BaseReaderTests
{
private readonly Expression<Func<TestDocument, bool>> filter = t => string.IsNullOrWhiteSpace(t.SomeContent2);
private readonly Expression<Func<TestDocument, TestProjection>>
projectionExpression = t => new TestProjection {TestDocumentId = t.Id, NestedData = t.Nested.SomeDate};
[Fact]
public void WithFilterAndProjection_Projects()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var projections = Fixture.CreateMany<TestProjection>().ToList();
var (context, cursor) = SetupAsyncProjection(projections, collection);
// Act
var result = Sut.ProjectMany<TestDocument, TestProjection, Guid>(filter, projectionExpression);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.AtLeast(1));
result.Should().NotBeNull();
result.Should().OnlyContain(x => projections.Contains(x));
}
[Fact]
public void WithFilterAndProjectionAndCancellationToken_Projects()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var projections = Fixture.CreateMany<TestProjection>().ToList();
var token = new CancellationToken(false);
var (context, cursor) = SetupAsyncProjection(projections, collection);
// Act
var result = Sut.ProjectMany<TestDocument, TestProjection, Guid>(filter, projectionExpression, cancellationToken: token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.MoveNext(token), Times.AtLeast(1));
result.Should().NotBeNull();
result.Should().OnlyContain(x => projections.Contains(x));
}
[Fact]
public void WithFilterAndProjectionAndPartitionKey_Projects()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var projections = Fixture.CreateMany<TestProjection>().ToList();
var partitionKey = Fixture.Create<string>();
var (context, cursor) = SetupAsyncProjection(projections, collection, partitionKey);
// Act
var result = Sut.ProjectMany<TestDocument, TestProjection, Guid>(filter, projectionExpression, partitionKey);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.AtLeast(1));
result.Should().NotBeNull();
result.Should().OnlyContain(x => projections.Contains(x));
}
[Fact]
public void WithFilterAndProjectionAndPartitionKeyAndCancellationToken_Projects()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var projections = Fixture.CreateMany<TestProjection>().ToList();
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(false);
var (context, cursor) = SetupAsyncProjection(projections, collection, partitionKey);
// Act
var result = Sut.ProjectMany<TestDocument, TestProjection, Guid>(filter, projectionExpression, partitionKey, token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.MoveNext(token), Times.AtLeast(projections.Count));
result.Should().NotBeNull();
result.Should().OnlyContain(x => projections.Contains(x));
}
private (Mock<IMongoDbContext>, Mock<IAsyncCursor<TProjection>>) SetupAsyncProjection<TDocument, TProjection>(
List<TProjection> projections,
Mock<IMongoCollection<TDocument>> collection,
string partitionKey = null)
{
var asyncCursor = SetupSyncCursor(projections);
SetupFindSync(collection, asyncCursor);
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TDocument>(partitionKey))
.Returns(collection.Object);
return (context, asyncCursor);
}
}
@@ -0,0 +1,121 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using AutoFixture;
using CoreUnitTests.Infrastructure.Model;
using FluentAssertions;
using MongoDB.Driver;
using MongoDbGenericRepository;
using Moq;
using Xunit;
namespace CoreUnitTests.DataAccessTests.MongoDbReaderTests;
public class ProjectOneAsyncTests : BaseReaderTests
{
private readonly Expression<Func<TestDocument, bool>> filter = t => string.IsNullOrWhiteSpace(t.SomeContent2);
private readonly Expression<Func<TestDocument, TestProjection>>
projectionExpression = t => new TestProjection {TestDocumentId = t.Id, NestedData = t.Nested.SomeDate};
[Fact]
public async Task WithFilterAndProjection_Projects()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var projections = Fixture.CreateMany<TestProjection>().ToList();
var (context, cursor) = SetupAsyncProjection(projections, collection);
// Act
var result = await Sut.ProjectOneAsync<TestDocument, TestProjection, Guid>(filter, projectionExpression);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.Once);
result.Should().NotBeNull();
result.Should().Be(projections[0]);
}
[Fact]
public async Task WithFilterAndProjectionAndCancellationToken_Projects()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var projections = Fixture.CreateMany<TestProjection>().ToList();
var token = new CancellationToken(true);
var (context, cursor) = SetupAsyncProjection(projections, collection);
// Act
var result = await Sut.ProjectOneAsync<TestDocument, TestProjection, Guid>(filter, projectionExpression, cancellationToken: token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNextAsync(token), Times.Once);
result.Should().NotBeNull();
result.Should().Be(projections[0]);
}
[Fact]
public async Task WithFilterAndProjectionAndPartitionKey_Projects()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var projections = Fixture.CreateMany<TestProjection>().ToList();
var partitionKey = Fixture.Create<string>();
var (context, cursor) = SetupAsyncProjection(projections, collection, partitionKey);
// Act
var result = await Sut.ProjectOneAsync<TestDocument, TestProjection, Guid>(filter, projectionExpression, partitionKey);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNextAsync(CancellationToken.None), Times.Once);
result.Should().NotBeNull();
result.Should().Be(projections[0]);
}
[Fact]
public async Task WithFilterAndProjectionAndPartitionKeyAndCancellationToken_Projects()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var projections = Fixture.CreateMany<TestProjection>().ToList();
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
var (context, cursor) = SetupAsyncProjection(projections, collection, partitionKey);
// Act
var result = await Sut.ProjectOneAsync<TestDocument, TestProjection, Guid>(filter, projectionExpression, partitionKey, token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNextAsync(token), Times.Once);
result.Should().NotBeNull();
result.Should().Be(projections[0]);
}
private (Mock<IMongoDbContext>, Mock<IAsyncCursor<TProjection>>) SetupAsyncProjection<TDocument, TProjection>(
List<TProjection> projections,
Mock<IMongoCollection<TDocument>> collection,
string partitionKey = null)
{
var asyncCursor = SetupAsyncCursor(projections);
SetupFindAsync(collection, asyncCursor);
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TDocument>(partitionKey))
.Returns(collection.Object);
return (context, asyncCursor);
}
}
@@ -0,0 +1,121 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using AutoFixture;
using CoreUnitTests.Infrastructure.Model;
using FluentAssertions;
using MongoDB.Driver;
using MongoDbGenericRepository;
using Moq;
using Xunit;
namespace CoreUnitTests.DataAccessTests.MongoDbReaderTests;
public class ProjectOneTests : BaseReaderTests
{
private readonly Expression<Func<TestDocument, bool>> filter = t => string.IsNullOrWhiteSpace(t.SomeContent2);
private readonly Expression<Func<TestDocument, TestProjection>>
projectionExpression = t => new TestProjection {TestDocumentId = t.Id, NestedData = t.Nested.SomeDate};
[Fact]
public void WithFilterAndProjection_Projects()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var projections = Fixture.CreateMany<TestProjection>().ToList();
var (context, cursor) = SetupProjection(projections, collection);
// Act
var result = Sut.ProjectOne<TestDocument, TestProjection, Guid>(filter, projectionExpression);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.Once);
result.Should().NotBeNull();
result.Should().Be(projections[0]);
}
[Fact]
public void WithFilterAndProjectionAndCancellationToken_Projects()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var projections = Fixture.CreateMany<TestProjection>().ToList();
var token = new CancellationToken(true);
var (context, cursor) = SetupProjection(projections, collection);
// Act
var result = Sut.ProjectOne<TestDocument, TestProjection, Guid>(filter, projectionExpression, cancellationToken: token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(null), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNext(token), Times.Once);
result.Should().NotBeNull();
result.Should().Be(projections[0]);
}
[Fact]
public void WithFilterAndProjectionAndPartitionKey_Projects()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var projections = Fixture.CreateMany<TestProjection>().ToList();
var partitionKey = Fixture.Create<string>();
var (context, cursor) = SetupProjection(projections, collection, partitionKey);
// Act
var result = Sut.ProjectOne<TestDocument, TestProjection, Guid>(filter, projectionExpression, partitionKey);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNext(CancellationToken.None), Times.Once);
result.Should().NotBeNull();
result.Should().Be(projections[0]);
}
[Fact]
public void WithFilterAndProjectionAndPartitionKeyAndCancellationToken_Projects()
{
// Arrange
var collection = MockOf<IMongoCollection<TestDocument>>();
var projections = Fixture.CreateMany<TestProjection>().ToList();
var partitionKey = Fixture.Create<string>();
var token = new CancellationToken(true);
var (context, cursor) = SetupProjection(projections, collection, partitionKey);
// Act
var result = Sut.ProjectOne<TestDocument, TestProjection, Guid>(filter, projectionExpression, partitionKey, token);
// Assert
context.Verify(x => x.GetCollection<TestDocument>(partitionKey), Times.Once);
cursor.Verify(x => x.Current, Times.Once);
cursor.Verify(x => x.MoveNext(token), Times.Once);
result.Should().NotBeNull();
result.Should().Be(projections[0]);
}
private (Mock<IMongoDbContext>, Mock<IAsyncCursor<TProjection>>) SetupProjection<TDocument, TProjection>(
List<TProjection> projections,
Mock<IMongoCollection<TDocument>> collection,
string partitionKey = null)
{
var asyncCursor = SetupSyncCursor(projections);
SetupFindSync(collection, asyncCursor);
var context = MockOf<IMongoDbContext>();
context
.Setup(x => x.GetCollection<TDocument>(partitionKey))
.Returns(collection.Object);
return (context, asyncCursor);
}
}
@@ -0,0 +1,582 @@
using System;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using AutoFixture;
using CoreUnitTests.Infrastructure;
using CoreUnitTests.Infrastructure.Model;
using FluentAssertions;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDbGenericRepository;
using MongoDbGenericRepository.DataAccess.Update;
using Moq;
using Xunit;
namespace CoreUnitTests.DataAccessTests.MongoDbUpdaterTests;
public class UpdateManyAsyncTests : GenericTestContext<MongoDbUpdater>
{
[Fact]
public async Task WithFilterAndUpdateDefinition_UpdatesMany()
{
// Arrange
var count = Fixture.Create<long>();
var value = Fixture.Create<string>();
var updateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
var collection = SetupCollection(count);
var filter = Builders<TestDocument>.Filter.Eq(x => x.SomeContent, "SomeContent");
// Act
var result = await Sut.UpdateManyAsync<TestDocument, Guid>(
filter,
updateDefinition);
// Assert
result.Should().Be(count);
collection
.Verify(
x => x.UpdateManyAsync(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(filter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(updateDefinition)),
null,
CancellationToken.None),
Times.Once());
}
[Fact]
public async Task WithFilterAndUpdateDefinitionAndCancellationToken_UpdatesMany()
{
// Arrange
var count = Fixture.Create<long>();
var value = Fixture.Create<string>();
var updateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
var collection = SetupCollection(count);
var filter = Builders<TestDocument>.Filter.Eq(x => x.SomeContent, "SomeContent");
var token = new CancellationToken(true);
// Act
var result = await Sut.UpdateManyAsync<TestDocument, Guid>(
filter,
updateDefinition,
cancellationToken: token);
// Assert
result.Should().Be(count);
collection
.Verify(
x => x.UpdateManyAsync(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(filter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(updateDefinition)),
null,
token),
Times.Once());
}
[Fact]
public async Task WithFilterAndUpdateDefinitionAndPartitionKey_UpdatesMany()
{
// Arrange
var count = Fixture.Create<long>();
var value = Fixture.Create<string>();
var partitionKey = Fixture.Create<string>();
var updateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
var collection = SetupCollection(count, partitionKey);
var filter = Builders<TestDocument>.Filter.Eq(x => x.SomeContent, "SomeContent");
// Act
var result = await Sut.UpdateManyAsync<TestDocument, Guid>(
filter,
updateDefinition,
partitionKey);
// Assert
result.Should().Be(count);
collection
.Verify(
x => x.UpdateManyAsync(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(filter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(updateDefinition)),
null,
CancellationToken.None),
Times.Once());
}
[Fact]
public async Task WithFilterAndUpdateDefinitionAndPartitionKeyAndCancellationToken_UpdatesMany()
{
// Arrange
var count = Fixture.Create<long>();
var value = Fixture.Create<string>();
var partitionKey = Fixture.Create<string>();
var updateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
var collection = SetupCollection(count, partitionKey);
var filter = Builders<TestDocument>.Filter.Eq(x => x.SomeContent, "SomeContent");
var token = new CancellationToken(true);
// Act
var result = await Sut.UpdateManyAsync<TestDocument, Guid>(
filter,
updateDefinition,
partitionKey,
cancellationToken: token);
// Assert
result.Should().Be(count);
collection
.Verify(
x => x.UpdateManyAsync(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(filter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(updateDefinition)),
null,
token),
Times.Once());
}
[Fact]
public async Task WithFilterAndFieldExpressionAndValue_UpdatesMany()
{
// Arrange
var count = Fixture.Create<long>();
var value = Fixture.Create<string>();
var collection = SetupCollection(count);
var filter = Builders<TestDocument>.Filter.Eq(x => x.SomeContent, "SomeContent");
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = await Sut.UpdateManyAsync<TestDocument, Guid, string>(
filter,
fieldExpression,
value);
// Assert
result.Should().Be(count);
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
collection
.Verify(
x => x.UpdateManyAsync(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(filter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
CancellationToken.None),
Times.Once());
}
[Fact]
public async Task WithFilterAndFieldExpressionAndValueAndPartitionKey_UpdatesMany()
{
// Arrange
var count = Fixture.Create<long>();
var value = Fixture.Create<string>();
var partitionKey = Fixture.Create<string>();
var collection = SetupCollection(count, partitionKey);
var filter = Builders<TestDocument>.Filter.Eq(x => x.SomeContent, "SomeContent");
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = await Sut.UpdateManyAsync<TestDocument, Guid, string>(
filter,
fieldExpression,
value,
partitionKey);
// Assert
result.Should().Be(count);
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
collection
.Verify(
x => x.UpdateManyAsync(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(filter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
CancellationToken.None),
Times.Once());
}
[Fact]
public async Task WithFilterAndFieldExpressionAndValueAndCancellationToken_UpdatesMany()
{
// Arrange
var count = Fixture.Create<long>();
var value = Fixture.Create<string>();
var collection = SetupCollection(count);
var token = new CancellationToken(true);
var filter = Builders<TestDocument>.Filter.Eq(x => x.SomeContent, "SomeContent");
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = await Sut.UpdateManyAsync<TestDocument, Guid, string>(
filter,
fieldExpression,
value,
cancellationToken: token);
// Assert
result.Should().Be(count);
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
collection
.Verify(
x => x.UpdateManyAsync(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(filter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
token),
Times.Once());
}
[Fact]
public async Task WithFilterAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_UpdatesMany()
{
// Arrange
var count = Fixture.Create<long>();
var value = Fixture.Create<string>();
var partitionKey = Fixture.Create<string>();
var collection = SetupCollection(count, partitionKey);
var token = new CancellationToken(true);
var filter = Builders<TestDocument>.Filter.Eq(x => x.SomeContent, "SomeContent");
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = await Sut.UpdateManyAsync<TestDocument, Guid, string>(
filter,
fieldExpression,
value,
partitionKey,
token);
// Assert
result.Should().Be(count);
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
collection
.Verify(
x => x.UpdateManyAsync(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(filter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
token),
Times.Once());
}
[Fact]
public async Task WithFilterExpressionAndFieldExpressionAndValue_UpdatesMany()
{
// Arrange
var count = Fixture.Create<long>();
var value = Fixture.Create<string>();
var collection = SetupCollection(count);
Expression<Func<TestDocument, bool>> filterExpression = testDocument => testDocument.SomeContent == "SomeContent";
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = await Sut.UpdateManyAsync<TestDocument, Guid, string>(
filterExpression,
fieldExpression,
value);
// Assert
result.Should().Be(count);
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
var expectedFilter = Builders<TestDocument>.Filter.Where(filterExpression);
collection
.Verify(
x => x.UpdateManyAsync(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
CancellationToken.None),
Times.Once());
}
[Fact]
public async Task WithFilterExpressionAndFieldExpressionAndValueAndCancellationToken_UpdatesMany()
{
// Arrange
var count = Fixture.Create<long>();
var value = Fixture.Create<string>();
var collection = SetupCollection(count);
var token = new CancellationToken(true);
Expression<Func<TestDocument, bool>> filterExpression = testDocument => testDocument.SomeContent == "SomeContent";
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = await Sut.UpdateManyAsync<TestDocument, Guid, string>(
filterExpression,
fieldExpression,
value,
cancellationToken: token);
// Assert
result.Should().Be(count);
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
var expectedFilter = Builders<TestDocument>.Filter.Where(filterExpression);
collection
.Verify(
x => x.UpdateManyAsync(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
token),
Times.Once());
}
[Fact]
public async Task WithFilterExpressionAndFieldExpressionAndValueAndPartitionKey_UpdatesMany()
{
// Arrange
var value = Fixture.Create<string>();
var partitionKey = Fixture.Create<string>();
var count = Fixture.Create<long>();
var collection = SetupCollection(count, partitionKey);
Expression<Func<TestDocument, bool>> filterExpression = testDocument => testDocument.SomeContent == "SomeContent";
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = await Sut.UpdateManyAsync<TestDocument, Guid, string>(
filterExpression,
fieldExpression,
value,
partitionKey);
// Assert
result.Should().Be(count);
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
var expectedFilter = Builders<TestDocument>.Filter.Where(filterExpression);
collection
.Verify(
x => x.UpdateManyAsync(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
CancellationToken.None),
Times.Once());
}
[Fact]
public async Task WithFilterExpressionAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_UpdatesMany()
{
// Arrange
var value = Fixture.Create<string>();
var count = Fixture.Create<long>();
var partitionKey = Fixture.Create<string>();
var collection = SetupCollection(count, partitionKey);
var token = new CancellationToken(true);
Expression<Func<TestDocument, bool>> filterExpression = testDocument => testDocument.SomeContent == "SomeContent";
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = await Sut.UpdateManyAsync<TestDocument, Guid, string>(
filterExpression,
fieldExpression,
value,
partitionKey,
token);
// Assert
result.Should().Be(count);
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
var expectedFilter = Builders<TestDocument>.Filter.Where(filterExpression);
collection
.Verify(
x => x.UpdateManyAsync(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
token),
Times.Once());
}
[Fact]
public async Task WithFilterExpressionAndUpdateDefinition_UpdatesMany()
{
// Arrange
var count = Fixture.Create<long>();
var value = Fixture.Create<string>();
var updateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
var collection = SetupCollection(count);
Expression<Func<TestDocument, bool>> filterExpression = testDocument => testDocument.SomeContent == "SomeContent";
// Act
var result = await Sut.UpdateManyAsync<TestDocument, Guid>(
filterExpression,
updateDefinition);
// Assert
result.Should().Be(count);
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
var expectedFilter = Builders<TestDocument>.Filter.Where(filterExpression);
collection
.Verify(
x => x.UpdateManyAsync(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
CancellationToken.None),
Times.Once());
}
[Fact]
public async Task WithFilterExpressionAndUpdateDefinitionAndCancellationToken_UpdatesMany()
{
// Arrange
var count = Fixture.Create<long>();
var value = Fixture.Create<string>();
var updateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
var collection = SetupCollection(count);
var token = new CancellationToken(true);
Expression<Func<TestDocument, bool>> filterExpression = testDocument => testDocument.SomeContent == "SomeContent";
// Act
var result = await Sut.UpdateManyAsync<TestDocument, Guid>(
filterExpression,
updateDefinition,
cancellationToken: token);
// Assert
result.Should().Be(count);
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
var expectedFilter = Builders<TestDocument>.Filter.Where(filterExpression);
collection
.Verify(
x => x.UpdateManyAsync(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
token),
Times.Once());
}
[Fact]
public async Task WithFilterExpressionAndUpdateDefinitionAndPartitionKey_UpdatesMany()
{
// Arrange
var value = Fixture.Create<string>();
var partitionKey = Fixture.Create<string>();
var updateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
var count = Fixture.Create<long>();
var collection = SetupCollection(count, partitionKey);
Expression<Func<TestDocument, bool>> filterExpression = testDocument => testDocument.SomeContent == "SomeContent";
// Act
var result = await Sut.UpdateManyAsync<TestDocument, Guid>(
filterExpression,
updateDefinition,
partitionKey);
// Assert
result.Should().Be(count);
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
var expectedFilter = Builders<TestDocument>.Filter.Where(filterExpression);
collection
.Verify(
x => x.UpdateManyAsync(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
CancellationToken.None),
Times.Once());
}
[Fact]
public async Task WithFilterExpressionAndUpdateDefinitionAndPartitionKeyAndCancellationToken_UpdatesMany()
{
// Arrange
var value = Fixture.Create<string>();
var count = Fixture.Create<long>();
var updateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
var partitionKey = Fixture.Create<string>();
var collection = SetupCollection(count, partitionKey);
var token = new CancellationToken(true);
Expression<Func<TestDocument, bool>> filterExpression = testDocument => testDocument.SomeContent == "SomeContent";
// Act
var result = await Sut.UpdateManyAsync<TestDocument, Guid>(
filterExpression,
updateDefinition,
partitionKey,
token);
// Assert
result.Should().Be(count);
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
var expectedFilter = Builders<TestDocument>.Filter.Where(filterExpression);
collection
.Verify(
x => x.UpdateManyAsync(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
token),
Times.Once());
}
private Mock<IMongoCollection<TestDocument>> SetupCollection(long count, string partitionKey = null)
{
var replacedId = Fixture.Create<Guid>();
var replaceResult = new ReplaceOneResult.Acknowledged(count, count, new BsonBinaryData(replacedId, GuidRepresentation.Standard));
var updateResult = new UpdateResult.Acknowledged(count, count, new BsonBinaryData(replacedId, GuidRepresentation.Standard));
var collection = MockOf<IMongoCollection<TestDocument>>();
collection
.Setup(
x => x.ReplaceOneAsync(
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<TestDocument>(),
It.IsAny<ReplaceOptions>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(replaceResult);
collection
.Setup(
x => x.UpdateManyAsync(
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<UpdateDefinition<TestDocument>>(),
It.IsAny<UpdateOptions>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(updateResult);
collection
.Setup(
x => x.ReplaceOneAsync(
It.IsAny<IClientSessionHandle>(),
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<TestDocument>(),
It.IsAny<ReplaceOptions>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(replaceResult);
collection
.Setup(
x => x.UpdateManyAsync(
It.IsAny<IClientSessionHandle>(),
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<UpdateDefinition<TestDocument>>(),
It.IsAny<UpdateOptions>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(updateResult);
var dbContext = MockOf<IMongoDbContext>();
dbContext
.Setup(x => x.GetCollection<TestDocument>(partitionKey))
.Returns(collection.Object);
return collection;
}
}
@@ -0,0 +1,581 @@
using System;
using System.Linq.Expressions;
using System.Threading;
using AutoFixture;
using CoreUnitTests.Infrastructure;
using CoreUnitTests.Infrastructure.Model;
using FluentAssertions;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDbGenericRepository;
using MongoDbGenericRepository.DataAccess.Update;
using Moq;
using Xunit;
namespace CoreUnitTests.DataAccessTests.MongoDbUpdaterTests;
public class UpdateManyTests : GenericTestContext<MongoDbUpdater>
{
[Fact]
public void WithFilterAndUpdateDefinition_UpdatesMany()
{
// Arrange
var count = Fixture.Create<long>();
var value = Fixture.Create<string>();
var updateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
var collection = SetupCollection(count);
var filter = Builders<TestDocument>.Filter.Eq(x => x.SomeContent, "SomeContent");
// Act
var result = Sut.UpdateMany<TestDocument, Guid>(
filter,
updateDefinition);
// Assert
result.Should().Be(count);
collection
.Verify(
x => x.UpdateMany(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(filter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(updateDefinition)),
null,
CancellationToken.None),
Times.Once());
}
[Fact]
public void WithFilterAndUpdateDefinitionAndCancellationToken_UpdatesMany()
{
// Arrange
var count = Fixture.Create<long>();
var value = Fixture.Create<string>();
var updateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
var collection = SetupCollection(count);
var filter = Builders<TestDocument>.Filter.Eq(x => x.SomeContent, "SomeContent");
var token = new CancellationToken(true);
// Act
var result = Sut.UpdateMany<TestDocument, Guid>(
filter,
updateDefinition,
cancellationToken: token);
// Assert
result.Should().Be(count);
collection
.Verify(
x => x.UpdateMany(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(filter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(updateDefinition)),
null,
token),
Times.Once());
}
[Fact]
public void WithFilterAndUpdateDefinitionAndPartitionKey_UpdatesMany()
{
// Arrange
var count = Fixture.Create<long>();
var value = Fixture.Create<string>();
var partitionKey = Fixture.Create<string>();
var updateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
var collection = SetupCollection(count, partitionKey);
var filter = Builders<TestDocument>.Filter.Eq(x => x.SomeContent, "SomeContent");
// Act
var result = Sut.UpdateMany<TestDocument, Guid>(
filter,
updateDefinition,
partitionKey);
// Assert
result.Should().Be(count);
collection
.Verify(
x => x.UpdateMany(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(filter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(updateDefinition)),
null,
CancellationToken.None),
Times.Once());
}
[Fact]
public void WithFilterAndUpdateDefinitionAndPartitionKeyAndCancellationToken_UpdatesMany()
{
// Arrange
var count = Fixture.Create<long>();
var value = Fixture.Create<string>();
var partitionKey = Fixture.Create<string>();
var updateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
var collection = SetupCollection(count, partitionKey);
var filter = Builders<TestDocument>.Filter.Eq(x => x.SomeContent, "SomeContent");
var token = new CancellationToken(true);
// Act
var result = Sut.UpdateMany<TestDocument, Guid>(
filter,
updateDefinition,
partitionKey,
token);
// Assert
result.Should().Be(count);
collection
.Verify(
x => x.UpdateMany(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(filter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(updateDefinition)),
null,
token),
Times.Once());
}
[Fact]
public void WithFilterAndFieldExpressionAndValue_UpdatesMany()
{
// Arrange
var count = Fixture.Create<long>();
var value = Fixture.Create<string>();
var collection = SetupCollection(count);
var filter = Builders<TestDocument>.Filter.Eq(x => x.SomeContent, "SomeContent");
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = Sut.UpdateMany<TestDocument, Guid, string>(
filter,
fieldExpression,
value);
// Assert
result.Should().Be(count);
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
collection
.Verify(
x => x.UpdateMany(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(filter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
CancellationToken.None),
Times.Once());
}
[Fact]
public void WithFilterAndFieldExpressionAndValueAndPartitionKey_UpdatesMany()
{
// Arrange
var count = Fixture.Create<long>();
var value = Fixture.Create<string>();
var partitionKey = Fixture.Create<string>();
var collection = SetupCollection(count, partitionKey);
var filter = Builders<TestDocument>.Filter.Eq(x => x.SomeContent, "SomeContent");
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = Sut.UpdateMany<TestDocument, Guid, string>(
filter,
fieldExpression,
value,
partitionKey);
// Assert
result.Should().Be(count);
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
collection
.Verify(
x => x.UpdateMany(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(filter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
CancellationToken.None),
Times.Once());
}
[Fact]
public void WithFilterAndFieldExpressionAndValueAndCancellationToken_UpdatesMany()
{
// Arrange
var count = Fixture.Create<long>();
var value = Fixture.Create<string>();
var collection = SetupCollection(count);
var token = new CancellationToken(true);
var filter = Builders<TestDocument>.Filter.Eq(x => x.SomeContent, "SomeContent");
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = Sut.UpdateMany<TestDocument, Guid, string>(
filter,
fieldExpression,
value,
cancellationToken: token);
// Assert
result.Should().Be(count);
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
collection
.Verify(
x => x.UpdateMany(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(filter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
token),
Times.Once());
}
[Fact]
public void WithFilterAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_UpdatesMany()
{
// Arrange
var count = Fixture.Create<long>();
var value = Fixture.Create<string>();
var partitionKey = Fixture.Create<string>();
var collection = SetupCollection(count, partitionKey);
var token = new CancellationToken(true);
var filter = Builders<TestDocument>.Filter.Eq(x => x.SomeContent, "SomeContent");
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = Sut.UpdateMany<TestDocument, Guid, string>(
filter,
fieldExpression,
value,
partitionKey,
token);
// Assert
result.Should().Be(count);
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
collection
.Verify(
x => x.UpdateMany(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(filter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
token),
Times.Once());
}
[Fact]
public void WithFilterExpressionAndFieldExpressionAndValue_UpdatesMany()
{
// Arrange
var count = Fixture.Create<long>();
var value = Fixture.Create<string>();
var collection = SetupCollection(count);
Expression<Func<TestDocument, bool>> filterExpression = testDocument => testDocument.SomeContent == "SomeContent";
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = Sut.UpdateMany<TestDocument, Guid, string>(
filterExpression,
fieldExpression,
value);
// Assert
result.Should().Be(count);
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
var expectedFilter = Builders<TestDocument>.Filter.Where(filterExpression);
collection
.Verify(
x => x.UpdateMany(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
CancellationToken.None),
Times.Once());
}
[Fact]
public void WithFilterExpressionAndFieldExpressionAndValueAndCancellationToken_UpdatesMany()
{
// Arrange
var count = Fixture.Create<long>();
var value = Fixture.Create<string>();
var collection = SetupCollection(count);
var token = new CancellationToken(true);
Expression<Func<TestDocument, bool>> filterExpression = testDocument => testDocument.SomeContent == "SomeContent";
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = Sut.UpdateMany<TestDocument, Guid, string>(
filterExpression,
fieldExpression,
value,
cancellationToken: token);
// Assert
result.Should().Be(count);
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
var expectedFilter = Builders<TestDocument>.Filter.Where(filterExpression);
collection
.Verify(
x => x.UpdateMany(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
token),
Times.Once());
}
[Fact]
public void WithFilterExpressionAndFieldExpressionAndValueAndPartitionKey_UpdatesMany()
{
// Arrange
var value = Fixture.Create<string>();
var partitionKey = Fixture.Create<string>();
var count = Fixture.Create<long>();
var collection = SetupCollection(count, partitionKey);
Expression<Func<TestDocument, bool>> filterExpression = testDocument => testDocument.SomeContent == "SomeContent";
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = Sut.UpdateMany<TestDocument, Guid, string>(
filterExpression,
fieldExpression,
value,
partitionKey);
// Assert
result.Should().Be(count);
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
var expectedFilter = Builders<TestDocument>.Filter.Where(filterExpression);
collection
.Verify(
x => x.UpdateMany(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
CancellationToken.None),
Times.Once());
}
[Fact]
public void WithFilterExpressionAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_UpdatesMany()
{
// Arrange
var value = Fixture.Create<string>();
var count = Fixture.Create<long>();
var partitionKey = Fixture.Create<string>();
var collection = SetupCollection(count, partitionKey);
var token = new CancellationToken(true);
Expression<Func<TestDocument, bool>> filterExpression = testDocument => testDocument.SomeContent == "SomeContent";
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = Sut.UpdateMany<TestDocument, Guid, string>(
filterExpression,
fieldExpression,
value,
partitionKey,
token);
// Assert
result.Should().Be(count);
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
var expectedFilter = Builders<TestDocument>.Filter.Where(filterExpression);
collection
.Verify(
x => x.UpdateMany(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
token),
Times.Once());
}
[Fact]
public void WithFilterExpressionAndUpdateDefinition_UpdatesMany()
{
// Arrange
var count = Fixture.Create<long>();
var value = Fixture.Create<string>();
var updateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
var collection = SetupCollection(count);
Expression<Func<TestDocument, bool>> filterExpression = testDocument => testDocument.SomeContent == "SomeContent";
// Act
var result = Sut.UpdateMany<TestDocument, Guid>(
filterExpression,
updateDefinition);
// Assert
result.Should().Be(count);
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
var expectedFilter = Builders<TestDocument>.Filter.Where(filterExpression);
collection
.Verify(
x => x.UpdateMany(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
CancellationToken.None),
Times.Once());
}
[Fact]
public void WithFilterExpressionAndUpdateDefinitionAndCancellationToken_UpdatesMany()
{
// Arrange
var count = Fixture.Create<long>();
var value = Fixture.Create<string>();
var updateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
var collection = SetupCollection(count);
var token = new CancellationToken(true);
Expression<Func<TestDocument, bool>> filterExpression = testDocument => testDocument.SomeContent == "SomeContent";
// Act
var result = Sut.UpdateMany<TestDocument, Guid>(
filterExpression,
updateDefinition,
cancellationToken: token);
// Assert
result.Should().Be(count);
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
var expectedFilter = Builders<TestDocument>.Filter.Where(filterExpression);
collection
.Verify(
x => x.UpdateMany(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
token),
Times.Once());
}
[Fact]
public void WithFilterExpressionAndUpdateDefinitionAndPartitionKey_UpdatesMany()
{
// Arrange
var value = Fixture.Create<string>();
var partitionKey = Fixture.Create<string>();
var updateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
var count = Fixture.Create<long>();
var collection = SetupCollection(count, partitionKey);
Expression<Func<TestDocument, bool>> filterExpression = testDocument => testDocument.SomeContent == "SomeContent";
// Act
var result = Sut.UpdateMany<TestDocument, Guid>(
filterExpression,
updateDefinition,
partitionKey);
// Assert
result.Should().Be(count);
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
var expectedFilter = Builders<TestDocument>.Filter.Where(filterExpression);
collection
.Verify(
x => x.UpdateMany(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
CancellationToken.None),
Times.Once());
}
[Fact]
public void WithFilterExpressionAndUpdateDefinitionAndPartitionKeyAndCancellationToken_UpdatesMany()
{
// Arrange
var value = Fixture.Create<string>();
var count = Fixture.Create<long>();
var updateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
var partitionKey = Fixture.Create<string>();
var collection = SetupCollection(count, partitionKey);
var token = new CancellationToken(true);
Expression<Func<TestDocument, bool>> filterExpression = testDocument => testDocument.SomeContent == "SomeContent";
// Act
var result = Sut.UpdateMany<TestDocument, Guid>(
filterExpression,
updateDefinition,
partitionKey,
token);
// Assert
result.Should().Be(count);
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
var expectedFilter = Builders<TestDocument>.Filter.Where(filterExpression);
collection
.Verify(
x => x.UpdateMany(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
token),
Times.Once());
}
private Mock<IMongoCollection<TestDocument>> SetupCollection(long count, string partitionKey = null)
{
var replacedId = Fixture.Create<Guid>();
var replaceResult = new ReplaceOneResult.Acknowledged(count, count, new BsonBinaryData(replacedId, GuidRepresentation.Standard));
var updateResult = new UpdateResult.Acknowledged(count, count, new BsonBinaryData(replacedId, GuidRepresentation.Standard));
var collection = MockOf<IMongoCollection<TestDocument>>();
collection
.Setup(
x => x.ReplaceOneAsync(
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<TestDocument>(),
It.IsAny<ReplaceOptions>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(replaceResult);
collection
.Setup(
x => x.UpdateMany(
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<UpdateDefinition<TestDocument>>(),
It.IsAny<UpdateOptions>(),
It.IsAny<CancellationToken>()))
.Returns(updateResult);
collection
.Setup(
x => x.ReplaceOneAsync(
It.IsAny<IClientSessionHandle>(),
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<TestDocument>(),
It.IsAny<ReplaceOptions>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(replaceResult);
collection
.Setup(
x => x.UpdateMany(
It.IsAny<IClientSessionHandle>(),
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<UpdateDefinition<TestDocument>>(),
It.IsAny<UpdateOptions>(),
It.IsAny<CancellationToken>()))
.Returns(updateResult);
var dbContext = MockOf<IMongoDbContext>();
dbContext
.Setup(x => x.GetCollection<TestDocument>(partitionKey))
.Returns(collection.Object);
return collection;
}
}
@@ -0,0 +1,806 @@
using System;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using AutoFixture;
using CoreUnitTests.Infrastructure;
using CoreUnitTests.Infrastructure.Model;
using FluentAssertions;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDbGenericRepository;
using MongoDbGenericRepository.DataAccess.Update;
using Moq;
using Xunit;
namespace CoreUnitTests.DataAccessTests.MongoDbUpdaterTests;
public class UpdateOneAsyncTests : GenericTestContext<MongoDbUpdater>
{
[Fact]
public async Task WithDocument_ReplacesOne()
{
// Arrange
var document = Fixture.Create<TestDocument>();
var collection = SetupCollection();
// Act
var result = await Sut.UpdateOneAsync<TestDocument, Guid>(document);
// Assert
result.Should().BeTrue();
var expectedFilter = Builders<TestDocument>.Filter.Eq("Id", document.Id);
ReplaceOptions expectedOptions = null;
collection
.Verify(
x => x.ReplaceOneAsync(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
document,
expectedOptions,
CancellationToken.None),
Times.Once());
}
[Fact]
public async Task WithDocumentAndCancellationToken_ReplacesOne()
{
// Arrange
var document = Fixture.Create<TestDocument>();
var token = new CancellationToken(true);
var collection = SetupCollection();
// Act
var result = await Sut.UpdateOneAsync<TestDocument, Guid>(document, token);
// Assert
result.Should().BeTrue();
var expectedFilter = Builders<TestDocument>.Filter.Eq("Id", document.Id);
ReplaceOptions expectedOptions = null;
collection
.Verify(
x => x.ReplaceOneAsync(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
document,
expectedOptions,
token),
Times.Once());
}
[Fact]
public async Task WithDocumentAndUpdateDefinition_ReplacesOne()
{
// Arrange
var document = Fixture.Create<TestDocument>();
var collection = SetupCollection();
var updateDefinition = Builders<TestDocument>.Update.Set(x => x.Id, document.Id);
// Act
var result = await Sut.UpdateOneAsync<TestDocument, Guid>(document, updateDefinition);
// Assert
result.Should().BeTrue();
var expectedFilter = Builders<TestDocument>.Filter.Eq("Id", document.Id);
collection
.Verify(
x => x.UpdateOneAsync(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
updateDefinition,
null,
CancellationToken.None),
Times.Once());
}
[Fact]
public async Task WithDocumentAndUpdateDefinitionAndCancellationToken_ReplacesOne()
{
// Arrange
var document = Fixture.Create<TestDocument>();
var collection = SetupCollection();
var updateDefinition = Builders<TestDocument>.Update.Set(x => x.Id, document.Id);
var token = new CancellationToken(true);
// Act
var result = await Sut.UpdateOneAsync<TestDocument, Guid>(document, updateDefinition, token);
// Assert
result.Should().BeTrue();
var expectedFilter = Builders<TestDocument>.Filter.Eq("Id", document.Id);
collection
.Verify(
x => x.UpdateOneAsync(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
updateDefinition,
null,
token),
Times.Once());
}
[Fact]
public async Task WithDocumentAndFieldExpressionAndValue_ReplacesOne()
{
// Arrange
var document = Fixture.Create<TestDocument>();
var value = Fixture.Create<string>();
var collection = SetupCollection();
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = await Sut.UpdateOneAsync<TestDocument, Guid, string>(document, fieldExpression, value);
// Assert
result.Should().BeTrue();
var expectedFilter = Builders<TestDocument>.Filter.Eq("Id", document.Id);
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
collection
.Verify(
x => x.UpdateOneAsync(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
CancellationToken.None),
Times.Once());
}
[Fact]
public async Task WithDocumentAndFieldExpressionAndValueAndCancellationToken_ReplacesOne()
{
// Arrange
var document = Fixture.Create<TestDocument>();
var value = Fixture.Create<string>();
var collection = SetupCollection();
var token = new CancellationToken(true);
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = await Sut.UpdateOneAsync<TestDocument, Guid, string>(document, fieldExpression, value, token);
// Assert
result.Should().BeTrue();
var expectedFilter = Builders<TestDocument>.Filter.Eq("Id", document.Id);
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
collection
.Verify(
x => x.UpdateOneAsync(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
token),
Times.Once());
}
[Fact]
public async Task WithFilterAndFieldExpressionAndValueAndPartitionKey_ReplacesOne()
{
// Arrange
var value = Fixture.Create<string>();
var partitionKey = Fixture.Create<string>();
var collection = SetupCollection(partitionKey);
var filter = Builders<TestDocument>.Filter.Eq(x => x.SomeContent, "SomeContent");
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = await Sut.UpdateOneAsync<TestDocument, Guid, string>(
filter,
fieldExpression,
value,
partitionKey);
// Assert
result.Should().BeTrue();
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
collection
.Verify(
x => x.UpdateOneAsync(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(filter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
CancellationToken.None),
Times.Once());
}
[Fact]
public async Task WithFilterAndFieldExpressionAndValueAndCancellationToken_ReplacesOne()
{
// Arrange
var value = Fixture.Create<string>();
var collection = SetupCollection();
var token = new CancellationToken(true);
var filter = Builders<TestDocument>.Filter.Eq(x => x.SomeContent, "SomeContent");
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = await Sut.UpdateOneAsync<TestDocument, Guid, string>(
filter,
fieldExpression,
value,
cancellationToken: token);
// Assert
result.Should().BeTrue();
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
collection
.Verify(
x => x.UpdateOneAsync(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(filter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
token),
Times.Once());
}
[Fact]
public async Task WithFilterAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_ReplacesOne()
{
// Arrange
var value = Fixture.Create<string>();
var partitionKey = Fixture.Create<string>();
var collection = SetupCollection(partitionKey);
var token = new CancellationToken(true);
var filter = Builders<TestDocument>.Filter.Eq(x => x.SomeContent, "SomeContent");
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = await Sut.UpdateOneAsync<TestDocument, Guid, string>(
filter,
fieldExpression,
value,
partitionKey,
token);
// Assert
result.Should().BeTrue();
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
collection
.Verify(
x => x.UpdateOneAsync(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(filter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
token),
Times.Once());
}
[Fact]
public async Task WithFilterExpressionAndFieldExpressionAndValueAndCancellationToken_ReplacesOne()
{
// Arrange
var value = Fixture.Create<string>();
var collection = SetupCollection();
var token = new CancellationToken(true);
Expression<Func<TestDocument, bool>> filterExpression = testDocument => testDocument.SomeContent == "SomeContent";
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = await Sut.UpdateOneAsync<TestDocument, Guid, string>(
filterExpression,
fieldExpression,
value,
cancellationToken: token);
// Assert
result.Should().BeTrue();
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
var expectedFilter = Builders<TestDocument>.Filter.Where(filterExpression);
collection
.Verify(
x => x.UpdateOneAsync(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
token),
Times.Once());
}
[Fact]
public async Task WithFilterExpressionAndFieldExpressionAndValueAndPartitionKey_ReplacesOne()
{
// Arrange
var value = Fixture.Create<string>();
var partitionKey = Fixture.Create<string>();
var collection = SetupCollection(partitionKey);
Expression<Func<TestDocument, bool>> filterExpression = testDocument => testDocument.SomeContent == "SomeContent";
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = await Sut.UpdateOneAsync<TestDocument, Guid, string>(
filterExpression,
fieldExpression,
value,
partitionKey);
// Assert
result.Should().BeTrue();
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
var expectedFilter = Builders<TestDocument>.Filter.Where(filterExpression);
collection
.Verify(
x => x.UpdateOneAsync(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
CancellationToken.None),
Times.Once());
}
[Fact]
public async Task WithFilterExpressionAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_ReplacesOne()
{
// Arrange
var value = Fixture.Create<string>();
var partitionKey = Fixture.Create<string>();
var collection = SetupCollection(partitionKey);
var token = new CancellationToken(true);
Expression<Func<TestDocument, bool>> filterExpression = testDocument => testDocument.SomeContent == "SomeContent";
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = await Sut.UpdateOneAsync<TestDocument, Guid, string>(
filterExpression,
fieldExpression,
value,
partitionKey,
token);
// Assert
result.Should().BeTrue();
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
var expectedFilter = Builders<TestDocument>.Filter.Where(filterExpression);
collection
.Verify(
x => x.UpdateOneAsync(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
token),
Times.Once());
}
[Fact]
public async Task WithClientSessionAndDocument_ReplacesOne()
{
// Arrange
var session = MockOf<IClientSessionHandle>();
var document = Fixture.Create<TestDocument>();
var collection = SetupCollection();
// Act
var result = await Sut.UpdateOneAsync<TestDocument, Guid>(session.Object, document);
// Assert
result.Should().BeTrue();
var expectedFilter = Builders<TestDocument>.Filter.Eq("Id", document.Id);
ReplaceOptions expectedOptions = null;
collection
.Verify(
x => x.ReplaceOneAsync(
session.Object,
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
document,
expectedOptions,
CancellationToken.None),
Times.Once());
}
[Fact]
public async Task WithClientSessionAndDocumentAndCancellationToken_ReplacesOne()
{
// Arrange
var session = MockOf<IClientSessionHandle>();
var document = Fixture.Create<TestDocument>();
var token = new CancellationToken(true);
var collection = SetupCollection();
// Act
var result = await Sut.UpdateOneAsync<TestDocument, Guid>(session.Object, document, token);
// Assert
result.Should().BeTrue();
var expectedFilter = Builders<TestDocument>.Filter.Eq("Id", document.Id);
ReplaceOptions expectedOptions = null;
collection
.Verify(
x => x.ReplaceOneAsync(
session.Object,
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
document,
expectedOptions,
token),
Times.Once());
}
[Fact]
public async Task WithClientSessionAndDocumentAndUpdateDefinition_ReplacesOne()
{
// Arrange
var session = MockOf<IClientSessionHandle>();
var document = Fixture.Create<TestDocument>();
var collection = SetupCollection();
var updateDefinition = Builders<TestDocument>.Update.Set(x => x.Id, document.Id);
// Act
var result = await Sut.UpdateOneAsync<TestDocument, Guid>(session.Object, document, updateDefinition);
// Assert
result.Should().BeTrue();
var expectedFilter = Builders<TestDocument>.Filter.Eq("Id", document.Id);
collection
.Verify(
x => x.UpdateOneAsync(
session.Object,
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
updateDefinition,
null,
CancellationToken.None),
Times.Once());
}
[Fact]
public async Task WithClientSessionAndDocumentAndUpdateDefinitionAndCancellationToken_ReplacesOne()
{
// Arrange
var session = MockOf<IClientSessionHandle>();
var document = Fixture.Create<TestDocument>();
var collection = SetupCollection();
var updateDefinition = Builders<TestDocument>.Update.Set(x => x.Id, document.Id);
var token = new CancellationToken(true);
// Act
var result = await Sut.UpdateOneAsync<TestDocument, Guid>(session.Object, document, updateDefinition, token);
// Assert
result.Should().BeTrue();
var expectedFilter = Builders<TestDocument>.Filter.Eq("Id", document.Id);
collection
.Verify(
x => x.UpdateOneAsync(
session.Object,
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
updateDefinition,
null,
token),
Times.Once());
}
[Fact]
public async Task WithClientSessionAndDocumentAndFieldExpressionAndValue_ReplacesOne()
{
// Arrange
var session = MockOf<IClientSessionHandle>();
var document = Fixture.Create<TestDocument>();
var value = Fixture.Create<string>();
var collection = SetupCollection();
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = await Sut.UpdateOneAsync<TestDocument, Guid, string>(session.Object, document, fieldExpression, value);
// Assert
result.Should().BeTrue();
var expectedFilter = Builders<TestDocument>.Filter.Eq("Id", document.Id);
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
collection
.Verify(
x => x.UpdateOneAsync(
session.Object,
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
CancellationToken.None),
Times.Once());
}
[Fact]
public async Task WithClientSessionAndDocumentAndFieldExpressionAndValueAndCancellationToken_ReplacesOne()
{
// Arrange
var session = MockOf<IClientSessionHandle>();
var document = Fixture.Create<TestDocument>();
var value = Fixture.Create<string>();
var collection = SetupCollection();
var token = new CancellationToken(true);
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = await Sut.UpdateOneAsync<TestDocument, Guid, string>(session.Object, document, fieldExpression, value, token);
// Assert
result.Should().BeTrue();
var expectedFilter = Builders<TestDocument>.Filter.Eq("Id", document.Id);
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
collection
.Verify(
x => x.UpdateOneAsync(
session.Object,
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
token),
Times.Once());
}
[Fact]
public async Task WithClientSessionAndFilterAndFieldExpressionAndValueAndPartitionKey_ReplacesOne()
{
// Arrange
var session = MockOf<IClientSessionHandle>();
var value = Fixture.Create<string>();
var partitionKey = Fixture.Create<string>();
var collection = SetupCollection(partitionKey);
var filter = Builders<TestDocument>.Filter.Eq(x => x.SomeContent, "SomeContent");
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = await Sut.UpdateOneAsync<TestDocument, Guid, string>(
session.Object,
filter,
fieldExpression,
value,
partitionKey);
// Assert
result.Should().BeTrue();
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
collection
.Verify(
x => x.UpdateOneAsync(
session.Object,
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(filter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
CancellationToken.None),
Times.Once());
}
[Fact]
public async Task WithClientSessionAndFilterAndFieldExpressionAndValueAndCancellationToken_ReplacesOne()
{
// Arrange
var session = MockOf<IClientSessionHandle>();
var value = Fixture.Create<string>();
var collection = SetupCollection();
var token = new CancellationToken(true);
var filter = Builders<TestDocument>.Filter.Eq(x => x.SomeContent, "SomeContent");
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = await Sut.UpdateOneAsync<TestDocument, Guid, string>(
session.Object,
filter,
fieldExpression,
value,
cancellationToken: token);
// Assert
result.Should().BeTrue();
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
collection
.Verify(
x => x.UpdateOneAsync(
session.Object,
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(filter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
token),
Times.Once());
}
[Fact]
public async Task WithClientSessionAndFilterAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_ReplacesOne()
{
// Arrange
var session = MockOf<IClientSessionHandle>();
var value = Fixture.Create<string>();
var partitionKey = Fixture.Create<string>();
var collection = SetupCollection(partitionKey);
var token = new CancellationToken(true);
var filter = Builders<TestDocument>.Filter.Eq(x => x.SomeContent, "SomeContent");
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = await Sut.UpdateOneAsync<TestDocument, Guid, string>(
session.Object,
filter,
fieldExpression,
value,
partitionKey,
token);
// Assert
result.Should().BeTrue();
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
collection
.Verify(
x => x.UpdateOneAsync(
session.Object,
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(filter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
token),
Times.Once());
}
[Fact]
public async Task WithClientSessionAndFilterExpressionAndFieldExpressionAndValueAndCancellationToken_ReplacesOne()
{
// Arrange
var session = MockOf<IClientSessionHandle>();
var value = Fixture.Create<string>();
var collection = SetupCollection();
var token = new CancellationToken(true);
Expression<Func<TestDocument, bool>> filterExpression = testDocument => testDocument.SomeContent == "SomeContent";
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = await Sut.UpdateOneAsync<TestDocument, Guid, string>(
session.Object,
filterExpression,
fieldExpression,
value,
cancellationToken: token);
// Assert
result.Should().BeTrue();
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
var expectedFilter = Builders<TestDocument>.Filter.Where(filterExpression);
collection
.Verify(
x => x.UpdateOneAsync(
session.Object,
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
token),
Times.Once());
}
[Fact]
public async Task WithClientSessionAndFilterExpressionAndFieldExpressionAndValueAndPartitionKey_ReplacesOne()
{
// Arrange
var session = MockOf<IClientSessionHandle>();
var value = Fixture.Create<string>();
var partitionKey = Fixture.Create<string>();
var collection = SetupCollection(partitionKey);
Expression<Func<TestDocument, bool>> filterExpression = testDocument => testDocument.SomeContent == "SomeContent";
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = await Sut.UpdateOneAsync<TestDocument, Guid, string>(
session.Object,
filterExpression,
fieldExpression,
value,
partitionKey);
// Assert
result.Should().BeTrue();
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
var expectedFilter = Builders<TestDocument>.Filter.Where(filterExpression);
collection
.Verify(
x => x.UpdateOneAsync(
session.Object,
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
CancellationToken.None),
Times.Once());
}
[Fact]
public async Task WithClientSessionAndFilterExpressionAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_ReplacesOne()
{
// Arrange
var session = MockOf<IClientSessionHandle>();
var value = Fixture.Create<string>();
var partitionKey = Fixture.Create<string>();
var collection = SetupCollection(partitionKey);
var token = new CancellationToken(true);
Expression<Func<TestDocument, bool>> filterExpression = testDocument => testDocument.SomeContent == "SomeContent";
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = await Sut.UpdateOneAsync<TestDocument, Guid, string>(
session.Object,
filterExpression,
fieldExpression,
value,
partitionKey,
token);
// Assert
result.Should().BeTrue();
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
var expectedFilter = Builders<TestDocument>.Filter.Where(filterExpression);
collection
.Verify(
x => x.UpdateOneAsync(
session.Object,
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
token),
Times.Once());
}
private Mock<IMongoCollection<TestDocument>> SetupCollection(string partitionKey = null)
{
var replacedId = Fixture.Create<Guid>();
var count = Fixture.Create<long>();
var replaceResult = new ReplaceOneResult.Acknowledged(count, 1, new BsonBinaryData(replacedId, GuidRepresentation.Standard));
var updateResult = new UpdateResult.Acknowledged(count, 1, new BsonBinaryData(replacedId, GuidRepresentation.Standard));
var collection = MockOf<IMongoCollection<TestDocument>>();
collection
.Setup(
x => x.ReplaceOneAsync(
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<TestDocument>(),
It.IsAny<ReplaceOptions>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(replaceResult);
collection
.Setup(
x => x.UpdateOneAsync(
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<UpdateDefinition<TestDocument>>(),
It.IsAny<UpdateOptions>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(updateResult);
collection
.Setup(
x => x.ReplaceOneAsync(
It.IsAny<IClientSessionHandle>(),
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<TestDocument>(),
It.IsAny<ReplaceOptions>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(replaceResult);
collection
.Setup(
x => x.UpdateOneAsync(
It.IsAny<IClientSessionHandle>(),
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<UpdateDefinition<TestDocument>>(),
It.IsAny<UpdateOptions>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(updateResult);
var dbContext = MockOf<IMongoDbContext>();
dbContext
.Setup(x => x.GetCollection<TestDocument>(partitionKey))
.Returns(collection.Object);
return collection;
}
}
@@ -0,0 +1,805 @@
using System;
using System.Linq.Expressions;
using System.Threading;
using AutoFixture;
using CoreUnitTests.Infrastructure;
using CoreUnitTests.Infrastructure.Model;
using FluentAssertions;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDbGenericRepository;
using MongoDbGenericRepository.DataAccess.Update;
using Moq;
using Xunit;
namespace CoreUnitTests.DataAccessTests.MongoDbUpdaterTests;
public class UpdateOneTests : GenericTestContext<MongoDbUpdater>
{
[Fact]
public void WithDocument_ReplacesOne()
{
// Arrange
var document = Fixture.Create<TestDocument>();
var collection = SetupCollection();
// Act
var result = Sut.UpdateOne<TestDocument, Guid>(document);
// Assert
result.Should().BeTrue();
var expectedFilter = Builders<TestDocument>.Filter.Eq("Id", document.Id);
ReplaceOptions expectedOptions = null;
collection
.Verify(
x => x.ReplaceOne(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
document,
expectedOptions,
CancellationToken.None),
Times.Once());
}
[Fact]
public void WithDocumentAndCancellationToken_ReplacesOne()
{
// Arrange
var document = Fixture.Create<TestDocument>();
var token = new CancellationToken(true);
var collection = SetupCollection();
// Act
var result = Sut.UpdateOne<TestDocument, Guid>(document, token);
// Assert
result.Should().BeTrue();
var expectedFilter = Builders<TestDocument>.Filter.Eq("Id", document.Id);
ReplaceOptions expectedOptions = null;
collection
.Verify(
x => x.ReplaceOne(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
document,
expectedOptions,
token),
Times.Once());
}
[Fact]
public void WithDocumentAndUpdateDefinition_ReplacesOne()
{
// Arrange
var document = Fixture.Create<TestDocument>();
var collection = SetupCollection();
var updateDefinition = Builders<TestDocument>.Update.Set(x => x.Id, document.Id);
// Act
var result = Sut.UpdateOne<TestDocument, Guid>(document, updateDefinition);
// Assert
result.Should().BeTrue();
var expectedFilter = Builders<TestDocument>.Filter.Eq("Id", document.Id);
collection
.Verify(
x => x.UpdateOne(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
updateDefinition,
null,
CancellationToken.None),
Times.Once());
}
[Fact]
public void WithDocumentAndUpdateDefinitionAndCancellationToken_ReplacesOne()
{
// Arrange
var document = Fixture.Create<TestDocument>();
var collection = SetupCollection();
var updateDefinition = Builders<TestDocument>.Update.Set(x => x.Id, document.Id);
var token = new CancellationToken(true);
// Act
var result = Sut.UpdateOne<TestDocument, Guid>(document, updateDefinition, token);
// Assert
result.Should().BeTrue();
var expectedFilter = Builders<TestDocument>.Filter.Eq("Id", document.Id);
collection
.Verify(
x => x.UpdateOne(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
updateDefinition,
null,
token),
Times.Once());
}
[Fact]
public void WithDocumentAndFieldExpressionAndValue_ReplacesOne()
{
// Arrange
var document = Fixture.Create<TestDocument>();
var value = Fixture.Create<string>();
var collection = SetupCollection();
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = Sut.UpdateOne<TestDocument, Guid, string>(document, fieldExpression, value);
// Assert
result.Should().BeTrue();
var expectedFilter = Builders<TestDocument>.Filter.Eq("Id", document.Id);
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
collection
.Verify(
x => x.UpdateOne(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
CancellationToken.None),
Times.Once());
}
[Fact]
public void WithDocumentAndFieldExpressionAndValueAndCancellationToken_ReplacesOne()
{
// Arrange
var document = Fixture.Create<TestDocument>();
var value = Fixture.Create<string>();
var collection = SetupCollection();
var token = new CancellationToken(true);
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = Sut.UpdateOne<TestDocument, Guid, string>(document, fieldExpression, value, token);
// Assert
result.Should().BeTrue();
var expectedFilter = Builders<TestDocument>.Filter.Eq("Id", document.Id);
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
collection
.Verify(
x => x.UpdateOne(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
token),
Times.Once());
}
[Fact]
public void WithFilterAndFieldExpressionAndValueAndPartitionKey_ReplacesOne()
{
// Arrange
var value = Fixture.Create<string>();
var partitionKey = Fixture.Create<string>();
var collection = SetupCollection(partitionKey);
var filter = Builders<TestDocument>.Filter.Eq(x => x.SomeContent, "SomeContent");
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = Sut.UpdateOne<TestDocument, Guid, string>(
filter,
fieldExpression,
value,
partitionKey);
// Assert
result.Should().BeTrue();
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
collection
.Verify(
x => x.UpdateOne(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(filter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
CancellationToken.None),
Times.Once());
}
[Fact]
public void WithFilterAndFieldExpressionAndValueAndCancellationToken_ReplacesOne()
{
// Arrange
var value = Fixture.Create<string>();
var collection = SetupCollection();
var token = new CancellationToken(true);
var filter = Builders<TestDocument>.Filter.Eq(x => x.SomeContent, "SomeContent");
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = Sut.UpdateOne<TestDocument, Guid, string>(
filter,
fieldExpression,
value,
cancellationToken: token);
// Assert
result.Should().BeTrue();
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
collection
.Verify(
x => x.UpdateOne(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(filter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
token),
Times.Once());
}
[Fact]
public void WithFilterAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_ReplacesOne()
{
// Arrange
var value = Fixture.Create<string>();
var partitionKey = Fixture.Create<string>();
var collection = SetupCollection(partitionKey);
var token = new CancellationToken(true);
var filter = Builders<TestDocument>.Filter.Eq(x => x.SomeContent, "SomeContent");
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = Sut.UpdateOne<TestDocument, Guid, string>(
filter,
fieldExpression,
value,
partitionKey,
token);
// Assert
result.Should().BeTrue();
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
collection
.Verify(
x => x.UpdateOne(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(filter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
token),
Times.Once());
}
[Fact]
public void WithFilterExpressionAndFieldExpressionAndValueAndCancellationToken_ReplacesOne()
{
// Arrange
var value = Fixture.Create<string>();
var collection = SetupCollection();
var token = new CancellationToken(true);
Expression<Func<TestDocument, bool>> filterExpression = testDocument => testDocument.SomeContent == "SomeContent";
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = Sut.UpdateOne<TestDocument, Guid, string>(
filterExpression,
fieldExpression,
value,
cancellationToken: token);
// Assert
result.Should().BeTrue();
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
var expectedFilter = Builders<TestDocument>.Filter.Where(filterExpression);
collection
.Verify(
x => x.UpdateOne(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
token),
Times.Once());
}
[Fact]
public void WithFilterExpressionAndFieldExpressionAndValueAndPartitionKey_ReplacesOne()
{
// Arrange
var value = Fixture.Create<string>();
var partitionKey = Fixture.Create<string>();
var collection = SetupCollection(partitionKey);
Expression<Func<TestDocument, bool>> filterExpression = testDocument => testDocument.SomeContent == "SomeContent";
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = Sut.UpdateOne<TestDocument, Guid, string>(
filterExpression,
fieldExpression,
value,
partitionKey);
// Assert
result.Should().BeTrue();
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
var expectedFilter = Builders<TestDocument>.Filter.Where(filterExpression);
collection
.Verify(
x => x.UpdateOne(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
CancellationToken.None),
Times.Once());
}
[Fact]
public void WithFilterExpressionAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_ReplacesOne()
{
// Arrange
var value = Fixture.Create<string>();
var partitionKey = Fixture.Create<string>();
var collection = SetupCollection(partitionKey);
var token = new CancellationToken(true);
Expression<Func<TestDocument, bool>> filterExpression = testDocument => testDocument.SomeContent == "SomeContent";
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = Sut.UpdateOne<TestDocument, Guid, string>(
filterExpression,
fieldExpression,
value,
partitionKey,
token);
// Assert
result.Should().BeTrue();
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
var expectedFilter = Builders<TestDocument>.Filter.Where(filterExpression);
collection
.Verify(
x => x.UpdateOne(
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
token),
Times.Once());
}
[Fact]
public void WithClientSessionAndDocument_ReplacesOne()
{
// Arrange
var session = MockOf<IClientSessionHandle>();
var document = Fixture.Create<TestDocument>();
var collection = SetupCollection();
// Act
var result = Sut.UpdateOne<TestDocument, Guid>(session.Object, document);
// Assert
result.Should().BeTrue();
var expectedFilter = Builders<TestDocument>.Filter.Eq("Id", document.Id);
ReplaceOptions expectedOptions = null;
collection
.Verify(
x => x.ReplaceOne(
session.Object,
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
document,
expectedOptions,
CancellationToken.None),
Times.Once());
}
[Fact]
public void WithClientSessionAndDocumentAndCancellationToken_ReplacesOne()
{
// Arrange
var session = MockOf<IClientSessionHandle>();
var document = Fixture.Create<TestDocument>();
var token = new CancellationToken(true);
var collection = SetupCollection();
// Act
var result = Sut.UpdateOne<TestDocument, Guid>(session.Object, document, token);
// Assert
result.Should().BeTrue();
var expectedFilter = Builders<TestDocument>.Filter.Eq("Id", document.Id);
ReplaceOptions expectedOptions = null;
collection
.Verify(
x => x.ReplaceOne(
session.Object,
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
document,
expectedOptions,
token),
Times.Once());
}
[Fact]
public void WithClientSessionAndDocumentAndUpdateDefinition_ReplacesOne()
{
// Arrange
var session = MockOf<IClientSessionHandle>();
var document = Fixture.Create<TestDocument>();
var collection = SetupCollection();
var updateDefinition = Builders<TestDocument>.Update.Set(x => x.Id, document.Id);
// Act
var result = Sut.UpdateOne<TestDocument, Guid>(session.Object, document, updateDefinition);
// Assert
result.Should().BeTrue();
var expectedFilter = Builders<TestDocument>.Filter.Eq("Id", document.Id);
collection
.Verify(
x => x.UpdateOne(
session.Object,
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
updateDefinition,
null,
CancellationToken.None),
Times.Once());
}
[Fact]
public void WithClientSessionAndDocumentAndUpdateDefinitionAndCancellationToken_ReplacesOne()
{
// Arrange
var session = MockOf<IClientSessionHandle>();
var document = Fixture.Create<TestDocument>();
var collection = SetupCollection();
var updateDefinition = Builders<TestDocument>.Update.Set(x => x.Id, document.Id);
var token = new CancellationToken(true);
// Act
var result = Sut.UpdateOne<TestDocument, Guid>(session.Object, document, updateDefinition, token);
// Assert
result.Should().BeTrue();
var expectedFilter = Builders<TestDocument>.Filter.Eq("Id", document.Id);
collection
.Verify(
x => x.UpdateOne(
session.Object,
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
updateDefinition,
null,
token),
Times.Once());
}
[Fact]
public void WithClientSessionAndDocumentAndFieldExpressionAndValue_ReplacesOne()
{
// Arrange
var session = MockOf<IClientSessionHandle>();
var document = Fixture.Create<TestDocument>();
var value = Fixture.Create<string>();
var collection = SetupCollection();
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = Sut.UpdateOne<TestDocument, Guid, string>(session.Object, document, fieldExpression, value);
// Assert
result.Should().BeTrue();
var expectedFilter = Builders<TestDocument>.Filter.Eq("Id", document.Id);
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
collection
.Verify(
x => x.UpdateOne(
session.Object,
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
CancellationToken.None),
Times.Once());
}
[Fact]
public void WithClientSessionAndDocumentAndFieldExpressionAndValueAndCancellationToken_ReplacesOne()
{
// Arrange
var session = MockOf<IClientSessionHandle>();
var document = Fixture.Create<TestDocument>();
var value = Fixture.Create<string>();
var collection = SetupCollection();
var token = new CancellationToken(true);
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = Sut.UpdateOne<TestDocument, Guid, string>(session.Object, document, fieldExpression, value, token);
// Assert
result.Should().BeTrue();
var expectedFilter = Builders<TestDocument>.Filter.Eq("Id", document.Id);
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
collection
.Verify(
x => x.UpdateOne(
session.Object,
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
token),
Times.Once());
}
[Fact]
public void WithClientSessionAndFilterAndFieldExpressionAndValueAndPartitionKey_ReplacesOne()
{
// Arrange
var session = MockOf<IClientSessionHandle>();
var value = Fixture.Create<string>();
var partitionKey = Fixture.Create<string>();
var collection = SetupCollection(partitionKey);
var filter = Builders<TestDocument>.Filter.Eq(x => x.SomeContent, "SomeContent");
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = Sut.UpdateOne<TestDocument, Guid, string>(
session.Object,
filter,
fieldExpression,
value,
partitionKey);
// Assert
result.Should().BeTrue();
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
collection
.Verify(
x => x.UpdateOne(
session.Object,
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(filter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
CancellationToken.None),
Times.Once());
}
[Fact]
public void WithClientSessionAndFilterAndFieldExpressionAndValueAndCancellationToken_ReplacesOne()
{
// Arrange
var session = MockOf<IClientSessionHandle>();
var value = Fixture.Create<string>();
var collection = SetupCollection();
var token = new CancellationToken(true);
var filter = Builders<TestDocument>.Filter.Eq(x => x.SomeContent, "SomeContent");
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = Sut.UpdateOne<TestDocument, Guid, string>(
session.Object,
filter,
fieldExpression,
value,
cancellationToken: token);
// Assert
result.Should().BeTrue();
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
collection
.Verify(
x => x.UpdateOne(
session.Object,
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(filter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
token),
Times.Once());
}
[Fact]
public void WithClientSessionAndFilterAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_ReplacesOne()
{
// Arrange
var session = MockOf<IClientSessionHandle>();
var value = Fixture.Create<string>();
var partitionKey = Fixture.Create<string>();
var collection = SetupCollection(partitionKey);
var token = new CancellationToken(true);
var filter = Builders<TestDocument>.Filter.Eq(x => x.SomeContent, "SomeContent");
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = Sut.UpdateOne<TestDocument, Guid, string>(
session.Object,
filter,
fieldExpression,
value,
partitionKey,
token);
// Assert
result.Should().BeTrue();
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
collection
.Verify(
x => x.UpdateOne(
session.Object,
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(filter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
token),
Times.Once());
}
[Fact]
public void WithClientSessionAndFilterExpressionAndFieldExpressionAndValueAndCancellationToken_ReplacesOne()
{
// Arrange
var session = MockOf<IClientSessionHandle>();
var value = Fixture.Create<string>();
var collection = SetupCollection();
var token = new CancellationToken(true);
Expression<Func<TestDocument, bool>> filterExpression = testDocument => testDocument.SomeContent == "SomeContent";
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = Sut.UpdateOne<TestDocument, Guid, string>(
session.Object,
filterExpression,
fieldExpression,
value,
cancellationToken: token);
// Assert
result.Should().BeTrue();
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
var expectedFilter = Builders<TestDocument>.Filter.Where(filterExpression);
collection
.Verify(
x => x.UpdateOne(
session.Object,
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
token),
Times.Once());
}
[Fact]
public void WithClientSessionAndFilterExpressionAndFieldExpressionAndValueAndPartitionKey_ReplacesOne()
{
// Arrange
var session = MockOf<IClientSessionHandle>();
var value = Fixture.Create<string>();
var partitionKey = Fixture.Create<string>();
var collection = SetupCollection(partitionKey);
Expression<Func<TestDocument, bool>> filterExpression = testDocument => testDocument.SomeContent == "SomeContent";
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = Sut.UpdateOne<TestDocument, Guid, string>(
session.Object,
filterExpression,
fieldExpression,
value,
partitionKey);
// Assert
result.Should().BeTrue();
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
var expectedFilter = Builders<TestDocument>.Filter.Where(filterExpression);
collection
.Verify(
x => x.UpdateOne(
session.Object,
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
CancellationToken.None),
Times.Once());
}
[Fact]
public void WithClientSessionAndFilterExpressionAndFieldExpressionAndValueAndPartitionKeyAndCancellationToken_ReplacesOne()
{
// Arrange
var session = MockOf<IClientSessionHandle>();
var value = Fixture.Create<string>();
var partitionKey = Fixture.Create<string>();
var collection = SetupCollection(partitionKey);
var token = new CancellationToken(true);
Expression<Func<TestDocument, bool>> filterExpression = testDocument => testDocument.SomeContent == "SomeContent";
Expression<Func<TestDocument, string>> fieldExpression = testDocument => testDocument.SomeContent;
// Act
var result = Sut.UpdateOne<TestDocument, Guid, string>(
session.Object,
filterExpression,
fieldExpression,
value,
partitionKey,
token);
// Assert
result.Should().BeTrue();
var expectedUpdateDefinition = Builders<TestDocument>.Update.Set(x => x.SomeContent, value);
var expectedFilter = Builders<TestDocument>.Filter.Where(filterExpression);
collection
.Verify(
x => x.UpdateOne(
session.Object,
It.Is<FilterDefinition<TestDocument>>(f => f.EquivalentTo(expectedFilter)),
It.Is<UpdateDefinition<TestDocument>>(u => u.EquivalentTo(expectedUpdateDefinition)),
null,
token),
Times.Once());
}
private Mock<IMongoCollection<TestDocument>> SetupCollection(string partitionKey = null)
{
var replacedId = Fixture.Create<Guid>();
var count = Fixture.Create<long>();
var replaceResult = new ReplaceOneResult.Acknowledged(count, 1, new BsonBinaryData(replacedId, GuidRepresentation.Standard));
var updateResult = new UpdateResult.Acknowledged(count, 1, new BsonBinaryData(replacedId, GuidRepresentation.Standard));
var collection = MockOf<IMongoCollection<TestDocument>>();
collection
.Setup(
x => x.ReplaceOne(
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<TestDocument>(),
It.IsAny<ReplaceOptions>(),
It.IsAny<CancellationToken>()))
.Returns(replaceResult);
collection
.Setup(
x => x.UpdateOne(
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<UpdateDefinition<TestDocument>>(),
It.IsAny<UpdateOptions>(),
It.IsAny<CancellationToken>()))
.Returns(updateResult);
collection
.Setup(
x => x.ReplaceOne(
It.IsAny<IClientSessionHandle>(),
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<TestDocument>(),
It.IsAny<ReplaceOptions>(),
It.IsAny<CancellationToken>()))
.Returns(replaceResult);
collection
.Setup(
x => x.UpdateOne(
It.IsAny<IClientSessionHandle>(),
It.IsAny<FilterDefinition<TestDocument>>(),
It.IsAny<UpdateDefinition<TestDocument>>(),
It.IsAny<UpdateOptions>(),
It.IsAny<CancellationToken>()))
.Returns(updateResult);
var dbContext = MockOf<IMongoDbContext>();
dbContext
.Setup(x => x.GetCollection<TestDocument>(partitionKey))
.Returns(collection.Object);
return collection;
}
}
@@ -0,0 +1,14 @@
namespace CoreUnitTests.Infrastructure;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Driver;
public static class FilterDefinitionExtensions
{
public static string RenderToJson<TDocument>(this FilterDefinition<TDocument> filter)
=> filter.Render(BsonSerializer.SerializerRegistry.GetSerializer<TDocument>(), BsonSerializer.SerializerRegistry).ToJson();
public static bool EquivalentTo<TDocument>(this FilterDefinition<TDocument> filter, FilterDefinition<TDocument> other)
=> filter.RenderToJson() == other.RenderToJson();
}
@@ -0,0 +1,18 @@
using AutoFixture;
using AutoFixture.AutoMoq;
using Moq;
namespace CoreUnitTests.Infrastructure;
public class GenericTestContext<TSut>
{
public GenericTestContext() => Fixture = new Fixture().Customize(new AutoMoqCustomization());
protected Mock<T> MockOf<T>()
where T : class =>
Fixture.Freeze<Mock<T>>();
protected IFixture Fixture { get; set; }
protected TSut Sut => Fixture.Create<TSut>();
}
@@ -0,0 +1,69 @@
using System;
using MongoDB.Bson.Serialization;
using MongoDB.Driver;
using MongoDbGenericRepository.Models;
using Xunit.Abstractions;
namespace CoreUnitTests.Infrastructure;
public static class IndexExtensions
{
public static bool EqualToJson<TDocument>(this IndexKeysDefinition<TDocument> keys, string json, ITestOutputHelper output)
{
var indexModelRendered = RenderIndexModelKeys(keys);
var result = indexModelRendered.Equals(json, StringComparison.Ordinal);
if (!result && output != null)
{
output.WriteLine($"Expected: {json}");
output.WriteLine($"Actual: {indexModelRendered}");
}
return result;
}
public static bool EqualToJson<TDocument>(this IndexKeysDefinition<TDocument> keys, string json)
{
var indexModelRendered = RenderIndexModelKeys(keys);
return indexModelRendered.Equals(json, StringComparison.Ordinal);
}
public static bool EqualTo(this IndexCreationOptions x, CreateIndexOptions y) =>
x.Unique == y.Unique &&
x.TextIndexVersion == y.TextIndexVersion &&
x.SphereIndexVersion == y.SphereIndexVersion &&
x.Sparse == y.Sparse &&
x.Name == y.Name &&
x.Min == y.Min &&
x.Max == y.Max &&
x.LanguageOverride == y.LanguageOverride &&
x.ExpireAfter == y.ExpireAfter &&
x.DefaultLanguage == y.DefaultLanguage &&
x.Bits == y.Bits &&
x.Background == y.Background &&
x.Version == y.Version;
public static bool EqualTo(this CreateIndexOptions x, IndexCreationOptions y) =>
x.Unique == y.Unique &&
x.TextIndexVersion == y.TextIndexVersion &&
x.SphereIndexVersion == y.SphereIndexVersion &&
x.Sparse == y.Sparse &&
x.Name == y.Name &&
x.Min == y.Min &&
x.Max == y.Max &&
x.LanguageOverride == y.LanguageOverride &&
x.ExpireAfter == y.ExpireAfter &&
x.DefaultLanguage == y.DefaultLanguage &&
x.Bits == y.Bits &&
x.Background == y.Background &&
x.Version == y.Version;
private static string RenderIndexModelKeys<TDocument>(IndexKeysDefinition<TDocument> keys)
{
var indexModelRendered = keys.Render(
BsonSerializer.SerializerRegistry.GetSerializer<TDocument>(),
BsonSerializer.SerializerRegistry);
var result = indexModelRendered.ToString();
return result.Replace(" ", "");
}
}

Some files were not shown because too many files have changed in this diff Show More