File: DbConfigurationManagerTests.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 (761 lines) | stat: -rw-r--r-- 36,764 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
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
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

namespace System.Data.Entity.Config
{
    using System.Collections.Concurrent;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data.Entity.Internal;
    using System.Data.Entity.Resources;
    using System.Linq;
    using System.Data.Entity.TestHelpers;
    using Moq;
    using SimpleModel;
    using Xunit;

    public class DbConfigurationManagerTests : TestBase
    {
        public class Instance : TestBase
        {
            [Fact]
            public void Instance_returns_the_Singleton_instance()
            {
                Assert.NotNull(DbConfigurationManager.Instance);
                Assert.Same(DbConfigurationManager.Instance, DbConfigurationManager.Instance);
            }
        }

        public class GetConfiguration : TestBase
        {
            [Fact]
            public void GetConfiguration_returns_the_configuration_at_the_top_of_the_stack_if_overriding_configurations_have_been_pushed()
            {
                var manager = CreateManager();
                var mockInternalConfiguration = new Mock<InternalConfiguration>
                                                    {
                                                        CallBase = true
                                                    };

                var mockDbConfiguration = new Mock<DbConfiguration>();
                mockDbConfiguration.Setup(m => m.InternalConfiguration).Returns(mockInternalConfiguration.Object);
                mockInternalConfiguration.Setup(m => m.Owner).Returns(mockDbConfiguration.Object);

                var configuration = mockInternalConfiguration.Object;

                manager.SetConfiguration(configuration);
                manager.PushConfiguration(AppConfig.DefaultInstance, typeof(DbContext));

                var pushed1 = manager.GetConfiguration();
                Assert.NotSame(configuration, pushed1);

                manager.PushConfiguration(AppConfig.DefaultInstance, typeof(DbContext));

                var pushed2 = manager.GetConfiguration();
                Assert.NotSame(pushed1, pushed2);
                Assert.NotSame(configuration, pushed2);
            }

            [Fact]
            public void GetConfiguration_returns_the_previously_set_configuration()
            {
                var manager = CreateManager();
                var mockInternalConfiguration = CreateMockInternalConfiguration();

                manager.SetConfiguration(mockInternalConfiguration.Object);

                Assert.Same(mockInternalConfiguration.Object, manager.GetConfiguration());
            }

            [Fact]
            public void GetConfiguration_sets_and_returns_a_new_configuration_if_none_was_previously_set()
            {
                var manager = CreateManager();

                var configuration = manager.GetConfiguration();

                Assert.NotNull(configuration);
                Assert.Same(configuration, manager.GetConfiguration());
            }

            /// <summary>
            ///     This test makes calls from multiple threads such that we have at least some chance of finding threading
            ///     issues. As with any test of this type just because the test passes does not mean that the code is
            ///     correct. On the other hand if this test ever fails (EVEN ONCE) then we know there is a problem to
            ///     be investigated. DON'T just re-run and think things are okay if the test then passes.
            /// </summary>
            [Fact]
            public void GetConfiguration_for_default_value_can_be_called_from_multiple_threads_concurrently()
            {
                ConfigurationThreadTest(m => { }, m => { });
            }

            /// <summary>
            ///     This test makes calls from multiple threads such that we have at least some chance of finding threading
            ///     issues. As with any test of this type just because the test passes does not mean that the code is
            ///     correct. On the other hand if this test ever fails (EVEN ONCE) then we know there is a problem to
            ///     be investigated. DON'T just re-run and think things are okay if the test then passes.
            /// </summary>
            [Fact]
            public void GetConfiguration_for_pushed_config_can_be_called_from_multiple_threads_concurrently()
            {
                ConfigurationThreadTest(m => m.PushConfiguration(AppConfig.DefaultInstance, typeof(SimpleModelContext)), m => { });
            }

