File: MultiThreadingTests.cs

package info (click to toggle)
mono 3.2.8%2Bdfsg-10
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 527,964 kB
  • ctags: 623,327
  • sloc: cs: 3,938,236; xml: 1,891,753; ansic: 418,737; java: 59,920; sh: 15,754; makefile: 11,067; sql: 7,956; perl: 2,279; cpp: 1,380; yacc: 1,203; python: 594; asm: 422; sed: 16; php: 1
file content (732 lines) | stat: -rw-r--r-- 26,895 bytes parent folder | download | duplicates (2)
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
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

namespace ProductivityApiUnitTests
{
    using System;
    using System.Collections.Generic;
    using System.Data.Entity;
    using System.Data.Entity.Core.EntityClient;
    using System.Data.Entity.Core.Objects;
    using System.Data.Entity.Infrastructure;
    using System.Data.Entity.Internal;
    using System.Data.Entity.Internal.Linq;
    using System.Threading.Tasks;
    using Moq;
    using Xunit;

    /// <summary>
    ///     Unit tests that execute the various places where we have thread-safe code with multiple threads
    ///     such that we have at least some chance of finding issues in this code. As with any test of this
    ///     type just because these tests pass does not mean that the code is correct. On the other hand,
    ///     if any test ever fails (EVEN ONCE) then we know there is a problem to be investigated.
    /// </summary>
    public class MultiThreadingTests : TestBase
    {
        #region Access to cached property type/getter/setter delegates

        [Fact]
        public void DbHelpers_GetPropertyTypes_can_be_accessed_from_multiple_threads_concurrently()
        {
            ExecuteInParallel(
                () =>
                    {
                        var types = DbHelpers.GetPropertyTypes(typeof(TypeWithALotOfProperties));

                        Assert.Equal(50, types.Count);
                        Assert.Equal(typeof(string), types["Property3"]);
                        Assert.Equal(typeof(int), types["Property26"]);
                    });
        }

        [Fact]
        public void DbHelpers_GetPropertySetters_can_be_accessed_from_multiple_threads_concurrently()
        {
            ExecuteInParallel(
                () =>
                    {
                        var setters = DbHelpers.GetPropertySetters(typeof(TypeWithALotOfProperties));

                        Assert.Equal(40, setters.Count);

                        var testType = new TypeWithALotOfProperties();

                        setters["Property10"](testType, "UnicornsOnTheRun");
                        Assert.Equal("UnicornsOnTheRun", testType.Property10);

                        setters["Property47"](testType, "UnicornNeXTcube");
                        Assert.Equal("UnicornNeXTcube", testType.Property47);
                    });
        }

        [Fact]
        public void DbHelpers_GetPropertyGetters_can_be_accessed_from_multiple_threads_concurrently()
        {
            ExecuteInParallel(
                () =>
                    {
                        var getters = DbHelpers.GetPropertyGetters(typeof(TypeWithALotOfProperties));

                        var testType = new TypeWithALotOfProperties();

                        Assert.Equal(47, getters.Count);
                        Assert.Equal("Hello", getters["Property3"](testType));
                        Assert.Equal(77, getters["Property26"](testType));
                    });
        }

        #endregion

        #region Access to cached ObjectContext constructor delegates

        public class DummyObjectContext : ObjectContext
        {
            public DummyObjectContext(EntityConnection connection)
                : base(connection)
            {
            }
        }

        [Fact]
        public void DbCompiledModel_GetConstructorDelegate_can_be_accessed_from_multiple_threads_concurrently()
        {
            DbCompiledModel_GetConstructorDelegate_can_be_accessed_from_multiple_threads_concurrently_implementation<DummyObjectContext>();
        }

        [Fact]
        public void DbCompiledModel_GetConstructorDelegate_for_non_derived_ObjectContext_can_be_accessed_from_multiple_threads_concurrently(
            
            )
        {
            DbCompiledModel_GetConstructorDelegate_can_be_accessed_from_multiple_threads_concurrently_implementation<ObjectContext>();
        }

        private void DbCompiledModel_GetConstructorDelegate_can_be_accessed_from_multiple_threads_concurrently_implementation<TContext>()
            where TContext : ObjectContext
        {
            ExecuteInParallel(
                () =>
                    {
                        var constructor = DbCompiledModel.GetConstructorDelegate<TContext>();

                        try
                        {
                            // We can't make an ObjectContext inexpensively so we don't want to make a real one
                            // in a unit test, therefore we just pass null and check for the exception.
                            constructor(null);
                            Assert.True(false);
                        }
                        catch (ArgumentNullException ex)
                        {
                            Assert.Equal("connection", ex.ParamName);
                        }
                    });
        }

