File: DictionaryHelper.cs

package info (click to toggle)
mono 6.12.0.199%2Bdfsg-6
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 1,296,836 kB
  • sloc: cs: 11,181,803; xml: 2,850,076; ansic: 699,709; cpp: 123,344; perl: 59,361; javascript: 30,841; asm: 21,853; makefile: 20,405; sh: 15,009; python: 4,839; pascal: 925; sql: 859; sed: 16; php: 1
file content (519 lines) | stat: -rw-r--r-- 21,132 bytes parent folder | download | duplicates (11)
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
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.

using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Assert = Microsoft.TestCommon.AssertEx;

namespace System.Web.TestUtil
{
    public class DictionaryHelper<TKey, TValue>
    {
        public IEqualityComparer<TKey> Comparer { get; set; }

        public Func<IDictionary<TKey, TValue>> Creator { get; set; }

        public IList<TKey> SampleKeys { get; set; }

        public IList<TValue> SampleValues { get; set; }

        public bool SkipItemPropertyTest { get; set; }

        public bool ThrowOnKeyNotFound { get; set; }

        public void Execute()
        {
            ValidateProperties();

            Executor executor = new Executor()
            {
                Comparer = Comparer,
                Creator = Creator,
                ThrowOnKeyNotFound = ThrowOnKeyNotFound,
                Values = SampleValues.ToArray()
            };
            SeparateKeys(out executor.ExcludedKey, out executor.ConflictingKeys, out executor.NonConflictingKeys);

            executor.TestAdd1();
            executor.TestAdd1ThrowsArgumentExceptionIfKeyAlreadyInDictionary();
            executor.TestAdd2();
            executor.TestClear();
            executor.TestContains();
            executor.TestContainsKey();
            executor.TestCopyTo();
            executor.TestCountProperty();
            executor.TestGetEnumerator();
            executor.TestGetEnumeratorGeneric();
            executor.TestIsReadOnlyProperty();

            if (!SkipItemPropertyTest)
            {
                executor.TestItemProperty();
            }

            executor.TestKeysProperty();
            executor.TestRemove1();
            executor.TestRemove2();
            executor.TestTryGetValue();
            executor.TestValuesProperty();
        }

        private void SeparateKeys(out TKey excludedKey, out TKey[] conflictingKeys, out TKey[] nonConflictingKeys)
        {
            List<TKey> nonConflictingKeyList = new List<TKey>();
            TKey[] newConflictingKeys = null;

            var keyLookup = SampleKeys.ToLookup(key => key, Comparer);
            foreach (var entry in keyLookup)
            {
                if (entry.Count() == 1)
                {
                    // not a conflict
                    nonConflictingKeyList.AddRange(entry);
                }
                else
                {
                    // conflict
                    newConflictingKeys = entry.ToArray();
                }
            }

            excludedKey = nonConflictingKeyList[nonConflictingKeyList.Count - 1];
            nonConflictingKeyList.RemoveAt(nonConflictingKeyList.Count - 1);
            conflictingKeys = newConflictingKeys;
            nonConflictingKeys = nonConflictingKeyList.ToArray();
        }

        private void ValidateProperties()
        {
            if (Creator == null)
            {
                throw new InvalidOperationException("The Creator property must not be null.");
            }
            if (SampleKeys == null || SampleKeys.Count < 4)
            {
                throw new InvalidOperationException("The SampleKeys property must contain at least 4 elements.");
            }
            if (SampleValues == null || SampleValues.Count != SampleKeys.Count)
            {
                throw new InvalidOperationException("The SampleValues property must contain as many elements as the SampleKeys property.");
            }

            HashSet<TKey> keys = new HashSet<TKey>(SampleKeys, Comparer);
            if (keys.Count != SampleKeys.Count - 1)
            {
                throw new InvalidOperationException("The SampleKeys property must contain exactly one colliding keypair using the given comparer.");
            }
        }

        private class Executor
        {
            public IEqualityComparer<TKey> Comparer;
            public Func<IDictionary<TKey, TValue>> Creator;
            public TKey ExcludedKey;
            public TKey[] ConflictingKeys;
            public TKey[] NonConflictingKeys;
            public bool ThrowOnKeyNotFound;
            public TValue[] Values;

            private IEnumerable<KeyValuePair<TKey, TValue>> MakeKeyValuePairs()
            {
                return MakeKeyValuePairs(false /* includeConflictingKeys */);
            }

            private IEnumerable<KeyValuePair<TKey, TValue>> MakeKeyValuePairs(bool includeConflictingKeys)
            {
                for (int i = 0; i < NonConflictingKeys.Length; i++)
                {
                    TKey key = NonConflictingKeys[i];
                    TValue value = Values[i];
                    yield return new KeyValuePair<TKey, TValue>(key, value);
                }
                if (includeConflictingKeys)
                {
                    for (int i = 0; i < 2; i++)
                    {
                        TKey key = ConflictingKeys[i];
                        TValue value = Values[NonConflictingKeys.Length + i];
                        yield return new KeyValuePair<TKey, TValue>(key, value);
                    }
                }
            }