            /// <summary>
            ///     This test makes calls from multiple threads such that we have at least some chance of finding threading
            ///     issues. As with any test of this type just because the test passes does not mean that the code is
            ///     correct. On the other hand if this test ever fails (EVEN ONCE) then we know there is a problem to
            ///     be investigated. DON'T just re-run and think things are okay if the test then passes.
            /// </summary>
            [Fact]
            public void GetConfiguration_for_pushed_and_popped_config_can_be_called_from_multiple_threads_concurrently()
            {
                ConfigurationThreadTest(
                    m =>
                        {
                            m.PushConfiguration(AppConfig.DefaultInstance, typeof(SimpleModelContext));
                            m.PopConfiguration(AppConfig.DefaultInstance);
                        },
                    m => { });
            }
        }

        public class SetConfiguration : TestBase
        {
            [Fact]
            public void SetConfiguration_sets_and_locks_the_configuration_if_none_was_previously_set_and_config_file_has_none()
            {
                var manager = CreateManager();
                var mockInternalConfiguration = CreateMockInternalConfiguration();

                manager.SetConfiguration(mockInternalConfiguration.Object);

                Assert.Same(mockInternalConfiguration.Object, manager.GetConfiguration());

                mockInternalConfiguration.Verify(m => m.Lock());
            }

            [Fact]
            public void The_same_type_of_configuration_can_be_set_multiple_times()
            {
                var manager = CreateManager();
                var mockInternalConfiguration1 = CreateMockInternalConfiguration();
                var mockInternalConfiguration2 = CreateMockInternalConfiguration();

                manager.SetConfiguration(mockInternalConfiguration1.Object);
                manager.SetConfiguration(mockInternalConfiguration2.Object);

                Assert.Same(mockInternalConfiguration1.Object, manager.GetConfiguration());
            }

            [Fact]
            public void SetConfiguration_discards_the_given_configuration_and_uses_the_configuration_from_the_config_file_if_it_exists()
            {
                var mockLoadedConfig = CreateMockInternalConfiguration();
                var mockLoader = new Mock<DbConfigurationLoader>();
                mockLoader.Setup(m => m.AppConfigContainsDbConfigurationType(It.IsAny<AppConfig>())).Returns(true);
                mockLoader.Setup(m => m.TryLoadFromConfig(It.IsAny<AppConfig>())).Returns(mockLoadedConfig.Object);

                var manager = CreateManager(mockLoader);
                var mockConfiguration = CreateMockInternalConfiguration();

                manager.SetConfiguration(mockConfiguration.Object);

                Assert.Same(mockLoadedConfig.Object, manager.GetConfiguration());

                mockLoadedConfig.Verify(m => m.Lock());
                mockConfiguration.Verify(m => m.Lock(), Times.Never());
            }

            [Fact]
            public void SetConfiguration_throws_if_an_attempt_is_made_to_set_a_different_configuration_type()
            {
                var manager = CreateManager();

                var configuration1 = new FakeConfiguration();
                var mockInternalConfiguration1 = CreateMockInternalConfiguration(configuration1);

                var configuration2 = new Mock<DbConfiguration>().Object;
                var mockInternalConfiguration2 = CreateMockInternalConfiguration(configuration2);

                manager.SetConfiguration(mockInternalConfiguration1.Object);

                Assert.Equal(
                    Strings.ConfigurationSetTwice(configuration2.GetType().Name, configuration1.GetType().Name),
                    Assert.Throws<InvalidOperationException>(() => manager.SetConfiguration(mockInternalConfiguration2.Object)).Message);
            }

            [Fact]
            public void SetConfiguration_throws_if_an_attempt_is_made_to_set_a_configuration_after_the_default_has_already_been_used()
            {
                var manager = CreateManager();

                var dbConfiguration = new Mock<DbConfiguration>().Object;
                var mockInternalConfiguration = CreateMockInternalConfiguration(dbConfiguration);

                manager.GetConfiguration(); // Initialize default

                Assert.Equal(
                    Strings.DefaultConfigurationUsedBeforeSet(dbConfiguration.GetType().Name),
                    Assert.Throws<InvalidOperationException>(() => manager.SetConfiguration(mockInternalConfiguration.Object)).Message);
            }