        #endregion

        #region Setting and calling database initializers for a context type

        // This is used instead of a Moq initializer in cases where the initializer is called multiple times
        // from different threads because the Moq initializer is not thread-safe.
        public class ThreadSafeCountingInitializer<TContext> : IDatabaseInitializer<TContext>
            where TContext : DbContext
        {
            private readonly object _lock = new object();
            private readonly bool _throwFoFirstFive;

            public ThreadSafeCountingInitializer(bool throwFoFirstFive = false)
            {
                _throwFoFirstFive = throwFoFirstFive;
            }

            public int Count { get; set; }

            public void InitializeDatabase(TContext context)
            {
                lock (_lock)
                {
                    Count++;

                    if (_throwFoFirstFive && Count <= 5)
                    {
                        throw new Exception("Fail!");
                    }
                }
            }
        }

        public class ContextForSettingInitializer : DbContextUsingMockInternalContext
        {
        }

        [Fact]
        public void Database_initializer_can_be_set_by_multiple_threads()
        {
            var countingInitializer = new ThreadSafeCountingInitializer<ContextForSettingInitializer>();

            ExecuteInParallel(() => Database.SetInitializer(countingInitializer));

            GetDatabaseForInitialization<ContextForSettingInitializer>().Initialize(force: false);

            Assert.Equal(1, countingInitializer.Count);
        }

        private Database GetDatabaseForInitialization<TContext>() where TContext : DbContextUsingMockInternalContext, new()
        {
            var mock = new Mock<InternalContextForMockWithRealContext<TContext>>
                           {
                               CallBase = true
                           };
            mock.Setup(c => c.UseTempObjectContext()).Callback(() => { });
            return new Database(mock.Object);
        }

        public class ContextForCallingInitializer : DbContextUsingMockInternalContext
        {
        }

        [Fact]
        public void Database_Initialize_without_force_can_be_called_by_multiple_threads_and_initialization_only_happens_once()
        {
            var countingInitializer = new ThreadSafeCountingInitializer<ContextForCallingInitializer>();
            Database.SetInitializer(countingInitializer);

            ExecuteInParallel(() => GetDatabaseForInitialization<ContextForCallingInitializer>().Initialize(force: false));

            Assert.Equal(1, countingInitializer.Count);
        }

        public class ContextForCallingInitializerWithForce : DbContextUsingMockInternalContext
        {
        }

        [Fact]
        public void Database_Initialize_with_force_can_be_called_by_multiple_threads_and_initialization_happens_every_time()
        {
            var countingInitializer = new ThreadSafeCountingInitializer<ContextForCallingInitializerWithForce>();
            Database.SetInitializer(countingInitializer);

            ExecuteInParallel(() => GetDatabaseForInitialization<ContextForCallingInitializerWithForce>().Initialize(force: true));

            Assert.Equal(20, countingInitializer.Count);
        }

        public class ContextForCallingInitializerWithFailures : DbContextUsingMockInternalContext
        {
        }

        [Fact]
        public void
            Database_Initialize_without_force_can_be_called_by_multiple_threads_and_initialization_is_attempted_until_one_thread_succeeds()
        {
            var countingInitializer = new ThreadSafeCountingInitializer<ContextForCallingInitializerWithFailures>(throwFoFirstFive: true);
            Database.SetInitializer(countingInitializer);

            try
            {
                ExecuteInParallel(() => GetDatabaseForInitialization<ContextForCallingInitializerWithFailures>().Initialize(force: false));
            }
            catch (AggregateException ex)
            {
                Assert.Equal(5, ex.InnerExceptions.Count);
                foreach (var innerException in ex.InnerExceptions)
                {
                    Assert.Equal("Fail!", innerException.Message);
                }
            }

            Assert.Equal(6, countingInitializer.Count);
        }

        #endregion

        #region Using DbSet discovery from multiple threads

