summaryrefslogtreecommitdiff
path: root/external/aspnetwebstack/test/System.Json.Test.Integration/JsonValueUsageTest.cs
blob: 2d44675749c10f1b291d9f5ba3526361bb20365b (plain)
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
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.

using System.Collections.Generic;
using System.Linq;
using Xunit;

namespace System.Json
{
    /// <summary>
    /// Test class for some scenario usages for <see cref="JsonValue"/> types.
    /// </summary>
    public class JsonValueUsageTest
    {
        /// <summary>
        /// Test for consuming <see cref="JsonValue"/> objects in a Linq query.
        /// </summary>
        [Fact]
        public void JLinqSimpleCreationQueryTest()
        {
            int seed = 1;
            Random rndGen = new Random(seed);

            JsonArray sourceJson = new JsonArray
            {
                new JsonObject { { "Name", "Alex" }, { "Age", 18 }, { "Birthday", PrimitiveCreator.CreateInstanceOfDateTime(rndGen) } },
                new JsonObject { { "Name", "Joe" }, { "Age", 19 }, { "Birthday", DateTime.MinValue } },
                new JsonObject { { "Name", "Chris" }, { "Age", 20 }, { "Birthday", DateTime.Now } },
                new JsonObject { { "Name", "Jeff" }, { "Age", 21 }, { "Birthday", DateTime.MaxValue } },
                new JsonObject { { "Name", "Carlos" }, { "Age", 22 }, { "Birthday", PrimitiveCreator.CreateInstanceOfDateTime(rndGen) } },
                new JsonObject { { "Name", "Mohammad" }, { "Age", 23 }, { "Birthday", PrimitiveCreator.CreateInstanceOfDateTime(rndGen) } },
                new JsonObject { { "Name", "Sara" }, { "Age", 24 }, { "Birthday", new DateTime(1998, 3, 20) } },
                new JsonObject { { "Name", "Tomasz" }, { "Age", 25 }, { "Birthday", PrimitiveCreator.CreateInstanceOfDateTime(rndGen) } },
                new JsonObject { { "Name", "Suwat" }, { "Age", 26 }, { "Birthday", new DateTime(1500, 12, 20) } },
                new JsonObject { { "Name", "Eugene" }, { "Age", 27 }, { "Birthday", PrimitiveCreator.CreateInstanceOfDateTime(rndGen) } }
            };

            var adults = from JsonValue adult in sourceJson
                         where (int)adult["Age"] > 21
                         select adult;
            Log.Info("Team contains: ");
            int count = 0;
            foreach (JsonValue adult in adults)
            {
                count++;
                Log.Info((string)adult["Name"]);
            }

            Assert.Equal(count, 6);
        }

        /// <summary>
        /// Test for consuming <see cref="JsonValue"/> arrays in a Linq query.
        /// </summary>
        [Fact]
        public void JLinqSimpleQueryTest()
        {
            JsonArray sourceJson = this.CreateArrayOfPeople();

            var adults = from JsonValue adult in sourceJson
                         where (int)adult["Age"] > 21
                         select adult;
            Log.Info("Team contains: ");
            int count = 0;
            foreach (JsonValue adult in adults)
            {
                count++;
                Log.Info((string)adult["Name"]);
            }

            Assert.Equal(count, 6);
        }