            /// <summary>
            ///     This test makes calls from multiple threads such that we have at least some chance of finding threading
            ///     issues. As with any test of this type just because the test passes does not mean that the code is
            ///     correct. On the other hand if this test ever fails (EVEN ONCE) then we know there is a problem to
            ///     be investigated. DON'T just re-run and think things are okay if the test then passes.
            /// </summary>
            [Fact]
            public void SetConfiguration_can_be_called_from_multiple_threads_concurrently_and_only_one_will_win()
            {
                ConfigurationThreadTest(
                    m => { },
                    m => m.SetConfiguration(new FunctionalTestsConfiguration().InternalConfiguration));
            }
        }

        public class EnsureLoadedForContext : TestBase
        {
            [Fact]
            public void EnsureLoadedForContext_loads_configuration_from_context_assembly_if_none_was_previously_used()
            {
                var foundConfiguration = CreateMockInternalConfiguration().Object;
                var mockFinder = new Mock<DbConfigurationFinder>();
                mockFinder.Setup(m => m.TryCreateConfiguration(typeof(FakeContext), It.IsAny<IEnumerable<Type>>())).Returns(
                    foundConfiguration);

                var manager = CreateManager(null, mockFinder);

                manager.EnsureLoadedForContext(typeof(FakeContext));

                mockFinder.Verify(m => m.TryCreateConfiguration(typeof(FakeContext), It.IsAny<IEnumerable<Type>>()));
                Assert.Same(foundConfiguration, manager.GetConfiguration());
            }

            [Fact]
            public void EnsureLoadedForContext_does_not_throw_if_given_context_is_exactly_DbContext()
            {
                var mockFinder = new Mock<DbConfigurationFinder>();

                CreateManager(null, mockFinder).EnsureLoadedForContext(typeof(DbContext));

                mockFinder.Verify(m => m.TryCreateConfiguration(typeof(DbContext), It.IsAny<IEnumerable<Type>>()), Times.Never());
            }

            [Fact]
            public void EnsureLoadedForContext_does_not_throw_if_assembly_has_already_been_checked()
            {
                var mockFinder = new Mock<DbConfigurationFinder>();
                var manager = CreateManager(null, mockFinder);

                manager.EnsureLoadedForContext(typeof(FakeContext));

                mockFinder.Verify(m => m.TryCreateConfiguration(typeof(FakeContext), It.IsAny<IEnumerable<Type>>()), Times.Once());

                manager.EnsureLoadedForContext(typeof(FakeContext));

                // Finder has not been used again
                mockFinder.Verify(m => m.TryCreateConfiguration(typeof(FakeContext), It.IsAny<IEnumerable<Type>>()), Times.Once());
            }

            [Fact]
            public void EnsureLoadedForContext_does_not_throw_if_an_override_configuration_has_been_pushed()
            {
                var mockFinder = new Mock<DbConfigurationFinder>();
                var manager = CreateManager(null, mockFinder);

                manager.PushConfiguration(AppConfig.DefaultInstance, typeof(DbContext));

                mockFinder.Verify(m => m.TryCreateConfiguration(typeof(DbContext), It.IsAny<IEnumerable<Type>>()), Times.Once());

                manager.EnsureLoadedForContext(typeof(FakeContext));

                // Finder has not been used again
                mockFinder.Verify(m => m.TryCreateConfiguration(typeof(DbContext), It.IsAny<IEnumerable<Type>>()), Times.Once());
            }

            [Fact]
            public void EnsureLoadedForContext_does_not_throw_if_none_was_previously_used_and_no_configuration_is_found_in_assembly()
            {
                var mockFinder = new Mock<DbConfigurationFinder>();
                var manager = CreateManager(null, mockFinder);

                manager.EnsureLoadedForContext(typeof(FakeContext));

                mockFinder.Verify(m => m.TryCreateConfiguration(typeof(FakeContext), It.IsAny<IEnumerable<Type>>()));

                var mockInternalConfiguration = CreateMockInternalConfiguration();
                manager.SetConfiguration(mockInternalConfiguration.Object);

                Assert.Same(mockInternalConfiguration.Object, manager.GetConfiguration());
            }