        public class ContextForSetDiscovery : DbContext
        {
            // Having a lot of sets makes it more likely that the discovery
            // service will be running concurrently in two threads.
            public DbSet<FakeEntity> Set1 { get; set; }
            public DbSet<FakeEntity> Set2 { get; set; }
            public DbSet<FakeEntity> Set3 { get; set; }
            public DbSet<FakeEntity> Set4 { get; set; }
            public DbSet<FakeEntity> Set5 { get; set; }
            public DbSet<FakeEntity> Set6 { get; set; }
            public DbSet<FakeEntity> Set7 { get; set; }
            public DbSet<FakeEntity> Set8 { get; set; }
            public DbSet<FakeEntity> Set9 { get; set; }
            public DbSet<FakeEntity> Set10 { get; set; }
            public DbSet<FakeEntity> Set11 { get; set; }
            public DbSet<FakeEntity> Set12 { get; set; }
            public DbSet<FakeEntity> Set13 { get; set; }
            public DbSet<FakeEntity> Set14 { get; set; }
            public DbSet<FakeEntity> Set15 { get; set; }
            public DbSet<FakeEntity> Set16 { get; set; }
            public DbSet<FakeEntity> Set17 { get; set; }
            public DbSet<FakeEntity> Set18 { get; set; }
            public DbSet<FakeEntity> Set19 { get; set; }
            public DbSet<FakeEntity> Set20 { get; set; }
            public DbSet<FakeEntity> Set21 { get; set; }
            public DbSet<FakeEntity> Set22 { get; set; }
            public DbSet<FakeEntity> Set23 { get; set; }
            public DbSet<FakeEntity> Set24 { get; set; }
            public DbSet<FakeEntity> Set25 { get; set; }
            public DbSet<FakeEntity> Set26 { get; set; }
            public DbSet<FakeEntity> Set27 { get; set; }
            public DbSet<FakeEntity> Set28 { get; set; }
            public DbSet<FakeEntity> Set29 { get; set; }
            public DbSet<FakeEntity> Set30 { get; set; }
        }

        [Fact]
        public void Set_discovery_can_be_called_from_multiple_threads_at_the_same_time()
        {
            ExecuteInParallel(
                () =>
                    {
                        using (var context = new ContextForSetDiscovery())
                        {
                            new DbSetDiscoveryService(context).InitializeSets();
                            Assert.NotNull(context.Set1);
                            Assert.NotNull(context.Set30);
                        }
                    });
        }

        #endregion

        #region Various factory methods called from multiple threads

        [Fact]
        public void DbMemberEntry_Create_can_be_called_from_multiple_threads()
        {
            ExecuteInParallel(
                () =>
                    {
                        var collectionMetadata = new NavigationEntryMetadata(
                            typeof(FakeWithProps), typeof(FakeEntity), "Collection", isCollection: true);
                        var internalEntry =
                            new InternalCollectionEntry(
                                new Mock<InternalEntityEntryForMock<FakeEntity>>().Object, collectionMetadata);

                        var entry = internalEntry.CreateDbMemberEntry<FakeWithProps, ICollection<FakeEntity>>();

                        Assert.IsAssignableFrom<DbMemberEntry<FakeWithProps, ICollection<FakeEntity>>>(entry);
                    });
        }

        [Fact]
        public void InternalPropertyValues_ToObject_for_entity_type_can_be_called_from_multiple_threads()
        {
            ExecuteInParallel(
                () =>
                    {
                        var values = new TestInternalPropertyValues<DbPropertyValuesTests.FakeTypeWithProps>(null, isEntityValues: true);
                        values.MockInternalContext.Setup(c => c.CreateObject(typeof(DbPropertyValuesTests.FakeTypeWithProps))).Returns(
                            new DbPropertyValuesTests.FakeDerivedTypeWithProps());

                        var clone = values.ToObject();

                        Assert.IsType<DbPropertyValuesTests.FakeDerivedTypeWithProps>(clone);
                    });
        }

        [Fact]
        public void InternalPropertyValues_ToObject_for_non_entity_type_can_be_called_from_multiple_threads()
        {
            ExecuteInParallel(
                () =>
                    {
                        var values = new TestInternalPropertyValues<DbPropertyValuesTests.FakeTypeWithProps>(null, isEntityValues: true);
                        values.MockInternalContext.Setup(c => c.CreateObject(typeof(DbPropertyValuesTests.FakeTypeWithProps))).Returns(
                            new DbPropertyValuesTests.FakeDerivedTypeWithProps());

                        var clone = values.ToObject();

                        Assert.IsType<DbPropertyValuesTests.FakeDerivedTypeWithProps>(clone);
                    });
        }