            public void TestAdd1()
            {
                // Arrange
                Dictionary<TKey, TValue> controlDictionary = new Dictionary<TKey, TValue>(Comparer);
                IDictionary<TKey, TValue> testDictionary = Creator();

                // Act
                foreach (var entry in MakeKeyValuePairs())
                {
                    controlDictionary.Add(entry.Key, entry.Value);
                    testDictionary.Add(entry.Key, entry.Value);
                }

                // Assert
                VerifyDictionaryEntriesEqual(controlDictionary, testDictionary);
            }

            public void TestAdd1ThrowsArgumentExceptionIfKeyAlreadyInDictionary()
            {
                // Arrange
                IDictionary<TKey, TValue> testDictionary = Creator();

                // Act & assert
                var pairs = MakeKeyValuePairs(true /* includeConflictingKeys */).Skip(NonConflictingKeys.Length).ToArray();
                testDictionary.Add(pairs[0].Key, pairs[1].Value);

                Assert.Throws<ArgumentException>(
                    delegate { testDictionary.Add(pairs[1].Key, pairs[1].Value); },
                    "An item with the same key has already been added."
                    );
            }

            public void TestAdd2()
            {
                // Arrange
                Dictionary<TKey, TValue> controlDictionary = new Dictionary<TKey, TValue>(Comparer);
                IDictionary<TKey, TValue> testDictionary = Creator();

                // Act
                foreach (var entry in MakeKeyValuePairs())
                {
                    ((IDictionary<TKey, TValue>)controlDictionary).Add(entry);
                    testDictionary.Add(entry);
                }

                // Assert
                VerifyDictionaryEntriesEqual(controlDictionary, testDictionary);
            }

            public void TestClear()
            {
                // Arrange
                IDictionary<TKey, TValue> testDictionary = Creator();

                // Act
                foreach (var entry in MakeKeyValuePairs())
                {
                    testDictionary.Add(entry);
                }
                testDictionary.Clear();

                // Assert
                Assert.Empty(testDictionary);
            }

            public void TestCountProperty()
            {
                // Arrange
                Dictionary<TKey, TValue> controlDictionary = new Dictionary<TKey, TValue>(Comparer);
                IDictionary<TKey, TValue> testDictionary = Creator();

                // Act & assert
                foreach (var entry in MakeKeyValuePairs())
                {
                    controlDictionary.Add(entry.Key, entry.Value);
                    testDictionary.Add(entry.Key, entry.Value);
                    Assert.Equal(controlDictionary.Count, testDictionary.Count);
                }
            }

            public void TestContains()
            {
                // Arrange
                IDictionary<TKey, TValue> testDictionary = Creator();

                // Act
                foreach (var entry in MakeKeyValuePairs())
                {
                    testDictionary.Add(entry);
                }

                // Assert
                var shouldBeFound = MakeKeyValuePairs().First();
                var shouldNotBeFound = new KeyValuePair<TKey, TValue>(ExcludedKey, Values[Values.Length - 1]);
                Assert.True(testDictionary.Contains(shouldBeFound), String.Format("Test dictionary should have contained entry for KVP '{0}'.", shouldBeFound));
                Assert.False(testDictionary.Contains(shouldNotBeFound), String.Format("Test dictionary should not have contained entry for KVP '{0}'.", shouldNotBeFound));
            }

            public void TestContainsKey()
            {
                // Arrange
                IDictionary<TKey, TValue> testDictionary = Creator();

                // Act
                foreach (var entry in MakeKeyValuePairs())
                {
                    testDictionary.Add(entry);
                }

                // Assert
                Assert.True(testDictionary.ContainsKey(NonConflictingKeys[0]), String.Format("Test dictionary should have contained entry for key '{0}'.", NonConflictingKeys[0]));
                Assert.False(testDictionary.ContainsKey(ExcludedKey), String.Format("Test dictionary should not have contained entry for key '{0}'.", ExcludedKey));
            }