            [Fact]
            public void EnsureLoadedForContext_does_not_throw_if_one_was_previously_used_but_no_configuration_is_found_in_assembly()
            {
                var mockFinder = new Mock<DbConfigurationFinder>();
                var manager = CreateManager(null, mockFinder);

                var configuration = manager.GetConfiguration();

                manager.EnsureLoadedForContext(typeof(FakeContext));

                mockFinder.Verify(m => m.TryFindConfigurationType(typeof(FakeContext), It.IsAny<IEnumerable<Type>>()));

                Assert.Same(configuration, manager.GetConfiguration());
            }

            [Fact]
            public void EnsureLoadedForContext_does_not_throw_if_one_was_previously()
            {
                var mockFinder = new Mock<DbConfigurationFinder>();

                var manager = CreateManager(null, mockFinder);

                var configuration = manager.GetConfiguration();

                manager.EnsureLoadedForContext(typeof(FakeContext));

                mockFinder.Verify(m => m.TryFindConfigurationType(typeof(FakeContext), It.IsAny<IEnumerable<Type>>()));

                Assert.Same(configuration, manager.GetConfiguration());
            }

            [Fact]
            public void EnsureLoadedForContext_does_not_throw_if_configuration_in_assembly_is_the_same_as_was_previously_used()
            {
                var mockInternalConfiguration = CreateMockInternalConfiguration();

                var configuration = mockInternalConfiguration.Object;
                var mockFinder = new Mock<DbConfigurationFinder>();
                mockFinder.Setup(m => m.TryFindConfigurationType(typeof(FakeContext), It.IsAny<IEnumerable<Type>>()))
                          .Returns(configuration.Owner.GetType());
                var manager = CreateManager(null, mockFinder);

                manager.SetConfiguration(configuration);

                manager.EnsureLoadedForContext(typeof(FakeContext));

                mockFinder.Verify(m => m.TryFindConfigurationType(typeof(FakeContext), It.IsAny<IEnumerable<Type>>()));

                Assert.Same(configuration, manager.GetConfiguration());
            }

            [Fact]
            public void EnsureLoadedForContext_throws_if_found_configuration_does_not_match_previously_used_configuration()
            {
                var mockInternalConfiguration = CreateMockInternalConfiguration();

                var mockFinder = new Mock<DbConfigurationFinder>();
                mockFinder.Setup(m => m.TryFindConfigurationType(typeof(FakeContext), It.IsAny<IEnumerable<Type>>()))
                          .Returns(typeof(FakeConfiguration));
                var manager = CreateManager(null, mockFinder);

                manager.SetConfiguration(mockInternalConfiguration.Object);

                Assert.Equal(
                    Strings.SetConfigurationNotDiscovered(mockInternalConfiguration.Object.Owner.GetType().Name, typeof(FakeContext).Name),
                    Assert.Throws<InvalidOperationException>(
                        () => manager.EnsureLoadedForContext(typeof(FakeContext))).Message);
            }

            [Fact]
            public void EnsureLoadedForContext_throws_if_configuration_is_found_but_default_was_previously_used()
            {
                var configuration = new Mock<DbConfiguration>().Object;
                var mockFinder = new Mock<DbConfigurationFinder>();
                mockFinder.Setup(m => m.TryFindConfigurationType(typeof(FakeContext), It.IsAny<IEnumerable<Type>>()))
                          .Returns(configuration.GetType());
                var manager = CreateManager(null, mockFinder);

                manager.GetConfiguration();

                Assert.Equal(
                    Strings.ConfigurationNotDiscovered(configuration.GetType().Name),
                    Assert.Throws<InvalidOperationException>(
                        () => manager.EnsureLoadedForContext(typeof(FakeContext))).Message);
            }