        [Fact]
        public void Non_generic_DbSet_creation_can_be_called_from_multiple_threads()
        {
            ExecuteInParallel(
                () =>
                    {
                        var internalContext = new Mock<InternalContextForMock>
                                                  {
                                                      CallBase = true
                                                  }.Object;
                        var set = internalContext.Set(typeof(FakeEntity));
                        Assert.IsType<InternalDbSet<FakeEntity>>(set);
                    });
        }

        [Fact]
        public void ObjectContextTypeCache_GetObjectType_can_be_called_from_multiple_threads()
        {
            ExecuteInParallel(
                () =>
                    {
                        var type = ObjectContextTypeCache.GetObjectType(typeof(FakeEntity));

                        Assert.Same(typeof(FakeEntity), type);
                    });
        }

        #endregion

        #region RetryLazy tests

        [Fact]
        public void RetryLazy_only_runs_the_lazy_initializer_once_even_when_called_from_multiple_threads()
        {
            var count = 0;
            var lockObject = new object();
            var initializer = new RetryLazy<string, string>(
                i =>
                    {
                        // Locking here to ensure that count is incremented correctly even if RetryLazy isn't working correctly.
                        lock (lockObject)
                        {
                            count++;
                            return "";
                        }
                    });
            ExecuteInParallel(() => initializer.GetValue(""));
            Assert.Equal(1, count);
        }

        [Fact]
        public void RetryLazy_keeps_trying_to_initialize_until_an_attempt_succeeds()
        {
            var count = 0;
            var lockObject = new object();
            var initializer = new RetryLazy<string, string>(
                i =>
                    {
                        // Locking here to ensure that count is incremented correctly even if RetryLazy isn't working correctly.
                        lock (lockObject)
                        {
                            count++;
                            if (count <= 5)
                            {
                                throw new Exception("Fail!");
                            }
                            return "";
                        }
                    });

            try
            {
                ExecuteInParallel(() => initializer.GetValue(""));
            }
            catch (AggregateException ex)
            {
                Assert.Equal(5, ex.InnerExceptions.Count);
                foreach (var innerException in ex.InnerExceptions)
                {
                    Assert.Equal("Fail!", innerException.Message);
                }
            }
            Assert.Equal(6, count);
        }

        public class InitializerOutput
        {
            public int Input { get; set; }
            public int Count { get; set; }
        }

        [Fact]
        public void RetryLazy_uses_the_given_input_for_each_attempt_at_initialization_until_an_attempt_succeeds()
        {
            var count = 0;
            var lockObject = new object();
            InitializerOutput result = null;
            var inputs = new List<int>();

            var initializer = new RetryLazy<int, InitializerOutput>(
                i =>
                    {
                        // Locking here to ensure that count is incremented correctly even if RetryLazy isn't working correctly.
                        lock (lockObject)
                        {
                            inputs.Add(i);
                            count++;
                            if (count <= 5)
                            {
                                throw new Exception("Fail!");
                            }
                            return new InitializerOutput
                                       {
                                           Input = i,
                                           Count = count
                                       };
                        }
                    });

            var tests = new Action[20];
            for (var i = 0; i < 20; i++)
            {
                var outside = i; // Make sure i is used from outside the closure
                tests[i] = () => result = initializer.GetValue(outside);
            }

            try
            {
                Parallel.Invoke(tests);
            }
            catch (AggregateException ex)
            {
                Assert.Equal(5, ex.InnerExceptions.Count);
            }

            Assert.Equal(6, count);
            Assert.Equal(6, result.Count);
            Assert.Equal(6, inputs.Count);
            Assert.Equal(inputs[5], result.Input);

            for (var i = 0; i < inputs.Count; i++)
            {
                for (var j = 0; j < inputs.Count; j++)
                {
                    if (i != j)
                    {
                        Assert.NotEqual(inputs[i], inputs[j]);
                    }
                }
            }
        }

        #endregion

        #region RetryAction tests

        [Fact]
        public void RetryAction_only_runs_the_action_once_even_when_called_from_multiple_threads()
        {
            var count = 0;
            var lockObject = new object();
            var initializer = new RetryAction<string>(
                i =>
                    {
                        // Locking here to ensure that count is incremented correctly even if RetryAction isn't working correctly.
                        lock (lockObject)
                        {
                            count++;
                        }
                    });
            ExecuteInParallel(() => initializer.PerformAction(""));
            Assert.Equal(1, count);
        }

