mongo-csharp-driver /tests/MongoDB.Driver.Tests/OfTypeMongoCollectionTests.cs

Language C# Lines 827
MD5 Hash 5723fa660d5694e971e877169dee1a55 Estimated Cost $18,912 (why?)
Repository git://github.com/mongodb/mongo-csharp-driver.git View Raw File View Project SPDX
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
/* Copyright 2013-2015 MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Bson.TestHelpers.XunitExtensions;
using MongoDB.Driver;
using Moq;
using Xunit;

namespace MongoDB.Driver.Tests
{
    public class OfTypeMongoCollectionTests
    {
        private BsonDocument _ofTypeFilter;
        private BsonDocument _expectedFilter;
        private BsonDocument _providedFilter;
        private Mock<IMongoCollection<A>> _mockRootCollection;
        private Mock<IMongoCollection<B>> _mockDerivedCollection;
        private IMongoCollection<A> _rootCollection;
        private IMongoCollection<B> _derivedCollection;

        public OfTypeMongoCollectionTests()
        {
            _ofTypeFilter = new BsonDocument("_t", "B");
            _providedFilter = new BsonDocument("PropB", 4);
            _expectedFilter = new BsonDocument("_t", "B").Add("PropB", 4);

            _mockRootCollection = new Mock<IMongoCollection<A>>();
            _mockRootCollection.SetupGet(c => c.CollectionNamespace).Returns(CollectionNamespace.FromFullName("foo.bar"));
            _mockRootCollection.SetupGet(c => c.Settings).Returns(new MongoCollectionSettings());
            _mockDerivedCollection = new Mock<IMongoCollection<B>>();
            _mockDerivedCollection.SetupGet(c => c.CollectionNamespace).Returns(CollectionNamespace.FromFullName("foo.bar"));
            _mockDerivedCollection.SetupGet(c => c.Settings).Returns(new MongoCollectionSettings());
            _rootCollection = _mockRootCollection.Object;
            _derivedCollection = _mockDerivedCollection.Object;
        }

        [Theory]
        [ParameterAttributeData]
        public void Aggregate_should_add_match_to_beginning_of_pipeline(
            [Values(false, true)] bool async)
        {
            var subject = CreateSubject();
            var options = new AggregateOptions();

            if (async)
            {
                subject.AggregateAsync<B>(new[] { new BsonDocument("$skip", 10) }, options, CancellationToken.None);

                _mockDerivedCollection.Verify(
                    c => c.AggregateAsync(
                        It.Is<PipelineDefinition<B, B>>(p => RenderPipeline(p)[0].Equals(new BsonDocument("$match", _ofTypeFilter))),
                        options,
                        CancellationToken.None),
                    Times.Once);
            }
            else
            {
                subject.Aggregate<B>(new[] { new BsonDocument("$skip", 10) }, options, CancellationToken.None);

                _mockDerivedCollection.Verify(
                    c => c.Aggregate(
                        It.Is<PipelineDefinition<B, B>>(p => RenderPipeline(p)[0].Equals(new BsonDocument("$match", _ofTypeFilter))),
                        options,
                        CancellationToken.None),
                    Times.Once);
            }
        }

        [Theory]
        [ParameterAttributeData]
        public void Aggregate_should_combine_match_statements_at_the_beginning_of_a_pipeline(
            [Values(false, true)] bool async)
        {
            var subject = CreateSubject();
            var options = new AggregateOptions();

            if (async)
            {
                subject.AggregateAsync<B>(new[] { new BsonDocument("$match", new BsonDocument("x", 1)) }, options, CancellationToken.None);

                var expectedFilter = new BsonDocument(_ofTypeFilter).Add("x", 1);
                _mockDerivedCollection.Verify(
                    c => c.AggregateAsync(
                        It.Is<PipelineDefinition<B, B>>(p => RenderPipeline(p)[0].Equals(new BsonDocument("$match", expectedFilter))),
                        options,
                        CancellationToken.None),
                    Times.Once);
            }
            else
            {
                subject.Aggregate<B>(new[] { new BsonDocument("$match", new BsonDocument("x", 1)) }, options, CancellationToken.None);

                var expectedFilter = new BsonDocument(_ofTypeFilter).Add("x", 1);
                _mockDerivedCollection.Verify(
                    c => c.Aggregate(
                        It.Is<PipelineDefinition<B, B>>(p => RenderPipeline(p)[0].Equals(new BsonDocument("$match", expectedFilter))),
                        options,
                        CancellationToken.None),
                    Times.Once);
            }
        }

        [Theory]
        [ParameterAttributeData]
        public void BulkWrite_with_DeleteOne(
            [Values(false, true)] bool async)
        {
            var subject = CreateSubject();
            var model = new DeleteOneModel<B>(_providedFilter);
            var options = new BulkWriteOptions();

            if (async)
            {
                subject.BulkWriteAsync(new[] { model }, options, CancellationToken.None);

                _mockDerivedCollection.Verify(
                    c => c.BulkWriteAsync(
                        It.Is<IEnumerable<WriteModel<B>>>(v => v.OfType<DeleteOneModel<B>>()
                            .Where(m => RenderFilter(m.Filter).Equals(_expectedFilter)).Count() == 1),
                        options,
                        CancellationToken.None),
                    Times.Once);
            }
            else
            {
                subject.BulkWrite(new[] { model }, options, CancellationToken.None);

                _mockDerivedCollection.Verify(
                    c => c.BulkWrite(
                        It.Is<IEnumerable<WriteModel<B>>>(v => v.OfType<DeleteOneModel<B>>()
                            .Where(m => RenderFilter(m.Filter).Equals(_expectedFilter)).Count() == 1),
                        options,
                        CancellationToken.None),
                    Times.Once);
            }
        }

        [Theory]
        [ParameterAttributeData]
        public void BulkWrite_with_DeleteMany(
            [Values(false, true)] bool async)
        {
            var subject = CreateSubject();
            var model = new DeleteManyModel<B>(_providedFilter);
            var options = new BulkWriteOptions();

            if (async)
            {
                subject.BulkWriteAsync(new[] { model }, options, CancellationToken.None);

                _mockDerivedCollection.Verify(
                    c => c.BulkWriteAsync(
                        It.Is<IEnumerable<WriteModel<B>>>(v => v.OfType<DeleteManyModel<B>>()
                            .Where(m => RenderFilter(m.Filter).Equals(_expectedFilter)).Count() == 1),
                        options,
                        CancellationToken.None),
                    Times.Once);
            }
            else
            {
                subject.BulkWrite(new[] { model }, options, CancellationToken.None);

                _mockDerivedCollection.Verify(
                    c => c.BulkWrite(
                        It.Is<IEnumerable<WriteModel<B>>>(v => v.OfType<DeleteManyModel<B>>()
                            .Where(m => RenderFilter(m.Filter).Equals(_expectedFilter)).Count() == 1),
                        options,
                        CancellationToken.None),
                    Times.Once);
            }
        }

        [Theory]
        [ParameterAttributeData]
        public void BulkWrite_with_ReplaceOne(
            [Values(false, true)] bool async)
        {
            var subject = CreateSubject();
            var replacement = new B();
            var model = new ReplaceOneModel<B>(_providedFilter, replacement) { IsUpsert = true };
            var options = new BulkWriteOptions();

            if (async)
            {
                subject.BulkWriteAsync(new[] { model }, options, CancellationToken.None);

                _mockDerivedCollection.Verify(
                    c => c.BulkWriteAsync(
                        It.Is<IEnumerable<WriteModel<B>>>(v => v.OfType<ReplaceOneModel<B>>()
                            .Where(m => RenderFilter(m.Filter).Equals(_expectedFilter) &&
                                m.Replacement == model.Replacement &&
                                m.IsUpsert == model.IsUpsert).Count() == 1),
                        options,
                        CancellationToken.None),
                    Times.Once);
            }
            else
            {
                subject.BulkWrite(new[] { model }, options, CancellationToken.None);

                _mockDerivedCollection.Verify(
                    c => c.BulkWrite(
                        It.Is<IEnumerable<WriteModel<B>>>(v => v.OfType<ReplaceOneModel<B>>()
                            .Where(m => RenderFilter(m.Filter).Equals(_expectedFilter) &&
                                m.Replacement == model.Replacement &&
                                m.IsUpsert == model.IsUpsert).Count() == 1),
                        options,
                        CancellationToken.None),
                    Times.Once);
            }
        }

        [Theory]
        [ParameterAttributeData]
        public void BulkWrite_with_UpdateMany(
            [Values(false, true)] bool async)
        {
            var subject = CreateSubject();
            var model = new UpdateManyModel<B>(_providedFilter, "{$set: {x: 1}}") { IsUpsert = true };
            var options = new BulkWriteOptions();

            if (async)
            {
                subject.BulkWriteAsync(new[] { model }, options, CancellationToken.None);

                _mockDerivedCollection.Verify(
                    c => c.BulkWriteAsync(
                        It.Is<IEnumerable<WriteModel<B>>>(v => v.OfType<UpdateManyModel<B>>()
                            .Where(m => RenderFilter(m.Filter).Equals(_expectedFilter) &&
                                RenderUpdate(m.Update).Equals(BsonDocument.Parse("{$set: {x: 1}}")) &&
                                m.IsUpsert == model.IsUpsert).Count() == 1),
                        options,
                        CancellationToken.None),
                    Times.Once);
            }
            else
            {
                subject.BulkWrite(new[] { model }, options, CancellationToken.None);

                _mockDerivedCollection.Verify(
                    c => c.BulkWrite(
                        It.Is<IEnumerable<WriteModel<B>>>(v => v.OfType<UpdateManyModel<B>>()
                            .Where(m => RenderFilter(m.Filter).Equals(_expectedFilter) &&
                                RenderUpdate(m.Update).Equals(BsonDocument.Parse("{$set: {x: 1}}")) &&
                                m.IsUpsert == model.IsUpsert).Count() == 1),
                        options,
                        CancellationToken.None),
                    Times.Once);
            }
        }

        [Theory]
        [ParameterAttributeData]
        public void BulkWrite_with_UpdateOne(
            [Values(false, true)] bool async)
        {
            var subject = CreateSubject();
            var model = new UpdateOneModel<B>(_providedFilter, "{$set: {x: 1}}") { IsUpsert = true };
            var options = new BulkWriteOptions();

            if (async)
            {
                subject.BulkWriteAsync(new[] { model }, options, CancellationToken.None);

                _mockDerivedCollection.Verify(
                    c => c.BulkWriteAsync(
                        It.Is<IEnumerable<WriteModel<B>>>(v => v.OfType<UpdateOneModel<B>>()
                            .Where(m => RenderFilter(m.Filter).Equals(_expectedFilter) &&
                                RenderUpdate(m.Update).Equals(BsonDocument.Parse("{$set: {x: 1}}")) &&
                                m.IsUpsert == model.IsUpsert).Count() == 1),
                        options,
                        CancellationToken.None),
                    Times.Once);
            }
            else
            {
                subject.BulkWrite(new[] { model }, options, CancellationToken.None);

                _mockDerivedCollection.Verify(
                    c => c.BulkWrite(
                        It.Is<IEnumerable<WriteModel<B>>>(v => v.OfType<UpdateOneModel<B>>()
                            .Where(m => RenderFilter(m.Filter).Equals(_expectedFilter) &&
                                RenderUpdate(m.Update).Equals(BsonDocument.Parse("{$set: {x: 1}}")) &&
                                m.IsUpsert == model.IsUpsert).Count() == 1),
                        options,
                        CancellationToken.None),
                    Times.Once);
            }
        }

        [Theory]
        [ParameterAttributeData]
        public void Count_should_include_the_filter(
            [Values(false, true)] bool async)
        {
            var subject = CreateSubject();
            var options = new CountOptions();

            if (async)
            {
                subject.CountAsync(_providedFilter, options, CancellationToken.None);

                _mockDerivedCollection.Verify(
                    c => c.CountAsync(
                        It.Is<FilterDefinition<B>>(f => RenderFilter(f).Equals(_expectedFilter)),
                        options,
                        CancellationToken.None),
                    Times.Once);
            }
            else
            {
                subject.Count(_providedFilter, options, CancellationToken.None);

                _mockDerivedCollection.Verify(
                    c => c.Count(
                        It.Is<FilterDefinition<B>>(f => RenderFilter(f).Equals(_expectedFilter)),
                        options,
                        CancellationToken.None),
                    Times.Once);
            }
        }

        [Theory]
        [ParameterAttributeData]
        public void Distinct_should_include_the_filter(
            [Values(false, true)] bool async)
        {
            var subject = CreateSubject();
            var options = new DistinctOptions();

            if (async)
            {
                subject.DistinctAsync(x => x.PropA, _providedFilter, options, CancellationToken.None);

                _mockDerivedCollection.Verify(
                    c => c.DistinctAsync(
                        It.Is<FieldDefinition<B, int>>(f => RenderField(f).Equals("PropA")),
                        It.Is<FilterDefinition<B>>(f => RenderFilter(f).Equals(_expectedFilter)),
                        options,
                        CancellationToken.None),
                    Times.Once);
            }
            else
            {
                subject.Distinct(x => x.PropA, _providedFilter, options, CancellationToken.None);

                _mockDerivedCollection.Verify(
                    c => c.Distinct(
                        It.Is<FieldDefinition<B, int>>(f => RenderField(f).Equals("PropA")),
                        It.Is<FilterDefinition<B>>(f => RenderFilter(f).Equals(_expectedFilter)),
                        options,
                        CancellationToken.None),
                    Times.Once);
            }
        }

        [Theory]
        [ParameterAttributeData]
        public void Find_should_include_the_filter(
            [Values(false, true)] bool async)
        {
            var subject = CreateSubject();
            var options = new FindOptions<B>();

            if (async)
            {
                subject.FindAsync(_providedFilter, options, CancellationToken.None);

                _mockDerivedCollection.Verify(
                    c => c.FindAsync(
                        It.Is<FilterDefinition<B>>(f => RenderFilter(f).Equals(_expectedFilter)),
                        options,
                        CancellationToken.None),
                    Times.Once);
            }
            else
            {
                subject.FindSync(_providedFilter, options, CancellationToken.None);

                _mockDerivedCollection.Verify(
                    c => c.FindSync(
                        It.Is<FilterDefinition<B>>(f => RenderFilter(f).Equals(_expectedFilter)),
                        options,
                        CancellationToken.None),
                    Times.Once);
            }
        }

        [Theory]
        [ParameterAttributeData]
        public void FindOneAndDelete_should_include_the_filter(
            [Values(false, true)] bool async)
        {
            var subject = CreateSubject();
            var options = new FindOneAndDeleteOptions<B>();

            if (async)
            {
                subject.FindOneAndDeleteAsync(_providedFilter, options, CancellationToken.None);

                _mockDerivedCollection.Verify(
                    c => c.FindOneAndDeleteAsync(
                        It.Is<FilterDefinition<B>>(f => RenderFilter(f).Equals(_expectedFilter)),
                        options,
                        CancellationToken.None),
                    Times.Once);
            }
            else
            {
                subject.FindOneAndDelete(_providedFilter, options, CancellationToken.None);

                _mockDerivedCollection.Verify(
                    c => c.FindOneAndDelete(
                        It.Is<FilterDefinition<B>>(f => RenderFilter(f).Equals(_expectedFilter)),
                        options,
                        CancellationToken.None),
                    Times.Once);
            }
        }

        [Theory]
        [ParameterAttributeData]
        public void FindOneAndReplace_should_include_the_filter(
            [Values(false, true)] bool async)
        {
            var subject = CreateSubject();
            var replacement = new B();
            var options = new FindOneAndReplaceOptions<B>();

            if (async)
            {
                subject.FindOneAndReplaceAsync(_providedFilter, replacement, options, CancellationToken.None);

                _mockDerivedCollection.Verify(
                    c => c.FindOneAndReplaceAsync(
                        It.Is<FilterDefinition<B>>(f => RenderFilter(f).Equals(_expectedFilter)),
                        replacement,
                        options,
                        CancellationToken.None),
                    Times.Once);
            }
            else
            {
                subject.FindOneAndReplace(_providedFilter, replacement, options, CancellationToken.None);

                _mockDerivedCollection.Verify(
                    c => c.FindOneAndReplace(
                        It.Is<FilterDefinition<B>>(f => RenderFilter(f).Equals(_expectedFilter)),
                        replacement,
                        options,
                        CancellationToken.None),
                    Times.Once);
            }
        }

        [Theory]
        [ParameterAttributeData]
        public void FindOneAndUpdate_should_include_the_filter(
            [Values(false, true)] bool async)
        {
            var subject = CreateSubject();
            var update = new BsonDocument("$set", new BsonDocument("x", 5));
            var options = new FindOneAndUpdateOptions<B>();

            if (async)
            {
                subject.FindOneAndUpdateAsync(_providedFilter, update, options, CancellationToken.None);

                _mockDerivedCollection.Verify(
                    c => c.FindOneAndUpdateAsync(
                        It.Is<FilterDefinition<B>>(f => RenderFilter(f).Equals(_expectedFilter)),
                        It.Is<UpdateDefinition<B>>(u => RenderUpdate(u).Equals(BsonDocument.Parse("{$set: {x: 5}}"))),
                        options,
                        CancellationToken.None),
                    Times.Once);
            }
            else
            {
                subject.FindOneAndUpdate(_providedFilter, update, options, CancellationToken.None);

                _mockDerivedCollection.Verify(
                    c => c.FindOneAndUpdate(
                        It.Is<FilterDefinition<B>>(f => RenderFilter(f).Equals(_expectedFilter)),
                        It.Is<UpdateDefinition<B>>(u => RenderUpdate(u).Equals(BsonDocument.Parse("{$set: {x: 5}}"))),
                        options,
                        CancellationToken.None),
                    Times.Once);
            }
        }

        [Theory]
        [ParameterAttributeData]
        public void MapReduce_should_include_the_filter_when_one_was_not_provided(
            [Values(false, true)] bool async)
        {
            var subject = CreateSubject();

            if (async)
            {
                subject.MapReduceAsync<B>("map", "reduce", null, CancellationToken.None);

                _mockDerivedCollection.Verify(
                    c => c.MapReduceAsync(
                        "map",
                        "reduce",
                        It.Is<MapReduceOptions<B, B>>(o => RenderFilter(o.Filter).Equals(_ofTypeFilter)),
                        CancellationToken.None),
                    Times.Once);
            }
            else
            {
                subject.MapReduce<B>("map", "reduce", null, CancellationToken.None);

                _mockDerivedCollection.Verify(
                    c => c.MapReduce(
                        "map",
                        "reduce",
                        It.Is<MapReduceOptions<B, B>>(o => RenderFilter(o.Filter).Equals(_ofTypeFilter)),
                        CancellationToken.None),
                    Times.Once);
            }
        }

        [Theory]
        [ParameterAttributeData]
        public void MapReduce_should_include_the_filter(
            [Values(false, true)] bool async)
        {
            var subject = CreateSubject();
            var options = new MapReduceOptions<B, B>
            {
                Filter = _providedFilter
            };

            if (async)
            {
                subject.MapReduceAsync("map", "reduce", options, CancellationToken.None);

                _mockDerivedCollection.Verify(
                    c => c.MapReduceAsync(
                        "map",
                        "reduce",
                        It.Is<MapReduceOptions<B, B>>(o => RenderFilter(o.Filter).Equals(_expectedFilter)),
                        CancellationToken.None),
                    Times.Once);
            }
            else
            {
                subject.MapReduce("map", "reduce", options, CancellationToken.None);

                _mockDerivedCollection.Verify(
                    c => c.MapReduce(
                        "map",
                        "reduce",
                        It.Is<MapReduceOptions<B, B>>(o => RenderFilter(o.Filter).Equals(_expectedFilter)),
                        CancellationToken.None),
                    Times.Once);
            }
        }

        [Fact]
        public void OfType_should_resort_to_root_collections_OfType()
        {
            var subject = CreateSubject();

            subject.OfType<C>();

            _mockRootCollection.Verify(c => c.OfType<C>(), Times.Once);
            _mockDerivedCollection.Verify(c => c.OfType<C>(), Times.Never);
        }

        private OfTypeMongoCollection<A, B> CreateSubject()
        {
            return new OfTypeMongoCollection<A, B>(_rootCollection, _derivedCollection, _ofTypeFilter);
        }

        private string RenderField<TDocument, TField>(FieldDefinition<TDocument, TField> field)
        {
            var serializer = BsonSerializer.SerializerRegistry.GetSerializer<TDocument>();
            return field.Render(serializer, BsonSerializer.SerializerRegistry).FieldName;
        }

        private BsonDocument RenderFilter<TDocument>(FilterDefinition<TDocument> filter)
        {
            var serializer = BsonSerializer.SerializerRegistry.GetSerializer<TDocument>();
            var doc = filter.Render(serializer, BsonSerializer.SerializerRegistry);
            return doc;
        }

        private List<BsonDocument> RenderPipeline<TInput, TOutput>(PipelineDefinition<TInput, TOutput> pipeline)
        {
            var serializer = BsonSerializer.SerializerRegistry.GetSerializer<TInput>();
            return pipeline.Render(serializer, BsonSerializer.SerializerRegistry).Documents.ToList();
        }

        private BsonDocument RenderUpdate<TDocument>(UpdateDefinition<TDocument> update)
        {
            var serializer = BsonSerializer.SerializerRegistry.GetSerializer<TDocument>();
            return update.Render(serializer, BsonSerializer.SerializerRegistry);
        }

        public class A
        {
            public int PropA;
        }

        public class B : A
        {
            public int PropB;
        }

        public class C : B
        {
            public int PropC;
        }
    }

    public class OfTypeCollectionIntegrationTests
    {
        private IMongoCollection<BsonDocument> _docsCollection;
        private IMongoCollection<A> _rootCollection;

        public OfTypeCollectionIntegrationTests()
        {
            var client = DriverTestConfiguration.Client;
            var db = client.GetDatabase(DriverTestConfiguration.DatabaseNamespace.DatabaseName);
            db.DropCollection(DriverTestConfiguration.CollectionNamespace.CollectionName);

            _docsCollection = db.GetCollection<BsonDocument>(DriverTestConfiguration.CollectionNamespace.CollectionName);
            _rootCollection = db.GetCollection<A>(DriverTestConfiguration.CollectionNamespace.CollectionName);

            var docs = new List<A>();
            docs.Add(new A { PropA = 1 });
            docs.Add(new A { PropA = 2 });
            docs.Add(new A { PropA = 3 });
            docs.Add(new B { PropA = 4, PropB = 1 });
            docs.Add(new B { PropA = 5, PropB = 2 });
            docs.Add(new B { PropA = 6, PropB = 3 });
            docs.Add(new C { PropA = 7, PropB = 4, PropC = 1 });
            docs.Add(new C { PropA = 8, PropB = 5, PropC = 2 });
            docs.Add(new C { PropA = 9, PropB = 6, PropC = 3 });

            _rootCollection.InsertMany(docs);
        }

        [Theory]
        [ParameterAttributeData]
        public void Count_should_only_count_derived_types(
            [Values(false, true)] bool async)
        {
            var subject = CreateSubject();

            long result1, result2;
            if (async)
            {
                result1 = subject.CountAsync("{}").GetAwaiter().GetResult();
                result2 = subject.OfType<C>().CountAsync("{}").GetAwaiter().GetResult();
            }
            else
            {
                result1 = subject.Count("{}");
                result2 = subject.OfType<C>().Count("{}");
            }

            result1.Should().Be(6);
            result2.Should().Be(3);
        }

        [Theory]
        [ParameterAttributeData]
        public void Count_should_only_count_derived_types_with_a_filter(
            [Values(false, true)] bool async)
        {
            var subject = CreateSubject();

            long result;
            if (async)
            {
                result = subject.CountAsync(x => x.PropB > 2).GetAwaiter().GetResult();
            }
            else
            {
                result = subject.Count(x => x.PropB > 2);
            }

            result.Should().Be(4);
        }

        [Theory]
        [ParameterAttributeData]
        public void InsertOne_should_include_discriminator_when_document_is_of_type_B(
            [Values(false, true)] bool async)
        {
            var subject = CreateSubject();
            var document = new B { PropA = 10, PropB = 7 };

            if (async)
            {
                subject.InsertOneAsync(document).GetAwaiter().GetResult();
            }
            else
            {
                subject.InsertOne(document);
            }

            var insertedB = _docsCollection.FindSync("{PropA: 10}").Single();
            insertedB["_t"].Should().Be(new BsonArray(new[] { "A", "B" }));
        }

        [Theory]
        [ParameterAttributeData]
        public void InsertOne_should_include_discriminator_when_document_is_of_type_C(
            [Values(false, true)] bool async)
        {
            var subject = CreateSubject();
            var document = new C { PropA = 11, PropB = 8, PropC = 4 };

            if (async)
            {
                subject.InsertOneAsync(document).GetAwaiter().GetResult();
            }
            else
            {
                subject.InsertOne(document);
            }

            var insertedC = _docsCollection.FindSync("{PropA: 11}").Single();
            insertedC["_t"].Should().Be(new BsonArray(new[] { "A", "B", "C" }));
        }

        [Theory]
        [ParameterAttributeData]
        public void ReplaceOne_should_not_match_document_of_wrong_type(
            [Values(false, true)] bool async)
        {
            var subject = CreateSubject();
            var repacement = new B { PropA = 10, PropB = 7 };

            ReplaceOneResult result;
            if (async)
            {
                result = subject.ReplaceOneAsync("{PropA: 1}", repacement).GetAwaiter().GetResult();
            }
            else
            {
                result = subject.ReplaceOne("{PropA: 1}", repacement);
            }

            result.MatchedCount.Should().Be(0); // document matching { PropA : 1 } is not of type B
        }

        [Theory]
        [ParameterAttributeData]
        public void ReplaceOne_should_match_document_of_right_type(
            [Values(false, true)] bool async)
        {
            var subject = CreateSubject();
            var originalDocument = _docsCollection.FindSync("{ PropA : 4 }").Single();
            var replacement = new B { PropA = 10, PropB = 7 };

            ReplaceOneResult result;
            if (async)
            {
                result = subject.ReplaceOneAsync("{PropA: 4}", replacement).GetAwaiter().GetResult();
            }
            else
            {
                result = subject.ReplaceOne("{PropA: 4}", replacement);
            }

            result.MatchedCount.Should().Be(1); // document matching { PropA : 4 } is of type B
            var replacedB = _docsCollection.FindSync("{ PropA : 10 }").Single();
            replacedB.Should().Be(new BsonDocument
            {
                { "_id", originalDocument["_id"] },
                { "_t", new BsonArray { "A", "B" } },
                { "PropA", 10 },
                { "PropB", 7 }
            });
        }

        private IMongoCollection<B> CreateSubject()
        {
            return _rootCollection.OfType<B>();
        }

        [BsonDiscriminator(RootClass = true)]
        [BsonKnownTypes(typeof(B), typeof(C))]
        public class A
        {
            public int PropA;
        }

        public class B : A
        {
            public int PropB;
        }

        public class C : B
        {
            public int PropC;
        }
    }
}
Back to Top