        /// <summary>
        /// Test for consuming deep <see cref="JsonValue"/> objects in a Linq query.
        /// </summary>
        [Fact]
        public void JLinqDeepQueryTest()
        {
            int seed = 1;

            JsonArray mixedOrderJsonObj;
            JsonArray myJsonObj = SpecialJsonValueHelper.CreateDeepLevelJsonValuePair(seed, out mixedOrderJsonObj);

            if (myJsonObj != null && mixedOrderJsonObj != null)
            {
                bool retValue = true;

                var dict = new Dictionary<string, int>
                {
                    { "myArray", 1 }, 
                    { "myArrayLevel2", 2 }, 
                    { "myArrayLevel3", 3 }, 
                    { "myArrayLevel4", 4 }, 
                    { "myArrayLevel5", 5 }, 
                    { "myArrayLevel6", 6 }, 
                    { "myArrayLevel7", 7 },
                    { "myBool", 8 }, 
                    { "myByte", 9 }, 
                    { "myDatetime", 10 },
                    { "myDateTimeOffset", 11 },
                    { "myDecimal", 12 },
                    { "myDouble", 13 }, 
                    { "myInt16", 14 }, 
                    { "myInt32", 15 }, 
                    { "myInt64", 16 }, 
                    { "mySByte", 17 }, 
                    { "mySingle", 18 },
                    { "myString", 19 },
                    { "myUInt16", 20 },
                    { "myUInt32", 21 },
                    { "myUInt64", 22 }
                };

                foreach (string name in dict.Keys)
                {
                    if (!this.InternalVerificationViaLinqQuery(myJsonObj, name, dict[name]))
                    {
                        retValue = false;
                    }

                    if (!this.InternalVerificationViaLinqQuery(mixedOrderJsonObj, name, dict[name]))
                    {
                        retValue = false;
                    }

                    if (!this.CrossJsonValueVerificationOnNameViaLinqQuery(myJsonObj, mixedOrderJsonObj, name))
                    {
                        retValue = false;
                    }

                    if (!this.CrossJsonValueVerificationOnIndexViaLinqQuery(myJsonObj, mixedOrderJsonObj, dict[name]))
                    {
                        retValue = false;
                    }
                }

                Assert.True(retValue, "The JsonValue did not verify as expected!");
            }
            else
            {
                Assert.True(false, "Failed to create the pair of JsonValues!");
            }
        }

        /// <summary>
        /// Test for consuming <see cref="JsonValue"/> objects in a Linq query using the dynamic notation.
        /// </summary>
        [Fact]
        public void LinqToDynamicJsonArrayTest()
        {
            JsonValue people = this.CreateArrayOfPeople();

            var match = from person in people select person;
            Assert.True(match.Count() == people.Count, "IEnumerable returned different number of elements that JsonArray contains");

            int sum = 0;
            foreach (KeyValuePair<string, JsonValue> kv in match)
            {
                sum += Int32.Parse(kv.Key);
            }

            Assert.True(sum == (people.Count * (people.Count - 1) / 2), "Not all elements of the array were enumerated exactly once");

            match = from person in people
                    where person.Value.AsDynamic().Name.ReadAs<string>().StartsWith("S")
                        && person.Value.AsDynamic().Age.ReadAs<int>() > 20
                    select person;
            Assert.True(match.Count() == 2, "Number of matches was expected to be 2 but was " + match.Count());
        }

        /// <summary>
        /// Test for consuming <see cref="JsonValue"/> objects in a Linq query.
        /// </summary>
        [Fact]
        public void LinqToJsonObjectTest()
        {
            JsonValue person = this.CreateArrayOfPeople()[0];
            var match = from nameValue in person select nameValue;
            Assert.True(match.Count() == 3, "IEnumerable of JsonObject returned a different number of elements than there are name value pairs in the JsonObject" + match.Count());

            List<string> missingNames = new List<string>(new string[] { "Name", "Age", "Birthday" });
            foreach (KeyValuePair<string, JsonValue> kv in match)
            {
                Assert.Equal(person[kv.Key], kv.Value);
                missingNames.Remove(kv.Key);
            }

            Assert.True(missingNames.Count == 0, "Not all JsonObject properties were present in the enumeration");
        }

        /// <summary>
        /// Test for consuming <see cref="JsonValue"/> objects in a Linq query.
        /// </summary>
        [Fact]
        public void LinqToJsonObjectAsAssociativeArrayTest()
        {
            JsonValue gameScores = new JsonObject(new Dictionary<string, JsonValue>()
                {
                    { "tomek", 12 },
                    { "suwat", 27 },
                    { "carlos", 127 },
                    { "miguel", 57 },
                    { "henrik", 2 },
                    { "joe", 15 }
                });

            var match = from score in gameScores
                        where score.Key.Contains("o") && score.Value.ReadAs<int>() > 100
                        select score;
            Assert.True(match.Count() == 1, "Incorrect number of matching game scores");
        }