            [Fact]
            public void EnsureLoadedForContext_does_not_throw_if_configuration_was_set_but_is_not_found_in_context_assembly()
            {
                var configuration = CreateMockInternalConfiguration().Object;
                var mockFinder = new Mock<DbConfigurationFinder>();
                var manager = CreateManager(null, mockFinder);

                manager.SetConfiguration(configuration);

                manager.EnsureLoadedForContext(typeof(FakeContext));

                Assert.Same(configuration, manager.GetConfiguration());
            }

            [Fact]
            public void EnsureLoadedForContext_does_not_throw_if_configuration_is_specified_in_config_file()
            {
                var mockLoadedConfig = CreateMockInternalConfiguration();
                var mockLoader = new Mock<DbConfigurationLoader>();
                mockLoader.Setup(m => m.AppConfigContainsDbConfigurationType(It.IsAny<AppConfig>())).Returns(true);
                mockLoader.Setup(m => m.TryLoadFromConfig(It.IsAny<AppConfig>())).Returns(mockLoadedConfig.Object);

                var mockInternalConfiguration = CreateMockInternalConfiguration();
                var mockFinder = new Mock<DbConfigurationFinder>();
                var manager = CreateManager(mockLoader, mockFinder);

                manager.SetConfiguration(mockInternalConfiguration.Object);

                manager.EnsureLoadedForContext(typeof(FakeContext));
                Assert.Same(mockLoadedConfig.Object, manager.GetConfiguration());
            }

            [Fact]
            public void EnsureLoadedForContext_does_not_throw_even_if_finder_would_throw_if_configuration_is_specified_in_config_file()
            {
                var mockLoadedConfig = CreateMockInternalConfiguration();
                var mockLoader = new Mock<DbConfigurationLoader>();
                mockLoader.Setup(m => m.AppConfigContainsDbConfigurationType(It.IsAny<AppConfig>())).Returns(true);
                mockLoader.Setup(m => m.TryLoadFromConfig(It.IsAny<AppConfig>())).Returns(mockLoadedConfig.Object);

                var mockInternalConfiguration = CreateMockInternalConfiguration();

                var mockFinder = new Mock<DbConfigurationFinder>();
                mockFinder
                    .Setup(m => m.TryCreateConfiguration(It.IsAny<Type>(), It.IsAny<IEnumerable<Type>>()))
                    .Throws<InvalidOperationException>();
                mockFinder
                    .Setup(m => m.TryFindConfigurationType(It.IsAny<Type>(), It.IsAny<IEnumerable<Type>>()))
                    .Throws<InvalidOperationException>();

                var manager = CreateManager(mockLoader, mockFinder);
                manager.SetConfiguration(mockInternalConfiguration.Object);

                manager.EnsureLoadedForContext(typeof(FakeContext));

                Assert.Same(mockLoadedConfig.Object, manager.GetConfiguration());
            }

            /// <summary>
            ///     This test makes calls from multiple threads such that we have at least some chance of finding threading
            ///     issues. As with any test of this type just because the test passes does not mean that the code is
            ///     correct. On the other hand if this test ever fails (EVEN ONCE) then we know there is a problem to
            ///     be investigated. DON'T just re-run and think things are okay if the test then passes.
            /// </summary>
            [Fact]
            public void EnsureLoadedForContext_can_be_called_from_multiple_threads_concurrently_before_configuration_has_been_used()
            {
                ConfigurationThreadTest(
                    m => { },
                    m => m.EnsureLoadedForContext(typeof(SimpleModelContext)));
            }

            /// <summary>
            ///     This test makes calls from multiple threads such that we have at least some chance of finding threading
            ///     issues. As with any test of this type just because the test passes does not mean that the code is
            ///     correct. On the other hand if this test ever fails (EVEN ONCE) then we know there is a problem to
            ///     be investigated. DON'T just re-run and think things are okay if the test then passes.
            /// </summary>
            [Fact]
            public void EnsureLoadedForContext_can_be_called_from_multiple_threads_concurrently_after_push_and_pop()
            {
                ConfigurationThreadTest(
                    m =>
                        {
                            m.PushConfiguration(AppConfig.DefaultInstance, typeof(SimpleModelContext));
                            m.PopConfiguration(AppConfig.DefaultInstance);
                        },
                    m => m.EnsureLoadedForContext(typeof(SimpleModelContext)));
            }
        }