            public void TestCopyTo()
            {
                // Arrange
                IDictionary<TKey, TValue> controlDictionary = new Dictionary<TKey, TValue>(Comparer);
                IDictionary<TKey, TValue> testDictionary = Creator();

                foreach (var entry in MakeKeyValuePairs())
                {
                    controlDictionary.Add(entry.Key, entry.Value);
                    testDictionary.Add(entry.Key, entry.Value);
                }
                KeyValuePair<TKey, TValue>[] testKvps = new KeyValuePair<TKey, TValue>[testDictionary.Count + 2];

                // Act
                testDictionary.CopyTo(testKvps, 2);

                // Assert
                for (int i = 0; i < 2; i++)
                {
                    var defaultValue = default(KeyValuePair<TKey, TValue>);
                    var entry = testKvps[i];
                    Assert.Equal(defaultValue, entry);
                }
                for (int i = 2; i < testKvps.Length; i++)
                {
                    var entry = testKvps[i];
                    Assert.True(controlDictionary.Contains(entry), String.Format("The value '{0}' wasn't present in the control dictionary.", entry));
                    controlDictionary.Remove(entry);
                }

                Assert.Empty(controlDictionary);
            }

            public void TestGetEnumerator()
            {
                // Arrange
                Dictionary<TKey, TValue> controlDictionary = new Dictionary<TKey, TValue>(Comparer);
                IDictionary<TKey, TValue> testDictionary = Creator();

                foreach (var entry in MakeKeyValuePairs())
                {
                    controlDictionary.Add(entry.Key, entry.Value);
                    testDictionary.Add(entry.Key, entry.Value);
                }

                IEnumerable testDictionaryAsEnumerable = (IEnumerable)testDictionary;

                // Act
                Dictionary<TKey, TValue> newTestDictionary = new Dictionary<TKey, TValue>(Comparer);
                foreach (object entry in testDictionaryAsEnumerable)
                {
                    var kvp = Assert.IsType<KeyValuePair<TKey, TValue>>(entry);
                    newTestDictionary.Add(kvp.Key, kvp.Value);
                }

                // Assert
                VerifyDictionaryEntriesEqual(controlDictionary, newTestDictionary);
            }

            public void TestGetEnumeratorGeneric()
            {
                // Arrange
                Dictionary<TKey, TValue> controlDictionary = new Dictionary<TKey, TValue>(Comparer);
                IDictionary<TKey, TValue> testDictionary = Creator();

                foreach (var entry in MakeKeyValuePairs())
                {
                    controlDictionary.Add(entry.Key, entry.Value);
                    testDictionary.Add(entry.Key, entry.Value);
                }

                // Act & assert
                VerifyDictionaryEntriesEqual(controlDictionary, testDictionary);
            }

            public void TestIsReadOnlyProperty()
            {
                // Arrange
                IDictionary<TKey, TValue> testDictionary = Creator();

                // Act & assert
                Assert.False(testDictionary.IsReadOnly, "Dictionary should not be read only.");
            }

            public void TestItemProperty()
            {
                // Arrange
                Dictionary<TKey, TValue> controlDictionary = new Dictionary<TKey, TValue>(Comparer);
                IDictionary<TKey, TValue> testDictionary = Creator();

                var shouldBeFound = MakeKeyValuePairs().First();
                var shouldNotBeFound = new KeyValuePair<TKey, TValue>(ExcludedKey, Values[Values.Length - 1]);

                // Act & assert
                foreach (var entry in MakeKeyValuePairs())
                {
                    controlDictionary.Add(entry.Key, entry.Value);
                    testDictionary[entry.Key] = entry.Value;
                }
                VerifyDictionaryEntriesEqual(controlDictionary, testDictionary);

                TValue value = testDictionary[shouldBeFound.Key];
                Assert.Equal(shouldBeFound.Value, value);

                if (ThrowOnKeyNotFound)
                {
                    Assert.Throws<KeyNotFoundException>(
                        delegate { TValue valueNotFound = testDictionary[shouldNotBeFound.Key]; }, allowDerivedExceptions: true);
                }
                else
                {
                    TValue valueNotFound = testDictionary[shouldNotBeFound.Key];
                    Assert.Equal(default(TValue), valueNotFound); // Should not throw
                }
            }

            public void TestKeysProperty()
            {
                // Arrange
                Dictionary<TKey, TValue> controlDictionary = new Dictionary<TKey, TValue>(Comparer);
                IDictionary<TKey, TValue> testDictionary = Creator();

                foreach (var entry in MakeKeyValuePairs())
                {
                    controlDictionary.Add(entry.Key, entry.Value);
                    testDictionary.Add(entry.Key, entry.Value);
                }

                // Act
                HashSet<TKey> controlKeys = new HashSet<TKey>(controlDictionary.Keys, Comparer);
                HashSet<TKey> testKeys = new HashSet<TKey>(testDictionary.Keys, Comparer);

                // Assert
                Assert.True(controlKeys.SetEquals(testKeys), "Control dictionary and test dictionary key sets were not equal.");
            }