        /// <summary>
        /// Test for consuming <see cref="JsonPrimitive"/> objects in a Linq query.
        /// </summary>
        [Fact]
        public void LinqToJsonPrimitiveTest()
        {
            JsonValue primitive = 12;

            var match = from m in primitive select m;
            KeyValuePair<string, JsonValue>[] kv = match.ToArray();
            Assert.True(kv.Length == 0);
        }

        /// <summary>
        /// Test for consuming <see cref="JsonValue"/> objects with <see cref="JsonType">JsonType.Default</see> in a Linq query.
        /// </summary>
        [Fact]
        public void LinqToJsonUndefinedTest()
        {
            JsonValue primitive = 12;

            var match = from m in primitive.ValueOrDefault("idontexist")
                        select m;
            Assert.True(match.Count() == 0);
        }

        /// <summary>
        /// Test for consuming calling <see cref="JsonValue.ReadAs{T}(T)"/> in a Linq query.
        /// </summary>
        [Fact]
        public void LinqToDynamicJsonUndefinedWithFallbackTest()
        {
            JsonValue people = this.CreateArrayOfPeople();

            var match = from person in people
                        where person.Value.AsDynamic().IDontExist.IAlsoDontExist.ReadAs<int>(5) > 2
                        select person;
            Assert.True(match.Count() == people.Count, "Number of matches was expected to be " + people.Count + " but was " + match.Count());

            match = from person in people
                    where person.Value.AsDynamic().Age.ReadAs<int>(1) < 21
                    select person;
            Assert.True(match.Count() == 3);
        }

        private JsonArray CreateArrayOfPeople()
        {
            int seed = 1;
            Random rndGen = new Random(seed);
            return new JsonArray(new List<JsonValue>()
            { 
                new JsonObject(new Dictionary<string, JsonValue>()
                {
                    { "Name", "Alex" },
                    { "Age", 18 },
                    { "Birthday", PrimitiveCreator.CreateInstanceOfDateTime(rndGen) }
                }),
                new JsonObject(new Dictionary<string, JsonValue>()
                {
                    { "Name", "Joe" },
                    { "Age", 19 },
                    { "Birthday", DateTime.MinValue }
                }),
                new JsonObject(new Dictionary<string, JsonValue>()
                {
                    { "Name", "Chris" },
                    { "Age", 20 },
                    { "Birthday", DateTime.Now }
                }),
                new JsonObject(new Dictionary<string, JsonValue>()
                {
                    { "Name", "Jeff" },
                    { "Age", 21 },
                    { "Birthday", DateTime.MaxValue }
                }),
                new JsonObject(new Dictionary<string, JsonValue>()
                {
                    { "Name", "Carlos" },
                    { "Age", 22 },
                    { "Birthday", PrimitiveCreator.CreateInstanceOfDateTime(rndGen) }
                }),
                new JsonObject(new Dictionary<string, JsonValue>()
                {
                    { "Name", "Mohammad" },
                    { "Age", 23 },
                    { "Birthday", PrimitiveCreator.CreateInstanceOfDateTime(rndGen) }
                }),
                new JsonObject(new Dictionary<string, JsonValue>()
                {
                    { "Name", "Sara" },
                    { "Age", 24 },
                    { "Birthday", new DateTime(1998, 3, 20) }
                }),
                new JsonObject(new Dictionary<string, JsonValue>()
                {
                    { "Name", "Tomasz" },
                    { "Age", 25 },
                    { "Birthday", PrimitiveCreator.CreateInstanceOfDateTime(rndGen) }
                }),
                new JsonObject(new Dictionary<string, JsonValue>()
                {
                    { "Name", "Suwat" },
                    { "Age", 26 },
                    { "Birthday", new DateTime(1500, 12, 20) }
                }),
                new JsonObject(new Dictionary<string, JsonValue>()
                {
                    { "Name", "Eugene" },
                    { "Age", 27 },
                    { "Birthday", PrimitiveCreator.CreateInstanceOfDateTime(rndGen) }
                })
            });
        }