        public class PushConfiguration : TestBase
        {
            [Fact]
            public void PushConfugiration_pushes_and_locks_configuration_from_config_if_found()
            {
                var mockConfiguration = new Mock<InternalConfiguration>();
                var mockLoader = new Mock<DbConfigurationLoader>();
                mockLoader.Setup(m => m.TryLoadFromConfig(AppConfig.DefaultInstance)).Returns(mockConfiguration.Object);
                mockLoader.Setup(m => m.AppConfigContainsDbConfigurationType(It.IsAny<AppConfig>())).Returns(true);
                var mockFinder = new Mock<DbConfigurationFinder>();

                var manager = CreateManager(mockLoader, mockFinder);

                manager.PushConfiguration(AppConfig.DefaultInstance, typeof(DbContext));

                mockConfiguration.Verify(m => m.Lock());
                Assert.Same(mockConfiguration.Object, manager.GetConfiguration());
                mockLoader.Verify(m => m.TryLoadFromConfig(AppConfig.DefaultInstance));
                mockFinder.Verify(m => m.TryCreateConfiguration(typeof(DbContext), It.IsAny<IEnumerable<Type>>()), Times.Never());
            }

            [Fact]
            public void PushConfugiration_pushes_and_locks_configuration_discovered_in_context_assembly_if_found()
            {
                var mockConfiguration = new Mock<InternalConfiguration>();
                var mockLoader = new Mock<DbConfigurationLoader>();
                var mockFinder = new Mock<DbConfigurationFinder>();
                mockFinder.Setup(m => m.TryCreateConfiguration(typeof(DbContext), It.IsAny<IEnumerable<Type>>())).Returns(
                    mockConfiguration.Object);

                var manager = CreateManager(mockLoader, mockFinder);

                manager.PushConfiguration(AppConfig.DefaultInstance, typeof(DbContext));

                mockConfiguration.Verify(m => m.Lock());
                Assert.Same(mockConfiguration.Object, manager.GetConfiguration());
                mockLoader.Verify(m => m.TryLoadFromConfig(AppConfig.DefaultInstance));
                mockFinder.Verify(m => m.TryCreateConfiguration(typeof(DbContext), It.IsAny<IEnumerable<Type>>()));
            }

            [Fact]
            public void PushConfugiration_pushes_default_configuration_if_no_other_found()
            {
                var mockLoader = new Mock<DbConfigurationLoader>();
                var mockFinder = new Mock<DbConfigurationFinder>();

                var manager = CreateManager(mockLoader, mockFinder);

                var defaultConfiguration = manager.GetConfiguration();

                manager.PushConfiguration(AppConfig.DefaultInstance, typeof(DbContext));

                Assert.NotSame(defaultConfiguration, manager.GetConfiguration());
                mockLoader.Verify(m => m.TryLoadFromConfig(AppConfig.DefaultInstance));
                mockFinder.Verify(m => m.TryCreateConfiguration(typeof(DbContext), It.IsAny<IEnumerable<Type>>()));
            }

            [Fact]
            public void AppConfigResolver_is_added_to_pushed_configuration()
            {
                var mockConfiguration = new Mock<InternalConfiguration>();
                var mockLoader = new Mock<DbConfigurationLoader>();
                mockLoader.Setup(m => m.TryLoadFromConfig(AppConfig.DefaultInstance)).Returns(mockConfiguration.Object);
                mockLoader.Setup(m => m.AppConfigContainsDbConfigurationType(It.IsAny<AppConfig>())).Returns(true);

                CreateManager(mockLoader).PushConfiguration(AppConfig.DefaultInstance, typeof(DbContext));

                mockConfiguration.Verify(m => m.AddAppConfigResolver(It.IsAny<AppConfigDependencyResolver>()));
            }