            public void TestRemove1()
            {
                // Arrange
                Dictionary<TKey, TValue> controlDictionary = new Dictionary<TKey, TValue>(Comparer);
                IDictionary<TKey, TValue> testDictionary = Creator();

                foreach (var entry in MakeKeyValuePairs())
                {
                    controlDictionary.Add(entry.Key, entry.Value);
                    testDictionary.Add(entry.Key, entry.Value);
                }

                // Act
                bool removalSuccess = testDictionary.Remove(NonConflictingKeys[0]);
                bool removalFailure = testDictionary.Remove(ExcludedKey);

                // Assert
                Assert.True(removalSuccess, "Remove() should return true if the key was removed.");
                Assert.False(removalFailure, "Remove() should return false if the key was not removed.");

                controlDictionary.Remove(NonConflictingKeys[0]);
                VerifyDictionaryEntriesEqual(controlDictionary, testDictionary);
            }

            public void TestRemove2()
            {
                // Arrange
                Dictionary<TKey, TValue> controlDictionary = new Dictionary<TKey, TValue>(Comparer);
                IDictionary<TKey, TValue> testDictionary = Creator();

                foreach (var entry in MakeKeyValuePairs())
                {
                    ((IDictionary<TKey, TValue>)controlDictionary).Add(entry);
                    testDictionary.Add(entry);
                }

                // Act
                var shouldBeFound = MakeKeyValuePairs().First();
                var shouldNotBeFound = new KeyValuePair<TKey, TValue>(ExcludedKey, Values[Values.Length - 1]);
                bool removalSuccess = testDictionary.Remove(shouldBeFound);
                bool removalFailure = testDictionary.Remove(shouldNotBeFound);

                // Assert
                Assert.True(removalSuccess, "Remove() should return true if the key was removed.");
                Assert.False(removalFailure, "Remove() should return false if the key was not removed.");

                ((IDictionary<TKey, TValue>)controlDictionary).Remove(shouldBeFound);
                VerifyDictionaryEntriesEqual(controlDictionary, testDictionary);
            }

            public void TestTryGetValue()
            {
                // Arrange
                Dictionary<TKey, TValue> controlDictionary = new Dictionary<TKey, TValue>(Comparer);
                IDictionary<TKey, TValue> testDictionary = Creator();

                foreach (var entry in MakeKeyValuePairs())
                {
                    controlDictionary.Add(entry.Key, entry.Value);
                    testDictionary.Add(entry.Key, entry.Value);
                }

                var shouldBeFound = MakeKeyValuePairs().First();
                var shouldNotBeFound = new KeyValuePair<TKey, TValue>(ExcludedKey, Values[Values.Length - 1]);

                // Act
                TValue value1;
                bool returned1 = testDictionary.TryGetValue(shouldBeFound.Key, out value1);
                TValue value2;
                bool returned2 = testDictionary.TryGetValue(shouldNotBeFound.Key, out value2);

                // Assert
                Assert.True(returned1, String.Format("The entry '{0}' should have been found.", shouldBeFound));
                Assert.Equal(shouldBeFound.Value, value1);
                Assert.False(returned2, String.Format("The entry '{0}' should not have been found.", shouldNotBeFound));
                Assert.Equal(default(TValue), value2);
            }

            public void TestValuesProperty()
            {
                // Arrange
                Dictionary<TKey, TValue> controlDictionary = new Dictionary<TKey, TValue>(Comparer);
                IDictionary<TKey, TValue> testDictionary = Creator();

                foreach (var entry in MakeKeyValuePairs())
                {
                    controlDictionary.Add(entry.Key, entry.Value);
                    testDictionary.Add(entry.Key, entry.Value);
                }

                // Act
                List<TValue> controlValues = controlDictionary.Values.ToList();
                List<TValue> testValues = testDictionary.Values.ToList();

                // Assert
                foreach (var entry in controlValues)
                {
                    Assert.True(testValues.Contains(entry), String.Format("Test dictionary did not contain value '{0}'.", entry));
                }
                foreach (var entry in testValues)
                {
                    Assert.True(controlValues.Contains(entry), String.Format("Control dictionary did not contain value '{0}'.", entry));
                }
            }

            private void VerifyDictionaryEntriesEqual(Dictionary<TKey, TValue> controlDictionary, IDictionary<TKey, TValue> testDictionary)
            {
                Assert.Equal(controlDictionary.Count, testDictionary.Count);

                Dictionary<TKey, TValue> clonedControlDictionary = new Dictionary<TKey, TValue>(controlDictionary, controlDictionary.Comparer);

                foreach (var entry in testDictionary)
                {
                    var key = entry.Key;
                    Assert.True(clonedControlDictionary.ContainsKey(entry.Key), String.Format("Control dictionary did not contain key '{0}'.", key));
                    clonedControlDictionary.Remove(key);
                }

                foreach (var entry in clonedControlDictionary)
                {
                    var key = entry.Key;
                    Assert.True(false, String.Format("Test dictionary did not contain key '{0}'.", key));
                }
            }
        }
    }
}