        private bool InternalVerificationViaLinqQuery(JsonArray sourceJson, string name, int index)
        {
            var itemsByName = from JsonValue itemByName in sourceJson
                              where (itemByName != null && (string)itemByName["Name"] == name)
                              select itemByName;
            int countByName = 0;
            foreach (JsonValue a in itemsByName)
            {
                countByName++;
            }

            Log.Info("Collection contains: " + countByName + " item By Name " + name);

            var itemsByIndex = from JsonValue itemByIndex in sourceJson
                               where (itemByIndex != null && (int)itemByIndex["Index"] == index)
                               select itemByIndex;
            int countByIndex = 0;
            foreach (JsonValue a in itemsByIndex)
            {
                countByIndex++;
            }

            Log.Info("Collection contains: " + countByIndex + " item By Index " + index);

            if (countByIndex != countByName)
            {
                Log.Info("Count by Name = " + countByName + "; Count by Index = " + countByIndex);
                Log.Info("The number of items matching the provided Name does NOT equal to that matching the provided Index, The two JsonValues are not equal!");
                return false;
            }
            else
            {
                return true;
            }
        }

        private bool CrossJsonValueVerificationOnNameViaLinqQuery(JsonArray sourceJson, JsonArray newJson, string name)
        {
            var itemsByName = from JsonValue itemByName in sourceJson
                              where (itemByName != null && (string)itemByName["Name"] == name)
                              select itemByName;
            int countByName = 0;
            foreach (JsonValue a in itemsByName)
            {
                countByName++;
            }

            Log.Info("Original Collection contains: " + countByName + " item By Name " + name);

            var newItemsByName = from JsonValue newItemByName in newJson
                                 where (newItemByName != null && (string)newItemByName["Name"] == name)
                                 select newItemByName;
            int newcountByName = 0;
            foreach (JsonValue a in newItemsByName)
            {
                newcountByName++;
            }

            Log.Info("New Collection contains: " + newcountByName + " item By Name " + name);

            if (countByName != newcountByName)
            {
                Log.Info("Count by Original JsonValue = " + countByName + "; Count by New JsonValue = " + newcountByName);
                Log.Info("The number of items matching the provided Name does NOT equal between these two JsonValues!");
                return false;
            }
            else
            {
                return true;
            }
        }

        private bool CrossJsonValueVerificationOnIndexViaLinqQuery(JsonArray sourceJson, JsonArray newJson, int index)
        {
            var itemsByIndex = from JsonValue itemByIndex in sourceJson
                               where (itemByIndex != null && (int)itemByIndex["Index"] == index)
                               select itemByIndex;
            int countByIndex = 0;
            foreach (JsonValue a in itemsByIndex)
            {
                countByIndex++;
            }

            Log.Info("Original Collection contains: " + countByIndex + " item By Index " + index);

            var newItemsByIndex = from JsonValue newItemByIndex in newJson
                                  where (newItemByIndex != null && (int)newItemByIndex["Index"] == index)
                                  select newItemByIndex;
            int newcountByIndex = 0;
            foreach (JsonValue a in newItemsByIndex)
            {
                newcountByIndex++;
            }

            Log.Info("New Collection contains: " + newcountByIndex + " item By Index " + index);

            if (countByIndex != newcountByIndex)
            {
                Log.Info("Count by Original JsonValue = " + countByIndex + "; Count by New JsonValue = " + newcountByIndex);
                Log.Info("The number of items matching the provided Index does NOT equal between these two JsonValues!");
                return false;
            }
            else
            {
                return true;
            }
        }
    }
}