            [Fact]
            public void PushConfugiration_switches_in_original_root_resolver()
            {
                var mockConfiguration = new Mock<InternalConfiguration>();
                var mockLoader = new Mock<DbConfigurationLoader>();
                mockLoader.Setup(m => m.TryLoadFromConfig(AppConfig.DefaultInstance)).Returns(mockConfiguration.Object);
                mockLoader.Setup(m => m.AppConfigContainsDbConfigurationType(It.IsAny<AppConfig>())).Returns(true);

                var manager = CreateManager(mockLoader);
                var defaultConfiguration = manager.GetConfiguration();

                manager.PushConfiguration(AppConfig.DefaultInstance, typeof(DbContext));

                mockConfiguration.Verify(m => m.SwitchInRootResolver(defaultConfiguration.RootResolver));
            }

            /// <summary>
            ///     This test makes calls from multiple threads such that we have at least some chance of finding threading
            ///     issues. As with any test of this type just because the test passes does not mean that the code is
            ///     correct. On the other hand if this test ever fails (EVEN ONCE) then we know there is a problem to
            ///     be investigated. DON'T just re-run and think things are okay if the test then passes.
            /// </summary>
            [Fact]
            public void Configurations_can_be_pushed_and_popped_from_multiple_threads_concurrently()
            {
                for (var i = 0; i < 30; i++)
                {
                    var manager = new DbConfigurationManager(new DbConfigurationLoader(), new DbConfigurationFinder());
                    var config = manager.GetConfiguration();

                    ExecuteInParallel(
                        () =>
                            {
                                var appConfig = new AppConfig(new ConnectionStringSettingsCollection());
                                manager.PushConfiguration(appConfig, typeof(SimpleModelContext));
                                manager.PopConfiguration(appConfig);
                            });

                    Assert.Same(config, manager.GetConfiguration());
                }
            }
        }

        public class PopConfiguration : TestBase
        {
            [Fact]
            public void PopConfiguration_removes_the_first_configuration_associated_with_the_given_AppConfig()
            {
                var manager = CreateManager();
                var mockInternalConfiguration = new Mock<InternalConfiguration>
                                                    {
                                                        CallBase = true
                                                    };

                var mockDbConfiguration = new Mock<DbConfiguration>();
                mockDbConfiguration.Setup(m => m.InternalConfiguration).Returns(mockInternalConfiguration.Object);
                mockInternalConfiguration.Setup(m => m.Owner).Returns(mockDbConfiguration.Object);

                var appConfig1 = AppConfig.DefaultInstance;
                var appConfig2 = new AppConfig(ConfigurationManager.ConnectionStrings);

                manager.SetConfiguration(mockInternalConfiguration.Object);

                manager.PushConfiguration(appConfig1, typeof(DbContext));
                var pushed1 = manager.GetConfiguration();
                manager.PushConfiguration(appConfig2, typeof(DbContext));

                manager.PopConfiguration(appConfig2);
                Assert.Same(pushed1, manager.GetConfiguration());

                manager.PopConfiguration(appConfig1);
                Assert.Same(mockInternalConfiguration.Object, manager.GetConfiguration());
            }

            [Fact]
            public void PopConfiguration_does_nothing_if_no_configuration_is_associated_with_the_given_AppConfig()
            {
                var manager = CreateManager();

                manager.PushConfiguration(AppConfig.DefaultInstance, typeof(DbContext));
                var pushed1 = manager.GetConfiguration();

                manager.PopConfiguration(new AppConfig(ConfigurationManager.ConnectionStrings));
                Assert.Same(pushed1, manager.GetConfiguration());
            }
        }

        public class AddOnLockingHandler
        {
            [Fact]
            public void Adding_handler_after_configuration_is_in_use_throws()
            {
                var manager = CreateManager();
                manager.GetConfiguration();

                Assert.Equal(
                    Strings.AddHandlerToInUseConfiguration,
                    Assert.Throws<InvalidOperationException>(() => manager.AddOnLockingHandler((_, __) => { })).Message);
            }
        }