        [Fact]
        public void RetryAction_keeps_trying_to_run_the_action_until_an_attempt_succeeds()
        {
            var count = 0;
            var lockObject = new object();
            var initializer = new RetryAction<string>(
                i =>
                    {
                        // Locking here to ensure that count is incremented correctly even if RetryAction isn't working correctly.
                        lock (lockObject)
                        {
                            count++;
                            if (count <= 5)
                            {
                                throw new Exception("Fail!");
                            }
                        }
                    });

            try
            {
                ExecuteInParallel(() => initializer.PerformAction(""));
            }
            catch (AggregateException ex)
            {
                Assert.Equal(5, ex.InnerExceptions.Count);
                foreach (var innerException in ex.InnerExceptions)
                {
                    Assert.Equal("Fail!", innerException.Message);
                }
            }
            Assert.Equal(6, count);
        }

        public void RetryAction_uses_the_given_input_for_each_attempt_until_an_attempt_succeeds()
        {
            var count = 0;
            var lockObject = new object();
            var inputs = new List<int>();

            var initializer = new RetryAction<int>(
                i =>
                    {
                        // Locking here to ensure that count is incremented correctly even if RetryAction isn't working correctly.
                        lock (lockObject)
                        {
                            inputs.Add(i);
                            count++;
                            if (count <= 5)
                            {
                                throw new Exception("Fail!");
                            }
                        }
                    });

            var tests = new Action[20];
            for (var i = 0; i < 20; i++)
            {
                var outside = i; // Make sure i is used from outside the closure
                tests[i] = () => initializer.PerformAction(outside);
            }

            try
            {
                Parallel.Invoke(tests);
            }
            catch (AggregateException ex)
            {
                Assert.Equal(5, ex.InnerExceptions.Count);
            }

            Assert.Equal(6, count);
            Assert.Equal(6, inputs.Count);

            for (var i = 0; i < inputs.Count; i++)
            {
                for (var j = 0; j < inputs.Count; j++)
                {
                    if (i != j)
                    {
                        Assert.NotEqual(inputs[i], inputs[j]);
                    }
                }
            }
        }

        #endregion
    }

    #region

    public class TypeWithALotOfProperties
    {
        public int Property0 { get; set; }
        private byte Property1 { get; set; }

        protected int Property2
        {
            get { return 0; }
        }

        public string Property3
        {
            get { return "Hello"; }
        }

        public int Property4 { get; set; }
        public object Property5 { get; set; }
        internal int Property6 { get; set; }
        public int Property7 { get; set; }
        public int Property8 { get; set; }
        public int Property9 { get; set; }
        public string Property10 { get; set; }
        protected int Property11 { get; set; }
        private int Property12 { get; set; }
        public int Property13 { get; set; }
        public byte Property14 { get; set; }

        internal int Property15
        {
            set { }
        }

        private int Property16 { get; set; }
        public object Property17 { get; set; }
        public int Property18 { get; set; }
        public int Property19 { get; set; }

        public string Property20
        {
            get { return ""; }
        }

        public int Property21 { get; set; }

        public int Property22
        {
            get { return 0; }
        }

        private int Property23 { get; set; }
        private string Property24 { get; set; }
        public int Property25 { get; set; }

        public int Property26
        {
            get { return 77; }
        }

        protected long Property27 { get; set; }
        public int Property28 { get; set; }
        private int Property29 { get; set; }

        protected string Property30
        {
            set { }
        }

        protected int Property31 { get; set; }
        private int Property32 { get; set; }
        public object Property33 { get; set; }

        internal int Property34
        {
            get { return 0; }
        }

        public string Property35
        {
            get { return ""; }
        }

        public int Property36 { get; set; }
        protected int Property37 { get; set; }

        public int Property38
        {
            get { return 0; }
        }

        public byte Property39 { get; set; }

        protected int Property40
        {
            get { return 0; }
        }

        public object Property41
        {
            get { return null; }
        }

        public int Property42 { get; set; }
        protected string Property43 { get; set; }
        public int Property44 { get; set; }

        public byte Property45
        {
            set { }
        }

        public byte Property46 { get; set; }
        public string Property47 { get; set; }
        public object Property48 { get; set; }
        public int Property49 { get; set; }
    }

    #endregion
}