        public class OnLocking
        {
            private readonly IDbDependencyResolver _snapshot;
            private readonly Mock<InternalConfiguration> _configuration;

            public OnLocking()
            {
                _snapshot = new Mock<IDbDependencyResolver>().Object;
                _configuration = CreateMockInternalConfiguration(null, _snapshot);
            }

            [Fact]
            public void OnLocking_calls_all_added_handlers_and_passes_in_correct_configuration()
            {
                var manager = CreateManager();

                manager.OnLocking(_configuration.Object); // No throw when no handlers registered

                manager.AddOnLockingHandler(Handler1);
                manager.AddOnLockingHandler(Handler2);
                manager.AddOnLockingHandler(Handler3);

                manager.OnLocking(_configuration.Object);
                Assert.Equal(1, Handler1Called);
                Assert.Equal(1, Handler2Called);
                Assert.Equal(1, Handler3Called);

                manager.RemoveOnLockingHandler(Handler2);

                manager.OnLocking(_configuration.Object);
                Assert.Equal(2, Handler1Called);
                Assert.Equal(1, Handler2Called);
                Assert.Equal(2, Handler3Called);
            }

            private int Handler1Called { get; set; }

            private void Handler1(object sender, DbConfigurationEventArgs args)
            {
                Assert.Same(_configuration.Object.Owner, sender);
                Assert.Same(_snapshot, args.ResolverSnapshot);
                Handler1Called++;
            }

            private int Handler2Called { get; set; }

            private void Handler2(object sender, DbConfigurationEventArgs args)
            {
                Assert.Same(_configuration.Object.Owner, sender);
                Assert.Same(_snapshot, args.ResolverSnapshot);
                Handler2Called++;
            }

            private int Handler3Called { get; set; }

            private void Handler3(object sender, DbConfigurationEventArgs args)
            {
                Assert.Same(_configuration.Object.Owner, sender);
                Assert.Same(_snapshot, args.ResolverSnapshot);
                Handler3Called++;
            }
        }

        private static DbConfigurationManager CreateManager(
            Mock<DbConfigurationLoader> mockLoader = null,
            Mock<DbConfigurationFinder> mockFinder = null)
        {
            return new DbConfigurationManager(
                (mockLoader ?? new Mock<DbConfigurationLoader>()).Object,
                (mockFinder ?? new Mock<DbConfigurationFinder>()).Object);
        }

        public class FakeConfiguration : DbConfiguration
        {
        }

        public class FakeContext : DbContext
        {
        }

        private static Mock<InternalConfiguration> CreateMockInternalConfiguration(
            DbConfiguration dbConfiguration = null, IDbDependencyResolver snapshot = null)
        {
            var mockInternalConfiguration = new Mock<InternalConfiguration>();

            if (dbConfiguration == null)
            {
                var mockDbConfiguration = new Mock<DbConfiguration>();
                mockDbConfiguration.Setup(m => m.InternalConfiguration).Returns(mockInternalConfiguration.Object);
                dbConfiguration = mockDbConfiguration.Object;
            }

            mockInternalConfiguration.Setup(m => m.Owner).Returns(dbConfiguration);
            mockInternalConfiguration.Setup(m => m.ResolverSnapshot).Returns(snapshot);

            return mockInternalConfiguration;
        }

        private static void ConfigurationThreadTest(Action<DbConfigurationManager> beforeThreads, Action<DbConfigurationManager> inThreads)
        {
            for (var i = 0; i < 30; i++)
            {
                var configurationBag = new ConcurrentBag<InternalConfiguration>();
                var manager = new DbConfigurationManager(new DbConfigurationLoader(), new DbConfigurationFinder());
                manager.SetConfiguration(new FunctionalTestsConfiguration().InternalConfiguration);
                beforeThreads(manager);

                ExecuteInParallel(
                    () =>
                        {
                            inThreads(manager);
                            configurationBag.Add(manager.GetConfiguration());
                        });

                Assert.Equal(20, configurationBag.Count);
                Assert.True(configurationBag.All(c => manager.GetConfiguration() == c));
            }
        }
    }
}